Home > SparkCharts > Cs > Java > Java Basics

Java


 
 

Java Basics

 

Types

The type system of a programming language describes the way the language interprets data stored in memory. Type checking in a Java program is done at compile-time to ensure type compatibility; information about data types is also maintained during runtime to facilitate polymorphism. Java has two varieties of types.

Primitive types: Primitive types are irreducible data types, hard-coded into the Java language. They include boolean values, Unicode characters, integers, and floating point numbers. Java has eight implementation-independent primitive types:

  • boolean: true or false

  • char: 16-bit Unicode character

  • byte: 8-bit signed two’s complement integer

  • short: 16-bit signed two’s complement integer

  • int: 32-bit signed two’s complement integer

  • long: 64-bit signed two’s complement integer

  • float: IEEE 754 single-precision floating-point value

  • double: IEEE 754 double-precision floating-point value

Note to C users: In Java, booleans and ints are distinct variable types; they cannot be used interchangeably or cast to one another.

  • Casting primitive types: Since Java is a strongly typed language, data sometimes must be cast from one primitive type (or object) to another. Casts allow the compiler to treat an expression as having the type specified by the cast. An explicit cast, one written directly by the programmer, has the following syntax, with the variable to be cast preceded by the desired cast type, in parentheses:

    • (type) variableName

    • type variable = (type) expression;

  • Java will make widening casts—casts from one type to another type that is at least as large as the first— automatically when necessary, often to avoid overflow.

  • The Java compiler will throw a warning when asked to make a narrowing cast. Narrowing casts must be made explicitly, as they can result in a loss of some data. They usually are used to assign an expression to a variable of a narrower type.

  • Booleans cannot be cast at all.

Reference types: Reference types are data types that hold multiple values and do not have one standard size. A reference type variable holds a reference to the data, rather than the actual data itself. Arrays and classes are reference types in Java.

  • Arrays are collections of elements, all of the same type, in which each element is assigned an index through which it is accessed. The indices are numbered sequentially.

  • Classes are the foundation of object-oriented programming. They contain a collection of data, as well as any operations that can be performed on that data. Fields store the data, and methods hold the operations. Classes exist in a hierarchy based on similar functionality and types, thus allowing reusable code to be inherited (see Inheritance). Classes are referred to by programmer-designated names such as Date, Linked List, or MyAmazingClass.

 
 

Declaring Variables

Before any variable can be used to refer to data, it must be declared—the programmer must tell Java what type of the data the variable will hold (e.g., an int, a double, or a StringTokenizer object). Java will then allocate an appropriate amount of memory for the variable.

Variables are declared with the following syntax:

  • type varName;

  • type varName1, varName2, varName3 ... ;

    Examples:

    • boolean trueOrFalse;

    • float cost, revenue, profit;

    • InputStream myInputStream;

  • A variable can be declared final, meaning that its value cannot be changed later in the program.

 
 

Initializing/Instantiating Variables

Unlike in C, variables are set to default values when they are declared. However, it is poor practice to use a variable without explicitly setting it to its initial value.

Initializing primitive types: Primitive types are initialized using the assignment operator =. The syntax is:

  • variable = value;

    Examples:

    • number = 3;

    • letter = 'D'; /* use single quotes to denote a Unicode character */

    • bool = true;

    Variables also can be initialized as they are declared. However, only one type of variable can be declared in a statement:

  • type varName = value;

    Examples:

    • boolean b = false;

    • double d = Math.sqrt(2);

    • int x = 0, y = 0, z = -2;

    • char ch = 'X', int i = 5; // syntax error!!!

Instantiating objects: Objects are instantiated with the new operator, which calls the object’s appropriate constructor (see Classes and objects). The constructor’s return value is assigned to the variable.

Examples:

  • cal = new Calendar();

  • Hashtable ht = new Hashtable();

  • thread = new Thread( target );

Objects can be instantiated at the same time as their variables are declared:

Examples:

  • Calendar cal = new Calendar();

  • Integer i1 = new Integer( 5 ), i2 = new Integer( -1 );

  • Thread t1 = new Thread( runnable1 );

  • Objects can also be instantiated without being assigned to a variable (see Anonymous inner classes).

Strings: In Java, Strings are a class type, not a primitive type. However, to facilitate the manipulation of Strings, Java allows a String variable to be instantiated explicitly as an object or implicitly by the assignment of a string literal, a string of characters in quotation marks. The following are equivalent; both are valid Java syntax:

  • String str = new String("Hello world!");

  • String str = "Hello World!";

Strings also can be operated on either as literals or as objects with either the String.concat(String str) method or the + operator. Both the concatenation operator and the concat () method concatenate their second operand or parameter to the end of the first. The following are equivalent:

  • String str = "Hello" + " world!";

  • String str = "Hello".concat(" world!");

  • String s1 = "Hello";

    String s2 = " world!";

    String str = s1 + s2;

 
 

Control Flow

Java starts executing programs at the public static void main (String[] args) line in the class specified on the command line, and it continues by executing each command sequentially. When the Java interpreter arrives at a method, it transfers control to that method, sequentially executing its statements. At the method’s end, or when it reaches a return statement, Java transfers control back to the calling method. A program’s flow of control can be modified with conditional statements and iterative statements.

With all control flow statements except switch, the braces are optional if there is only one code statement.

Example:

  • if (x < y)
       System.out.println("x is less than " + y);

  • if (isTrue) {    x++;
       System.out.println("Added one to x." );}

 
 

Conditional Statements

if: Java’s basic decision-making command is if, which is followed by a conditional statement and one or more command statements. The conditional must evaluate to a boolean. The command statements are sequentially executed if the conditional evaluates to true and skipped if it evaluates to false.

  • if (condition) {
       execute code statements here }

if/else: The if statement can be complemented with an else statement followed by one or more command statements. The commands following if are executed if the conditional statement is true, and the commands following else are executed if the conditional statement is false.

  • if (condition) {
       execute code statements here }
    else {
       execute other code statements here }

Example:

  • if (number < 5)
       System.out.println("Less than five.");
    else if (number == 5)
       System.out.println("Equals five.");
    else
       System.out.println("Greater than five.");

switch: The switch statement is equivalent to a series of else if statements. The switch statement is best used when only a single variable needs to be tested for a series of alternatives.

The variable is matched against each case value. When or if there is a match, the accompanying code segment is executed. The optional default statement can be placed at the end of the switch code; its associated code is executed if none of the other cases are executed.

  • switch (variable) {
       case value1:
          execute code statements here
          break;
       case value2:
          execute code statements here
          break;
       ...
       default:
          execute code statements here
       }

Example:

  • switch (ch) {
       case 'y':
          System.out.println("Yes!");
          break;
       case 'n':
          System.out.println("No!");
          break;
       default:
          System.out.println("Invalid input!");
       }

 
 

Iterative Statements

Java’s iterative control structures are similar to those of C, including while, do, and for loops. Loop control flow can be interrupted by the break and continue commands. The break command exits a loop; the continue command exits the current iteration of the loop and goes on to the next iteration. However, good programming practice minimizes the use of break and continue statements.

while: The while loop is the basic loop structure in Java. It consists of a conditional statement and a code segment. The code segment is executed and re-executed as long as the conditional is true.

  • while (condition) {
       execute code segments here }

Examples:

  • int x = number; // assign x the value of number
    // counts down from the current value of x to 0
    (x <= 0)
       System.out.println("Invalid value for x: " + x);
    else
       while (x != 0)
          System.out.println(--x);
          System.out.println( "x equals 0" );

  • // picks random numbers r, stops when 0.6 < r < 0.7
    double r = Math.random();
    while (!( r > 0.6 && r < 0.7)) {
          System.out.println( r );
          r = Math.random(); }

do: The do loop is similar to the while loop, except that the conditional statement of the do loop is evaluated after the loop executes once. The code segment is re-executed as long as the conditional is true.

  • do
       execute code statements here
    } while (condition);

Example:

  • /* flips a coin, stops when the coin is heads (true) */
    boolean heads;
    do {
       myCoin = myCoin.flip();
       heads = myCoin.getFace();
    } while (!heads);

for: The for statement governs a block of code through an initialization statement, conditional statement, and increment statement. The initialization, conditional, and increment statements are all optional, although the statement for ( ; ; ) is an infinite loop. Within a for loop, Java first executes the initialization statement and then executes and re-executes the block of code and increment statement—in that order—as long as the condition is true. The condition is evaluated each time before the code block is executed.

  • for (initialization; condition; increment) {
       execute code statements here }

Examples:

  • int x = number; // assign x the value of number
    // counts down from the current value of x to 0
    for ( ; x > 0 ; x-- )
       System.out.println(x);
    System.out.println(x = 0);

  • // sorts a char array k using bubble sort
    for (int i = 0; i < k.length(); i++) {
       char temp;
       for (int j = i; j < k.length() -1; j++) {
          if (k[j] > k[j + 1]) {
             temp = k[j];
             k[j] = k[j + 1];
             k[j + 1] = temp;
          }
       }
    }

“THERE ARE 10 PEOPLE IN THE WORLD: THOSE WHO UNDERSTAND BINARY AND THOSE WHO DON’T” —RANDY CASSINGHAM

 
 

Arrays

Although array elements are referenced by sequential integers, Java does not necessarily store the elements of an array in consecutive memory locations. There are no pointers in Java because the details of data storage are encapsulated from the user. Arrays in Java are Objects, and therefore they are instantiated with the new operator:

  • type[] arrayName = new type[size];

Arrays are not dynamic data structures; an array initialized to a particular size will stay that size throughout its lifetime. Java will throw an ArrayIndexOutOfBoundsException at runtime if you access an array index greater than length - 1 or less than zero. The java.util.Vector and java.util.ArrayList classes each simulate a dynamically growable array.

  • All the elements in an array must be the same type or subclasses of the same type.

    Examples:

    • int[] digits = new int[10];

    • File[] directory = new File[myDir.getSize()];

    • Object[] array = new Object[SIZE]; /* This array will hold instances of any class, but will not hold primitive types. In order to store a primitive type in this array, use a wrapper class such as java.lang.Boolean or java.lang.Double. */

 
 

Referencing Array Elements

Array elements are referenced with the [] operator. The array name is followed by the element’s index in square brackets.

  • arrayName[index]

The first element of an array has index number zero. Any attempt to reference an element beyond the array’s length – 1 will throw an ArrayIndexOutOfBoundsException.

Examples:

  • String s = args[0] /* references the first parameter on the command line */

  • File myFile = directory[k] /* references the (k - 1)th element of directory */

 
 

Array Variables and Methods

The java.util.Arrays class contains several useful methods and variables for working with arrays.

  • length: All arrays have an internal variable called length that stores the maximum number of elements the array can hold. The last index of array k is k.length - 1.

  • binarySearch(Object[] array, Object obj)
    Searches array for the object obj.

  • equals(Object[] array1, Object[] array2)
    Returns true if array1 equals array2.

  • fill(Object[] array, Object obj)
    Assigns the value obj to each element of array

  • sort(Object[] array)
    Sorts the elements of array in ascending order.

  • All of these methods are overloaded to handle arrays of primitive types and, in some cases, Comparables. See http://java.sun.com/j2se/1.4.1/docs/api/java/util/Arrays.html