Elementary Java language features

How to use identifiers, types, literals, and variables in your Java programs

1 2 3 Page 3
Page 3 of 3

The floating-point types are associated with literals consisting of a non-fractional part, a decimal point, a fractional part, an optional exponent, and either optional double precision floating-point type letter D or d, or a floating-point type letter F or f. Examples of floating-point literals include 2.7818, 0.8D, -57.2E+31, and 3.14159f. If neither D, d, F, nor f is present, the type defaults to double precision floating-point. If D or d is present, the type is also double precision floating-point. However, if F or f is specified, the type is floating-point.

For floating-point types you can insert underscore characters between digits; for example, 1.234_567e+56. You cannot specify a leading underscore (e.g., _1.234) because the compiler would assume that an identifier was being specified. You also cannot specify a trailing underscore (e.g., 1.5_), an underscore on either side of the decimal point (e.g., 2_.3 or 2._3), an underscore before or after the e or E character when an exponent is present (e.g., 1.2_e3 or 1.2E_3), and an underscore on either side of any + or - character that follows e or E (e.g., 2.8e_+2 or 3.1E-_5).

Variables: Storing values in your Java code

Applications manipulate values that are stored in memory. Java's variables feature symbolically represents memory in source code. A variable is a named memory location that stores a value of some type. For a primitive type, the value is stored directly in the variable. For a variable of reference type, a reference is stored in the variable and the object referred to by the reference is stored elsewhere. Variables that store references are often called reference variables.

You must declare a variable before it is used. A variable declaration minimally consists of a type name, optionally followed by a sequence of square bracket pairs, followed by a name, optionally followed by a sequence of square bracket pairs, and terminated with a semicolon character (;). Consider these examples:

int age;             // Declare integer variable age.
float interest_rate; // Declare floating-point variable interest_rate.
String name;         // Declare String variable name.
Car car;             // Declare Car variable car.
char[] text;         // Declare one-dimensional character array variable text.
double[][] temps;    // Declare two-dimensional floating-point array variable temps.

Variables need to be initialized before they are used, and there are two ways to do this. One way is to initialize a variable as part of its declaration:

int age = 25;
float interest_rate = 4.0F;
String name = "Java";
Car car = new Car();
char[] text = { 'J', 'a', 'v', 'a' };
double[][] temps = { { 25.0, 96.2, -32.5 }, { 0.0, 212.0, -41.0 }};

Each initialization requires = followed by a literal, an object-creation expression that begins with new, or an array initializer (for array types only). The array initializer consists of a brace-delimited and comma-separated list of literals and (for multi-dimensional arrays) nested array initializers.

Note that the text example creates a one-dimensional array of characters consisting of four elements. The temps example creates a two-row-by-three-column two-dimensional array of double precision floating-point values. The array initializer specifies two row arrays with each row array containing three column values.

If you prefer, you can initialize a variable after its declaration by omitting the type:

age = 25;
interest_rate = 4.0F;
name = "Java";
car = new Car();
text = { 'J', 'a', 'v', 'a' };
temps = { { 25.0, 96.2, -32.5 }, { 0.0, 212.0, -41.0 }};

Using var to declare local variables

Starting with Java SE 10, there is a simple alternative to declaring and initializing a variable. In certain contexts, you can replace the variable's type name with the var keyword, as follows:

var age = 25;
var interest_rate = 4.0F;
var name = "Java";
var car = new Car();

There are many restrictions on using var. For example, you cannot use var in an array context. See "Finally, Java 10 has var to declare local variables" to learn more about var.

Declaring and initializing variables with jshell

The Java Shell makes it easy to practice with variable declaration and initialization, as you can see in the examples below (note that semicolon terminators aren't required).

jshell> int age
age ==> 0

jshell> float interest_rate = 4.0F
interest_rate ==> 4.0

jshell> var name = "Java"
name ==> "Java"


After declaring a variable, jshell outputs a description of the variable name and its value. If you attempt to declare a variable without a type (or without using var), you'll see an error message:

jshell> foo = 5
|  Error:
|  cannot find symbol
|    symbol:   variable foo
|  foo = 5
|  ^_^


Java Shell lets you redeclare a variable with a different type. For example, let's redeclare age to be of type String and name to be of type int:

jshell> String age
age ==> null

jshell> var name = 1
name ==> 1

Accessing a variable's value

To access a variable's value, specify the variable's name (for primitive types and String), de-reference the object and access a member, or use an array-index notation to identify the element whose value is to be accessed:

System.out.println(age);           // Output: 25
System.out.println(interest_rate); // Output: 4.0
System.out.println(name);          // Output: Java
System.out.println(cat.name());    // Output: Garfield
System.out.println(text[0]);       // Output: J
System.out.println(temps[0][1]);   // Output: 96.2

In order to de-reference an object you must place a period character between the reference variable (cat) and the member (name()). In this case, the name() method is called and its return value is output.

Array access requires a zero-based integer index to be specified for each dimension. For text, only a single index is needed: 0 identifies the first element in this one-dimensional array. For temps, two indexes are required: 0 identifies the first row and 1 identifies the second column in the first row in this two-dimensional array.

You can declare multiple variables in one declaration by separating each variable from its predecessor with a comma, as demonstrated by the following example:

int a, b[], c;

This example declares three variables named a, b, and c. Each variable shares the same type, which happens to be integer. Unlike a and c, which each store one integer value, b[] denotes a one-dimensional array where each element stores an integer. No array is yet associated with b.

Note that the square brackets must appear after the variable name when the array is declared in the same declaration as the other variables. If you place the square brackets before the variable name, as in int a, []b, c;, the compiler reports an error. If you place the square brackets after the type name, as in int[] a, b, c;, all three variables signify one-dimensional arrays of integers.

Compiling Unicode

You've seen various examples of how character encoding works in Java programs. It's also important to understand how Unicode affects Java compilation.

Java program listings are typically stored in files, where they are encoded according to the native platform's character encoding. For example, my Windows 8.1 platform uses Cp1252 as its character encoding. When the JVM starts running, such as when you start the Java-based Java compiler via the javac tool, it tries to obtain this encoding. If the JVM cannot obtain it, the JVM chooses UTF-8 as the default character encoding.

Cp1252 doesn't support many characters beyond the traditional ASCII character set, which can cause problems. As an example, if you attempt to use the Windows notepad editor to save Listing 1, the editor will complain that characters in the Unicode format will be lost. Can you figure out why?

Listing 1. Symbolically naming an identifier (version 1)

class PrintPi
   public static void main(String[] args)
      double π = 3.14159;

The problem is that the above source includes the Greek letter Pi (π) as a variable's name, which causes the editor to balk. Fortunately, we can resolve this issue.

First, try saving Listing 1 to a file named PrintPi.java:

  • From notepad's Save As dialog box, enter PrintPi.java as the file's name.
  • Select Unicode, which corresponds to UTF-16, from the Encoding drop-down list of encoding options.
  • Press Save.

Next, attempt to compile PrintPi.java, as follows:

javac PrintPi.java

In response you'll receive many error messages because the text file's contents were encoded as UTF-16, but javac assumes (on my platform) that the contents were encoded as Cp1252. To fix this problem, we must tell javac that the contents were encoded as UTF-16. We do this by passing the -encoding Unicode option to this program, as follows:

javac -encoding Unicode PrintPi.java

This time, the code compiles without error. When you execute PrintPi.class via java PrintPi, you'll observe the following output:


You can also embed symbols from other alphabets by specifying their Unicode escape sequences without the surrounding quotes. This way, you don't have to specify an encoding when saving a listing or compiling the saved text because the text was encoded according to the native platform's encoding (e.g., Cp1252). For example, Listing 2 replaces π with the \u03c0 Unicode escape sequence for this symbol.

Listing 2. Symbolically naming an identifier (version 2)

class PrintPi
   public static void main(String[] args)
      double \u03c0 = 3.14159;

Compile the source code without the -encoding unicode option (javac PrintPi.java) and run the application as before (java PrintPi). You'll observe identical output.

In conclusion

Java has many fundamental language features that are important to know before getting to the more interesting parts of the language. In this tutorial, you've learned about using identifiers, types, literals, and variables in your Java programs. You also got a quick introduction to documenting your code, and you've explored a common (but solvable) challenge with compiling Unicode.

This story, "Elementary Java language features" was originally published by JavaWorld.

Copyright © 2019 IDG Communications, Inc.

1 2 3 Page 3
Page 3 of 3