Sometimes in your code you may need to create values that should never change but remain static (unchangeable). These values are called constants in Java
Introduction to Constants
To create constants in Java, we use the final
keyword to represent values that will not change. By convention, the variable name for a constant is normally written in all caps. The syntax for writing a constant in Java is final <data type> <variableName> = <value>;
If you try to reassign a value to the constant later in you code you will run into an error.
Because constants are normally used by various methods of a class (if you don't understand what methods are, check some of my earlier blogs), you may need to declare them as class variables so they can be used by all methods of the class.
what does this mean?
Anytime you create a variable inside a method, it is mostly only accessible by the method alone and no other method, though they may belong to the same class. Hence, declaring something as a class variable will. make it accessible to all and since they are being shared by all methods of a class, you might want the variable content to remain fixed, hence you declare them as constant variables.
But how is this done?
public class proto{
public final int num1 = 1000; // declaring a constant making it acessible to all within the class
public static void main(String [] args){
System.out.println("The public makes it accessible to all methods within that class");
}
}
Note: If you try to declare a variable as public in a method it still wouldn't make it accessible to all otehr methods outside its scope. Hence they must be made public at the class level so all methods fall within its scope.
Enumerated Type In Java
What is an Enum?
An enum (short for “enumerated type”) is a special kind of variable in Java that can only have a fixed set of values.
Think of it like a list of options you cannot go outside of.
Example: Pizza Sizes
Imagine you sell pizzas, and there are only four sizes:
SMALL
MEDIUM
LARGE
EXTRA_LARGE
Instead of using numbers like 1, 2, 3, 4 or letters like S, M, L, X (which can be confusing), you can define an enum:
enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE
}
Now, any variable of type Size can only hold one of these four values.
Using the Enum
public class EnumExample {
public static void main(String[] args) {
Size s = Size.MEDIUM; // choose a size
System.out.println("Selected size: " + s);
}
}
What happens here:
Size s declares a variable s that can only be SMALL, MEDIUM, LARGE, or EXTRA_LARGE.
Size.MEDIUM assigns the MEDIUM size to s.
You print it out: Selected size: MEDIUM.
Why Enums are Useful
Type-safe: You cannot assign random numbers or words to a Size variable.
Fewer mistakes: You won’t accidentally use 5 or Extra by mistake.
Advanced: Enums can even have their own methods, fields, and constructors for more complex behavior.
Simple analogy:
Enums are like a menu: you can only pick items that exist on the menu, not make up your own
Top comments (0)