Java 101: Foundations

Java 101: Elementary Java language features

Using comments, identifiers, types, literals, and variables in your Java programs

1 2 3 Page 3
Page 3 of 3

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 the following 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.

The above variables need to be initialized before they are used. You can 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.

Alternatively, you can initialize a variable after its declaration by omitting the type, as follows:

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 }};

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.

Earlier, I mentioned that Java supports Unicode. In the next section, we'll find out how this support can affect source code and compilation.

Experimenting with Java's Unicode support

Java program listings are typically stored in files where they are encoded according to the native platform's character encoding. For example, my Windows 7 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. For instance, 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;
      System.out.println(π);
   }
}

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 and select Unicode, which corresponds to UTF-16 (little-endian order), from the Encoding drop-down list of encoding options. Then press the Save button.

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:

3.14159

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;
      System.out.println(\u03c0);
   }
}

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

In conclusion

Java has many fundamental language features that you should grasp before getting to the really interesting parts of the language. In this article, you learned how Unicode, comments, identifiers, types, literals, and variables work in Java programs. Next time we'll tackle Java expressions and their operators.

1 2 3 Page 3
Page 3 of 3