Tools: Variables and Constants

Tools: Variables and Constants

Source: Dev.to

Declaring Variables ## Initializing Variables ## Constants ## Enumerated Types As in every programming language, variables are used to store values. Constants are variables whose values don't change. In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. Here are some examples: double salary; int vacationDays; long earthPopulation; boolean done; Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement, which must end in a semicolon. The identifier for a variable name (as well as for other names) is made up of letters, digits, currency symbols, and “punctuation connectors.” The first character cannot be a digit. Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. Letter case is significant: main and Main are distinct identifiers. The length of an identifier is essentially unlimited. The terms “letter,” “digit,” and “currency symbol” are much broader in Java than in most languages. A letter is any Unicode character that denotes a letter in a language. For example, German users can use umlauts such as ä in variable names; Greek speakers could use a π. Similarly, digits are 0–9 and any Unicode characters that denote a digit. Currency symbols are $, €, ¥, and so on. Punctuation connectors include the underscore character , a “wavy low line” ﹏, and a few others. In practice, most programmers stick to _A-Z, a-z, 0-9, and the underscore _. If you are really curious as to what Unicode characters can be used in identifiers, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check. Even though $ is a valid character in an identifier, you should not use it in your own code. It is intended for names that are generated by the Java compiler and other tools. You also cannot use a Java keyword such as class as a variable name. Underscores can be parts of identifiers. This is common for constant names, such as Double.POSITIVE_INFINITY. However, a single underscore _ is a reserved word. As of Java 21, a single underscore _ denotes a variable that is syntactially required but never used. You can declare multiple variables on a single line: int i, j; // both are integers I don’t recommend this style. If you declare each variable separately, your programs are easier to read. As you saw, names are case sensitive, for example, hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name as the type, for example Box box; // "Box" is the type and "box" is the variable name Other programmers prefer to use an “a” prefix for the variable: After you declare a variable, you must explicitly initialize it by means of an assignment statement, you can never use the value of an uninitialized variable. For example, the Java compiler flags the following sequence of statements as an error: int vacationDays; System.out.println(vacationDays); // ERROR--variable not initialized You assign to a previously declared variable by using the variable name on the left, an equal sign (=), and then some Java expression with an appropriate value on the right. int vacationDays; vacationDays = 12; You can both declare and initialize a variable on the same line. For example: int vacationDays = 12; Finally, in Java you can put declarations anywhere in your code. For example, the following is valid code in Java: double salary = 65000.0; System.out.println(salary); int vacationDays = 12; // OK to declare a variable here In Java, it is considered good style to declare variables as closely as possible to the point where they are first used. You do not need to declare the types of local variables if they can be inferred from the initial value. Simply use the keyword var instead of the type: var vacationDays = 12; // vacationDays is an int var greeting = "Hello"; // greeting is a String This is not too important for number and string types, but, as you will see in the next chapter, this feature can make the declaration of objects less verbose. C and C++ distinguish between the declaration and definition of a variable. For example, is a definition, whereas is a declaration. In Java, no declarations are separate from definitions. In Java, you use the keyword final to denote a constant. For example: The keyword final indicates that you can assign to the variable once, and then its value is set once and for all. It is customary to name constants in all uppercase. It is probably more common in Java to create a constant so it's available to multiple methods inside a single class. These are usually called class constants. Set up a class constant with the keywords static final. Here is an example of using a class constant: Note that the definition of the class constant appears outside the main method. Thus, the constant can also be used in other methods of the same class. Furthermore, if the constant is declared, as in this example, public, methods of other classes can also use it, in our example, as Constants2.CM_PER_INCH. Some coding style guides state that uppercase letters should only be used for static final variables. If you need to follow such a style guide, and you have a local constant, decide what is more important to you, the fact that it is local (and lowercase), or that it is visibly a constant (static and uppercase). const is a Java keyword, but it is not currently used for anything. You must use final for a constant. Sometimes, a variable should only hold a restricted set of values. For example, you may sell clothes or pizza in four sizes: small, medium, large, and extra large. Of course, you could encode these sizes as integers 1, 2, 3, 4 or characters S, M, L, and X. But that is an error-prone setup. It is too easy for a variable to hold a wrong value (such as 0 or m). You can define your own enumerated type whenever such a situation arises. An enumerated type has a finite number of named values. For example, enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE }; Now you can declare variables of this type: Size s = Size.MEDIUM; A variable of type Size can hold only one of the values listed in the type declaration, or the special value null that indicates that the variable is not set to any value at all. Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse CODE_BLOCK: public class Constants { public static void main(String[] args) { final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } } Enter fullscreen mode Exit fullscreen mode CODE_BLOCK: public class Constants { public static void main(String[] args) { final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } } CODE_BLOCK: public class Constants { public static void main(String[] args) { final double CM_PER_INCH = 2.54; double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } } CODE_BLOCK: public class Constants2 { public static final double CM_PER_INCH = 2.54; public static void main(String[] args) { double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } } Enter fullscreen mode Exit fullscreen mode CODE_BLOCK: public class Constants2 { public static final double CM_PER_INCH = 2.54; public static void main(String[] args) { double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } } CODE_BLOCK: public class Constants2 { public static final double CM_PER_INCH = 2.54; public static void main(String[] args) { double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } }