Concept
What shorthand and read-only options are available for Java variables?
ComputerScienceOne / Declaration & Assignment
"For brevity, Java allows you to declare a variable and immediately assign it a value on the same line. So these two code blocks could have been more compactly written as:\n\n1 int numUnits = 42;\n\n2 double costPerUnit = 32.79;\n\n3 char firstInitial = 'C';\n\n4 boolean isStudent = true;\n\nAs another shorthand, we can declare multiple variables on the same line by delimiting them with a comma. However, they must be of the same type. We can also use an assignment with them.\n\n1 int numOrders, numUnits = 42, numCustomers = 10, numItems;\n\n2 double costPerUnit = 32.79, salesTaxRate;\n\nAnother useful keyword is final. Though it has several uses, when applied to a variable declaration, it makes it a read-only variable. After a value has been assigned to a final variable, its value cannot be changed.\n\n1 final int secret = 42;\n\n2 final double salesTaxRate = 0.075;\n\nAny attempt to reassign the values of final variables will result in a compiler error. Instance variables, that is variables declared as part of an object do have default values. For objects, the default is null, for all numeric types, zero is the default value. For the boolean type, false is the default, and the default char value is \\0, the null-terminating character (zero in the ASCII table)."
Related Ideas
- What primitive types are available in Java?ComputerScienceOne · Declaration & Assignment
- What are the basic syntax rules of Java?ComputerScienceOne · Basic Syntax Rules
- How do you declare variables in C?ComputerScienceOne · Declaration & Assignment
- How are String variables declared and reassigned in Java?ComputerScienceOne · Basics
- What happens when you reassign a const variable in C?ComputerScienceOne · Operators
- How does Java handle default and multiple constructors?ComputerScienceOne · Constructors
- Why are getters, setters, and immutable member variables useful?ComputerScienceOne · Constructors
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods