Java Language Fundamentals

The following topics are are covered

Java Keywords

Keywords cannot be used as identifiers (names) for classes, methods, variables or anything else in your code. All keywords start with a lower case.

Access Modifiers
private Makes a method or a variable accessible only from within its own class
protected Makes a method or a variable accessible only to classes in the same package or subclass of the class
public Makes a class, method or variable accessible from any other class
Class, Method and Variable Modifiers
abstract Used to declare a class that cannot be instantiated or a method that must be implemented by a nonabstract subclass
class Used to specify a class
extends Used to indicate the superclass that a subclass is extending
final Makes it impossible to extend a class, override a method or reinitialize a variable
implements Used to indicate the interfaces that a class will implement
interface Used to specify a interface
native Indicates a method is written in a platform-dependent language such as C
new Used to instantiate an object by invoking the constructor
static Makes a method or a variable belong to a class as opposed to an instance
strictfp Used in front of a method or class to indicate that floating-point numbers will follow FP-strict rules in all expressions
synchronized Indicates that a method can be accessed by only one thread at a time
transient Prevents fields from ever being serialized. Transient fields are always skipped when objects are serialized
volatile Indicates a variable may change out of sync because it is used in threads
Flow Control
break Exits from the block of code in which it resides
case Executes a block of code, dependent on what the switch tests for
continue Stops the rest of the code within the block from executing in a loop and then begins the next iteration of the loop
default Executes this block of code if none of the switch-case statement match
do Executes a block of code one time, then, in conjunction with the while statement, it performs a test to determine whether the block should be executed again
else Executes an alternate block of code if an if test is false
for Used to perform a conditional loop for a block of code
if Used to perform a logical test for true or false
instanceof Determines whether an object is an instance of a class, superclass or interface
return Returns from a method without executing any code that follows the statement (can optionally return a variable)
switch Indicates the variable to be compared with the case statement
while Executes a block of code repeatedly while a certain condition is true
Error Handling
catch Declares the block of code used to handle an exception
finally Block of code usually following a try-catch statement, which is executed no matter what program flow occurs when dealing with an execption
throw Used to pass an exception up to the method that called this method
throws Indicates the method will pass an exception to the method that called it
try Block of code that will be tried, but which may cause an exception
assert Evaluates a conditional expression to verify the programmers assumption
Package Control
import Statement to import packages or classes into code
package Specifies to which package all classes in a source file belong
Variable Keywords
super Reference variable referring to the immediate superclass
this Reference variable referring to the current instance of an object
Void Return Type
void Indicates no return type for a method
Unused Reserved Words
const Do not use to declare a constant; use public static final
goto Not implemented in the Java language, its bad.

Java Primitive Data Types

Java has a number of primitive data types, these are portable across all computer platforms that support Java. Primitive data types are special data types built into the Java language, they are not objects created from a class. Object type String is often thought as a primitive data type but it is an Object. All Java's six number types are signed which means they can be positive or negative. Always append a f when you want a floating-point number otherwise it will be a double.

Data Type Value
boolean A value indicating true or false
byte An 8-bit integer (signed)
char A single unicode character (16-bit unsigned)
double A 64-bit floating-point number (signed)
float A 32-bit floating-point number (signed)
int A 32-bit integer (signed)
long A 64-bit integer (signed)
short A 16-bit integer (signed)

Type
Size in Bits
Size in Bytes
Default value
Minimum Range
Maximum Range
boolean
8
1
false
n/a
n/a
char
16
2
'\u0000'
n/a
n/a
byte
8
1
0
-2E7
2E7-1
short
16
2
0
-2E15
-2E15-1
int
32
4
0
-2E31
-2E31-1
long
64
8
0L
-2E63
-2E63-1
float
32
4
0.0f
Not needed
Not needed
double
64
8
0.0d
Not needed
Not needed

Java Variables

Java is a strongly typed programming language which means that every variable must be known at compile time, this identifies any errors in the code when compiling, there are two types of variables primitive (see above) or reference (pointer to an object).

A variable is just a storage location and has the following naming constraints

boolean example boolean t = true;
boolean p = false;
boolean q = 0;   // Compiler error
char example

char a = 'a';
char b = '@';
char letterN = '\u004E';   // The letter N
char c = (char) 70000;     // casting is required because 7000 is out of range
char d = 70000;            // ERROR: casting rquired

byte example byte b = 0x41;             // display 65
byte c = 4;                // display 4
short example short a = 10;
short b = 107;
int example int a = 1;
int b = 10;
int c = 10,000;   // ERROR: because of the comma
long example long l1 = 110599L;
long l2 = 0xFFFFl;   // Note the lower case l
float example float f1 = 23.467890;   // ERROR: Compiler error loss of precision
float f1 = 23.467890F;  // Note the suffix F at the end
double example double d1 = 987.987D;
double d1 = 987.987;   // OK, because the literal is a double

Array Declaration, Construction and Initialization

Arrays are objects in Java that store multiple variables of the same data type. Arrays can hold either primitive data types or object references, but the array itself will always be an object type. Multidimensional arrays are just arrays of arrays, the dimensions in a multidimensional array can have different lengths. An array of primitives can accept any value that can be promoted implicity to the declared type of the array (byte can go into a int array). An array of objects can hold any object that passes the IS-A (instanceof) test for the declared type.

Declaring an Array Arrays are declared by stating the type of element the array will hold, which can be a primitive or an object. The array will not be determined at this point and the compiler will throw an error if you do.
Constructing an Array

Constructing an array means creating the array object on the heap - in other words, doing a new on the array type, at this point you determine the size of the array so that the space can be allocated on the heap.

Primitive arrays are given default values when created unless otherwise specified (see above for default values).
Objects arrays are given null values as default unless otherwise specified.

Initializing an Array

Initializing an means putting things into it. if you have an array of objects, the array does not hold the object but holds a reference to the objects. The default value of an element of an array which has a type of object is null, so becareful if you try to use this element otherwise you get a nullpointerexception error.

To access an element within the array you start from 0, if you get an ArrayIndexOutOfBoundsException it means that you are trying to access an element that does not exist (not within range).

The position number in square brackets is more formally called a subscript (index), a subscript must be an integer or an integer expression. You cannot change the size of an array once constructed, however there are other list types that can be grown or shrunk see Collections for more details.

Array Examples
Declaring an Array Example

int[] array1;   // Square brackets before variable name (recommended)
int key [];     //  Square brackets after variable name

Thread[] threads;   // Recommended
Thread threads [];  // Legal but less readable

String [][][] occupantName;   // 3 dimensional array
String [][] managerName       // 2 dimensional array

int[5] array1;   // ERROR: You cannot include the size of an array, the compiler will complain

Constructing an Array Example

int[] array1;          // Declare the array of ints
array1 = new init[4];   // constructs an array and assigns the variable name array1

Note: the array will now be on the heap with each element set to 0 (default)

# Declare an array in one statement
int[] array1 = new int[14];

# Will not compile
int[] array1 = new int[];   // ERROR: missing array size

# Multidimension arrays
int[][] ratings = new int[3][];   // only first brackets are given a size which is acceptable

Initializing an Array Example

# Setting values for sepcific elements within the array
animals[0] = new Animal();    // Object type
x[4] = 2;                     // primitive type

# Initializing a multidimensional array
array[0] = new init[4];     // Specify that element 0 holds an array of 4 int elements
array[1] = new init[6];     // Specify that element 1 holds an array of 6 int elements

array[0][0] = 5;
array[0][1] = 6;

Declaring, Constructing and Initializing on one line

# 4 element array of type int
int[] dots = {3,6,9,12};

# Multidimensional array
int[][] scores = { {3,4,5}, {9,2}, {3,4,5} };

# Object array
String[] names = {new String("Paul"), new String("Lorraine")};

Anonymous Array

# A second short cut is called an anonymous array, below creates a 3 element array of type int.
int[] testScores;
testScores = new int[] {4,7,2};

Simple arrays

public class Array1 {

   public static void main(String[] args) {

      // array declaration and initialization
      int[] counter;
      counter = new int[3];

      // declaration and initialization in one statement
      String[] names = { "Paul", "Lorraine", "Dominic", "Jessica" };

      // add some data to the counter array
      counter[0] = 0;
      counter[1] = 1;
      counter[2] = 2;

      System.out.println("Counter: " + counter[0] + " " + counter[1] + " " + counter[2] + "\n");

      for (int x=0; x < names.length; x++)   // Use the length variable to get number of elements
      {
         System.out.println("Name: " + names[x]);
      }
   } // END MAIN
}

Note: arrays have a length variable that contains the number of elements.

multi-dimensional array examples class arrayTest {

   public static void main(String[] args) {

      int array1[][] = { {1,2,3}, {4,5,6} };
      int array2[][] = { {1,2}, {3}, {4,5,6} };

      buildOutput(array1);
      System.out.println();
      buildOutput(array2);
   }

   public static void buildOutput ( int a[][] ) {
      for ( int i = 0; i < a.length; i++ ) {
         for ( int j = 0; j < a[i].length; j++)
            System.out.print(a[i][j] + " ");

         System.out.println();

      }
   }
}
Passing arrays to methods class arrayTest {

public static void main(String[] args) {

   int a[] = { 1, 2, 3, 4, 5, 6 };

   System.out.print("Orginal array values: ");
   for (int i = 0; i < a.length; i++)
      System.out.print( a[i] + " ");

   System.out.println();

   // array is passed to by-reference
   modifyArray(a);

   System.out.print("Now changed to: ");
   for (int i = 0; i < a.length; i++)
      System.out.print( a[i] + " ");

   System.out.println("\n\nElement a[3] is now: " + a[3]);

   // array elements are passed by-value;
   modifyElement (a[3]);

   System.out.println("Element a[3] has been changed to: " + a[3]);

   }

   // whole array are passed by-reference
   public static void modifyArray (int b[]) {
      for (int j = 0; j < b.length; j++)
         b[j] *= 2;
   }

   // array elements are passed by-value
   public static void modifyElement (int e)
   {
      e *=2;
   }
}

Using a Variable or Array Element that is Uninitialized and Unassigned

There are two types of variable in Java

Instance Variable Declared within the class but outside any method, constructor or any other initializer block
Local Variable

Declared within a method (or argument list of a method)

You have the option to initialize a variable or leave it uninitialized, we get different behaviors when we attempt to use the uninitiailzed variable depending on what type of variable or array we are dealing with, the behavior also depends on the scope level at which we declared the variable.

Instance/Local Variable Type Action
Instance Primitive Will be initialized with its default value (see Java Primitive Data types above for default values)
Instance Object

Will be initialized with null

Instance Array Not Initialized - will have value null
If Initialized - will be given default values
Local Primitive All primitive must be initialized otherwise you will get a compiler error
Local Object

All object type be initialized otherwise you will get a compiler error, you can initialize a object with null to stop the compiler complaining

String name = null;

Local Array Not Initialized - will have value null
If Initialized - will be given default values

A quick example to explain the table above

Example

public class varTest {
   public static void main(String[] args) {

      test t1 = new test();
      t1.testMethod();
   }
}

class test {
   int instance_variable;         // OK not to initialize this as it will get the default value 0

   // Test constructor
   test() {
      System.out.println("instance_variable is " + instance_variable);
   }

   void test() {
      int method_variable;        // Must initialize this variable otherwise the compiler will complain.
      System.out.println("method_count: " + method_count);
   }
}

Note: when you try to compile this, the compiler will error stating that method_count might not have been initialized, remember that you should initialize memember variables

Command-line Arguments to Main

When passing command-line arguments to your Java program it creates a String array to hold the arguments, this array is just like any other array. Note that the array name args can be anything you want but it must be of type String.

Example 1

public class commandLine {
   public static void main (String args[] ) {

     System.out.println("You passed " + args.length + " arguments");

     for(int i = 0; i < args.length; i++)
        System.out.println(args[i]);
   }
}

# Run the command line
c:\> java testCommandLine one two three

Note: arrays args is just like any other array.