Concept

How are variables declared and assigned in Java?

ComputerScienceOne / Declaration & Assignment

"Java is a statically typed language meaning that all variables must be declared before you can use them or refer to them. In addition, when declaring a variable, you must specify both its type and its identifier. For example:\n\n1 int numUnits;\n\n2 double costPerUnit;\n\n3 char firstInitial;\n\n4 boolean isStudent;\n\nEach declaration specifies the variable’s type followed by the identifier and ending with a semicolon. The identifier rules are fairly standard: a name can consist of lowercase and uppercase alphabetic characters, numbers, and underscores but may not begin with a numeric character. We adopt the modern camelCasing naming convention for variables in our code. In general, variables must be assigned a value before you can use them in an expression. You do not have to immediately assign a value when you declare them, though it is good practice, but some value must be assigned before they can be used or the compiler will issue an error. The assignment operator is a single equal sign, = and is a right-to-left assignment. That is, the variable that we wish to assign the value to appears on the left-hand-side while the value (literal, variable or expression) is on the right-hand-side. Using our variables from before, we can assign them values:\n\n1 numUnits = 42;\n\n2 costPerUnit = 32.79;\n\n3 firstInitial = 'C';\n\n4 isStudent = true;"

Related Ideas

How are variables declared and assigned in Java? | ComputerScienceOne | Bifalgorithm | Bifalgorithm