Java Programming/Keywords

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Navigate Language Fundamentals topic: ( v d e )

Keywords are special tokens in the language which have reserved use in the language. Keywords may not be used as identifiers in Java - you cannot declare a field whose name is a keyword, for instance.

Examples of keywords are the primitive types, int and boolean; the control flow statements for and if; access modifiers such as public, and special words which mark the declaration and definition of Java classes, packages, and interfaces: class, package, interface.

Below are all the Java language keywords:



abstract is a Java keyword.

It declares a class abstract, not all its methods are defined/implemented. Objects cannot be created from an abstract class. It needs to have a non abstract subclass in order to create an object.

It also declares a method abstract, that is, not implemented in the abstract class. A method cannot be declared abstract in a non abstract class.

Syntact:

public abstract ClassName
or
abstract public ClassName

and for methods in an abstract class :

public abstract void methodName();  // --- No body, no implementation ---
or
abstract public void methodName();  // --- No body, no implementation ---


For Example:

public abstract ClassName
{
   // --- This method does not have a body; it is abstract. ---
   public abstract void abstractMethod();

   // --- This method does have a body; it is implemented in the abstract class; gives a default behavior. ---
   public void normalMethod()
   {
       ...
   }
}

assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws a AssertionError.

An example:

assert list != null && list.size() > 0;
Object value = list.get(0);

Assertions are usually used as a debugging aid. They should not be used instead of validating arguments to public methods.

Assertions are enabled with the Java -ea or -enableassertions runtime option. See your Java environment documentation for additional options for controlling assertions.


boolean is a keyword which designates the boolean primitive type. There are only two possible boolean values: true and false. The default value for boolean fields is false.

The following is a declaration of a private boolean field named initialized, and its use in a method named init()

private boolean initialized = false; 
public synchronized void init() {
   if ( ! initialized ) {
     connection = connect();
     initialized = true;
   }
 }

Note that there is no automatic conversion between integer types (such as int) to boolean as is possible in some languages like C. Instead, one must use an equivalent expression such as (i != 0) which evaluates to true if i is not zero.


break is a Java keyword.

Jumps (breaks) out from a loop. Also used at switch statement.

For Example:

for ( int i=0; i < maxLoopIter; i++ )
{
   System.out.println("Iter=" +i);
   if ( i == 5 )
   {
      break;  // -- 5 iteration is enough --
   }
}

See also:


byte is a keyword which designates the 8 bit signed integer primitive type.

The java.lang.Byte class is the nominal wrapper class when you need to store a byte value but an object reference is required.


Syntact:

byte <variable-name> = <integer-value>;

For Example:

byte b = 65;
or 
byte b = 'A';

'A' is the number 65 ASCII representation.

See also:


case is a Java keyword.

This is part of the switch statement, to find if the value passed to the switch statement matches a value followed by case.

For example:

int i = 3;
switch(i)
{
case 1:
System.out.println("The number is 1.");
break;
case 2:
System.out.println("The number is 2.");
break;
case 3:
System.out.println("The number is 3."); // this line will print
break;
case 4:
System.out.println("The number is 4.");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is not 1, 2, 3, 4, or 5.");

}

catch is a keyword.

It's part of a try block. If an exception is thrown inside a try block, the exception will be compared to any of the catch part of the block. If the exception match with one of the exception in the catch part, the exception will be handled there.

For example:

try {
  ...
    throw new MyException_1();
  ...
} catch ( MyException_1 e ) {
  // --- Handle the Exception_1 here --
} catch ( MyException_2 e ) {
  // --- Handle the Exception_2 here --
}

See also:


char is a keyword.

It defines a character primitive type.

The java.lang.Character class is the nominal wrapper class when you need to store an char value but an object reference is required.

Syntact:

char <variable-name> = '<character>';

For Example:

char oneChar = 'A';
or 
char oneChar = 65;

65 is the character 'A' numeric representation, or ASCII code.

System.out.println( oneChar );

Output:

A

See also:


class is a Java keyword which begins the declaration and definition of a class.

The general syntax of a class declaration, using Extended Backus-Naur Form, is

class-declaration ::= [access-modifiers] class identifier
                      [extends-clause] [implements-clause] 
                      class-body

extends-clause ::= extends class-name
implements-clause ::= implements interface-names 
interface-names ::= interface-name [, interface-names]
class-body ::= { [member-declarations] }
member-declarations = member-declaration [member-declarations]
member-declaration = field-declaration 
                     | initializer 
                     | constructor 
                     | method-declaration
                     | class-declaration

The extends word is optional. If omitted, the class extends the Object class, as all Java classes inherit from it.

See also:


const is a reserved keyword, presently not being used.

In other programming languages, such as C, const is often used to declare a constant. However, in Java, final is used instead.


continue is a Java keyword.

Skip the reminder of the loop and 'continue' with the next iteration.

For Example:

for ( int i=0; i < maxLoopIter; i++ )
{
   if ( i == 5 )
   {
      continue;  // -- 5 iteration is skipped --
   }
   System.println("Iteration = " +i);
}

See also:


default is a Java keyword.

This is an optional part of the switch statement, which only executes if none of the above cases are matched.

See also:


do is a Java keyword.

It starts a do-while looping block. The do-while loop is functionally similar to the while loop, except the condition is evaluated AFTER the statements execute

Syntax:

do{
   statement;
 } while (condition);


For Example:

do 
{
  i++;
} while ( i < maxLoopIter );

See also:


double is a keyword which designates the 64 bit float primitive type.

The java.lang.Double class is the nominal wrapper class when you need to store a double value but an object reference is required.


Syntact:

double <variable-name> = <float-value>;

For Example:

double d = 65.55;

See also:


else is a Java keyword.

It is an optional part of a branching statement. It starts the 'false' statement block.

The general syntax of a if, using Extended Backus-Naur Form, is

branching-statement ::= if condition-clause 
                                    single-statement | block-statement
                       [ else 
                                    single-statement | block-statement ]
 
condition-clause    ::= ( Boolean Expression )
single-statement    ::= Statement
block-statement     ::= { Statement [ Statement ] }

For Example:

if ( boolean Expression )
{
   System.out.println("'True' statement block");
}
else
{
   System.out.println("'False' statement block");
}

See also:


enum is a keyword since Java 1.5.

This keyword defines a group of constants.

For example:

enum Grade { A, B, C, D, F };
...
private Grade gradeA = Grade.A; 

This enum constant then can be passed in to methods:

student.assignGrade( gradeA );
...
public void assignGrade(Grade grade) 
{
   this.grade = grade;
}

extends is a Java keyword.

Used in class and interface definition to declare the class or interface that is to be extended.

Syntact:

public class MyClass extends SuperClass
{
  ...
}

public interface MyInterface extends SuperInterface
{
  ...
}

See also:

In Java 1.5 and later, the "extends" keyword is also used to specify an upper bound on a type parameter in Generics.

class Foo<T extends Number> { ... }

final is a keyword.

It has more than one meaning depending whether it used for a class, a method, or for a variable.

  • It is denoting that a variable is to be constant. This is similar to const in other languages. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful for universal constants, such as pi, or other values that the programmer would like to keep constant throughout the code.
  • It marks a method final, meaning that subclasses can not override this method. The compiler checks and gives an error if you try to override the method.
  • It marks a class final, meaning that the class can not be subclassed.

For Example

static final double PI = 3.1415926;

final public void method()
{
 ...
}

final public class MyClass
{
 ...
}

Note that final is always placed before the variable type in a constant, before the return type of a method, and before the keyword class in a class header.

See also:


finally is a keyword.

It is an optional part of a try block. The code inside the finally block will always be executed, even if there is an exception in the try block.

Three things can happen in a try block:

  • No exception is thrown. In such a case, the following are executed:
    • code in the try block
    • code in the finally block
    • code after the try-catch block
  • An exception is thrown and a matching catch block found. In such a case, the following are executed:
    • code in the try block until where the exception occurred
    • code in the matched catch block
    • code in the finally block
    • code after the try-catch block
  • An exception is thrown and no matching catch block exists. In such a case, the following are executed:
    • code in the try block until where the exception occurred
    • code in the finally block

Note: in that third and final case, NO CODE after the try-catch block is executed.

For Example:

public void method() throws NoMatchedException
{
  try {
  ...
    throw new MyException_1();
  ...
  } catch ( MyException_1 e ) {
    // --- Handle the Exception_1 here --
  } catch ( MyException_2 e ) {
    // --- Handle the Exception_2 here --
  } finally {
    // --- This will always be executed no matter what --
  }
  // --- Code after the try-catch block
}

Note: if there is an exception that happens before the try-catch block, the finally block is not executed.

See also:


float is a keyword which designates the 32 bit float primitive type.

The java.lang.Float class is the nominal wrapper class when you need to store a float value but an object reference is required.


Syntact:

float <variable-name> = <float-value>;

For Example:

float f = 65.55;

See also:


for is a Java keyword.

It starts a looping block.

The general syntax of a for, using Extended Backus-Naur Form, is

for-looping-statement ::= for condition-clause 
                                    single-statement | block-statement
 
condition-clause    ::= ( before-statement;  Boolean Expression ; after-statement )
single-statement    ::= Statement
block-statement     ::= { Statement [ Statement ] }

For Example:

for ( int i=0; i < maxLoopIter; i++ )
{
   System.println("Iter=" +i);
}

See also:


if is a Java keyword.

It starts a branching statement.

The general syntax of a if, using Extended Backus-Naur Form, is

branching-statement ::= if condition-clause 
                                    single-statement | block-statement
                       [ else 
                                    single-statement | block-statement ]
 
condition-clause    ::= ( Boolean Expression )
single-statement    ::= Statement
block-statement     ::= { Statement [ Statements ] }

For Example:

if ( boolean Expression )
{
   System.out.println("'True' statement block");
}
else
{
   System.out.println("'False' statement block");
}

See also:


goto is a reserved keyword, presently not being used.


implements is a Java keyword.

Used in class definition to declare the Interfaces that are to be implemented by the class.

Syntact:

public class MyClass implements MyInterface1, MyInterface2
{
  ...
}

See also:


import is a Java keyword.

It declares a Java class to use in the code below the import statement. Once a Java class is declared, then the class name can be used in the code without specifying the package the class belongs to.

Use the '*' character to declare all the classes belonging to the package.

Syntax:

import package.JavaClass;
import package.*;

See also:


instanceof is a keyword.

It checks if an object reference is an instance of a type, and returns a boolean value;

The <object-reference> instanceof Object will return true for all object references, since all Java objects are inherited from Object. Note, that instanceof will always return false if <object-reference> is null.

Syntax:

<object-reference> instanceof TypeName

For example:

class Fruit
{
...	
} 
class Apple extends Fruit
{
 ...
}
class Orange extends Fruit
{
 ...
}
public class Test 
{
   public static void main(String[] args) 
   {
      Collection<Object> coll = new ArrayList<Object>();

      Apple app1 = new Apple();
      Apple app2 = new Apple();
      coll.add(app1);
      coll.add(app2);

      Orange or1 = new Orange();
      Orange or2 = new Orange();
      coll.add(or1);
      coll.add(or2);

      printColl(coll);
   }

   private static String printColl( Collection<?> coll )
   {
      for (Object obj : coll)
      {
         if ( obj instanceof Object )
         {
            System.out.print( "It is a Java Object and" );
         }
         if ( obj instanceof Fruit )
         {
            System.out.print( "It is a Fruit and" );
         }
         if ( obj instanceof Apple )
         {
            System.out.println( "it is an Apple" );
         }
         if ( obj instanceof Orange )
         {
            System.out.println( "it is an Orange" );
         }
      }
   }
}

Run the program:

java Test

The output:

"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Apple"
"It is a Java Object and It is a Fruit and it is an Orange"
"It is a Java Object and It is a Fruit and it is an Orange"

Note that the instanceof operator can also be applied to interfaces. For example, if the example above was enhanced with the interface

interface Edible 
{
 ...
}

and the the classes modified such that they implemented this interface

class Orange extends Fruit implements Edible
{
 ...
}

we could ask if our object were edible.

if ( obj instanceof Edible )
{
  System.out.println( "it is edible" );
}

int is a keyword which designates the 32 bit signed integer primitive type.

The java.lang.Integer class is the nominal wrapper class when you need to store an int value but an object reference is required.


Syntact:

int <variable-name> = <integer-value>;

For Example:

int i = 65;

See also:


interface is a Java keyword.

Starts the declaration of a Java Interface.

For example:

public interface SampleInterface
{
   public void method1();
  ...
}

See also:


long is a keyword which designates the 64 bit signed integer primitive type.

The java.lang.Long class is the nominal wrapper class when you need to store a long value but an object reference is required.

Syntact:

long <variable-name> = <integer-value>;

For Example:

long l = 65;

See also:


native is a java keyword.

It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI(Java Native Interface)

Syntax:

[public|protected|private] native method();

new is a Java keyword. It creates a Java object and allocates memory for it on the heap. new is also used for array creation, as arrays are also objects.

Syntax:

JavaType variable = new JavaObject();
int[] intArray = new int[10];
String[][] stringMatrix = new String[5][10];

See also:


package is a Java keyword.

It declares a 'name space' for the Java class. It must be put at the top of the Java file, it should be the first Java statement line.

To make the package name to be unique across vendors, usually the company url is used stating in backword.

Syntact:

package package;

For Example:

 package com.mycompany.myapplication.mymodule;

See also:


private is a Java keyword which declares a members access as private. That is, the member is only visible within the class, not from any class (including subclasses). The visibility of private members extends to nested classes.

Syntact:

private void method();

See also:


protected is a Java keyword.

This is an access modifier, used before a method or other class member to indicate that the member can be accessed only by classes in the same package, or subclasses.

Syntact:

protected void method();

See also:


public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final.

A best practice is to give fields private access and reserve public access to only the set of methods and final fields that define the class' public constants. This helps with encapulation and information hiding, since it allows you to change the implementation of a class without affecting the consumers who use only the public API of the class.

Below is an example of an immutable public class named Length which maintains private instance fields named units and magnitude but provides a public constructor and two public accessor methods.

package org.wikibooks.java;
public class Length {
  private double magnitude;
  private String units;
  public Length(double magnitude, String units) {
     if (units == null || units.trim().length() == 0)
         throw new IllegalArgumentException("non-null, non-empty units required.");
     this.magnitute = magnitude;
     this.units = units;
  }
  public double getMagnitude() {
     return magnitude;
  }
  public String getUnits() {
     return units;
  }
}

return is a Java keyword.

Returns a primitive value, or an object reference, or nothing(void). It does not return object values, only object references.

Syntax:

return variable;  // --- Returns variable
or
return;           // --- Returns nothing

short is a keyword.

It defines a 16 bit signed integer primitive type.

Syntact:

short <variable-name> = <integer-value>;

For Example:

short shr = 65;

See also:


static is a keyword that states that all instances of a given class are to share the same variable/method. This is used for a constant variable or a method that is the same for every instance of a class, such as the methods in the Math class. The main method of a class is generally labelled static. The static keyword can also be used in the context of defining inner classes. These classes are not bound to an instance of the outer defining class.

No object needs to be created to use static variables or call static methods. Just put the class name before the static variable or method to use them.

Static methods cannot call non static methods. The this current object reference is also not available in static methods.

Syntact:

public static variableName;
or
static public variableName;

and for methods :

public static void methodName()
{
  ...
}
or
static public void methodName()
{
   ...
}

To access them :

ClassName.variableName = 10;

ClassName.methodName();

For Example:

public static final double pi = 3.14159;
public static void main(String[] args)
{
   ...
}

strictfp is a java keyword, since Java 1.2 .

It makes sure that floating point calculations result precisely the same regardless of the underlying operating system and hardware platform, even if more precision could be obtained. This is compatible with the earlier version of Java 1.1 . If you need that use it.

Syntact:

public strictfp class MyClass 
{ 
  ...
}
or
strictfp public class MyClass 
{
  ...
}

public strictfp void method() 
{ 
  ...
}
or
strictfp public void method() 
{
  ...
}

See also:


super is a keyword.

Used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class can not be called. Only public and protected methods can be called by the super keyword.

Syntact:

super.<method-name>();

For Example:

public class SuperClass
{
   public void printHello()
   {
      System.out.println( "Hello from SuperClass" );
     return;
   }
}
...
public class SubClass extends SuperClass
{
   public void printHello()
   {
      super.printHello();
      System.out.println( "Hello from SubClass" );
     return;
   }

   public static main( String[] args )
   {
      SubClass obj = new SubClass();
      obj.printHello();
   }
}

Running the above program:

Java SubClass

The output:

"Hello from SuperClass"
"Hello from SubClass"

See also:

In Java 1.5 and later, the "super" keyword is also used to specify a lower bound on a wildcard type parameter in Generics.

public void sort(Comparator<? super T> comp) { ... }

switch is a Java keyword.

It is a branching operation, based on a number. The 'number' must be either char, byte, short, or int primitive type.

Syntax:

switch ( <integer-var> )
{
   case <label1>: <statements>;
   case <label2>: <statements>;
   ...
   case <labeln>: <statements>;
   default: <statements>;
}

When the <integer-var> value match one of the <label>, then: The statements after the matched label will be executed including the following label's statements, until the end of the switch block, or until a break keyword is reached.

For Example:

int var = 3;
switch ( var )
{
   case 1: System.out.println( "Case: 1" );
           System.out.println( "Execute until break" );
   break;		  	
   case 2: System.out.println( "Case: 2" );
           System.out.println( "Execute until break" );
   break;
   case 3: System.out.println( "Case: 3" );
           System.out.println( "Execute until break" );
   break;  	
   case 4: System.out.println( "Case: 4" );
           System.out.println( "Execute until break" );
   break;      
   default: System.out.println( "Case: default" );
           System.out.println( "Execute until break" );
   break;	      
}		

The output from the above code is:

Case: 3
Execute until break

The same code can be written with if-else blocks":

int var = 3;
if ( var == 1 )
{
   System.out.println( "Case: 1" );
   System.out.println( "Execute until break" );
} 
else if ( var == 2 )
{
   System.out.println( "Case: 2" );
   System.out.println( "Execute until break" );
}
else if ( var == 3 )
{
   System.out.println( "Case: 3" );
   System.out.println( "Execute until break" );
}
else if ( var == 4 )
{
   System.out.println( "Case: 4" );
   System.out.println( "Execute until break" );
}
else // -- This is the default part --
{
   System.out.println( "Case: default" );
   System.out.println( "Execute until break" );
}

See also:


synchronized is a keyword.

It marks a 'critical section'. A 'critical section' is where one and only one thread is executing. So to enter into the marked code the threads are 'synchronized', only one can enter, the others have to wait. For more information see Synchronizing Threads Methods or [1].

The synchronized keyword can be used in two ways:

Syntax to mark a method synchronized:

public synchronized void method()
{
  // Thread.currentThread() has a lock on this object. ie. a synchronized method is the same as calling {synchronized(this){..}}.
}

Syntax to mark a synchronized block:

synchronized ( <object_reference> )
{
  // Thread.currentThread() has a lock on object_reference. All other threads trying to access it will be blocked until the current thread releases the lock.
}

this is a Java keyword.

It contains the current object reference.


Syntact:

this.method();

For Example:

public class MyClass
{ 
 ...
   private String _memberVar;
 ...
   public void setMemberVar( String value )
   {
       this._memberVar= value;
   }
}

For Example:

public class MyClass
{ 
   MyClass(int a, int b) {
       System.out.println("int a: " + a);
       System.out.println("int b: " + b);
   }
   MyClass(int a) {
       this(a, 0);
   }
 ...
   public static void main(String[] args) {
       new MyClass(1, 2);
       new MyClass(5);
   }
}

throw is a keyword.

It 'throws' a Java Exception.

Syntact:

throw <Exception Ref>;

For Example:

public Customer findCustomer( String name ) throws CustomerNotFoundException
{
   Customer custRet = null;
   Iterator iter = _customerList.iterator();
   while ( iter.hasNext() )
   {
       Customer cust = (Customer) iter.next();
       if ( cust.getName().equals( name ) )
       {
          // --- Customer find --
          custRet = cust;
          break;
       }
    }
    if ( custRet == null )
    {
       // --- Customer not found ---
       throw new CustomerNotFoundException( "Customer "+ name + "was not found" );
    }

   return custRet
 }

See also:


throws is a Java keyword.

Used in a method definition to declare the Exceptions to be thrown by the method.

Syntax:

public myMethod() throws MyException1, MyException2
{
  ...
}

Example:

class MohanDefinedException extends Exception
{
 public MohanDefinedException(String str) 
 {
    super(str);
 }   
}
public class MohanClass
{
   public static void showMyName(String str) throws MohanDefinedException
   {
         if(str.equals("What is your Name?"))
               throw new MohanDefinedException("My name is Mohan Rajashekaran");
   }
   public static void main(String a[])
   {
      try
      {
         showMyName("What is your Name?");
      }
      catch(MohanDefinedException mde)
      {
         mde.printStackTrace();
      }
    }
}

transient is a Java keyword.

It flags a field as something that should not be considered part of an object's persistent state.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost on purpose.

Syntax:

private transient <member-variable>;
or 
transient private <member-variable>;


For example:

public class Foo 
{
  private String saveMe;
  private transient String dontSaveMe;
  private transient String password;
 .
 .
}

See also:

  • Java language specification reference: jls
  • Serializable Interface. Serializable

try is a keyword.

It starts a try block. If an Exception is thrown inside a try block, the Exception will be compared any of the catch part of the block. If the Exception match with one of the Exception in the catch part, the exception will be handled there.

Three things can happen in a try block:

  • No exception is thrown:
    • the code in the try block
    • plus the code in the finally block will be executed
    • plus the code after the try-catch block is executed
  • An exception is thrown and a match is found among the catch blocks:
    • the code in the try block until the exception occurred is executed
    • plus the matched catch block is executed
    • plus the finally block is executed
    • plus the code after the try-catch block is executed
  • An exception is thrown and no match found among the catch blocks:
    • the code in the try block until the exception occurred is executed
    • plus the finally block is executed
    • NO CODE after the try-catch block is executed

For Example:

public void method() throws NoMatchedException
{
  try {
  ...
    throw new MyException_1();
  ...
  } catch ( MyException_1 e ) {
    // --- Handle the Exception_1 here --
  } catch ( MyException_2 e ) {
    // --- Handle the Exception_2 here --
  } finally {
    // --- This will always be executed no matter what --
  }
  // --- Code after the try-catch block
}

How the catch-blocks are evaluated see Catching Rule

See also:


void is a Java keyword.

Used at method declaration and definition to specify that the method does not return any type, the method returns void. It is not a type and there is no void references/pointers as in C/C++.

For example:

public void method()
{
  ...
  return;   // -- In this case the return is optional
}

See also:


volatile is a keyword.

It marks a member variable not to be used in optimization, during compilation. The compiler may make new code to gain performance optimisational, this can cause problems when a member variable can be changed by many threads. Those member variables that can be changed by more than one thread should be set to volatile.

Syntact:

private volatile <member-variable>;
or 
volatile private <member-variable>;


For example:

private volatile changingVar;

See also:


while is a Java keyword.

It starts a looping block.

The general syntax of a while, using Extended Backus-Naur Form, is

while-looping-statement ::= while condition-clause 
                                    single-statement | block-statement
 
condition-clause    ::= ( Boolean Expression )
single-statement    ::= Statement
block-statement     ::= { Statement [ Statements ] }

For Example:

while ( i < maxLoopIter )
{
   System.println("Iter=" +i++);
}

See also: