Jump to content

Keywords

100% developed
From Wikibooks, open books for an open world

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:

In addition, the identifiers null, true, and false denote literal values and may not be used to create identifiers.

abstract

[edit | edit source]

abstract is a Java keyword. It can be applied to a class and methods. An abstract class cannot be directly instantiated. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and after the static keyword. A non-abstract class is a concrete class. An abstract class cannot be final.

Only an abstract class can have abstract methods. An abstract method is only declared, not implemented:

Computer codeCode listing 1: AbstractClass.java
publicabstractclassAbstractClass{// This method does not have a body; it is abstract.publicabstractvoidabstractMethod();// This method does have a body; it is implemented in the abstract class and gives a default behavior.publicvoidconcreteMethod(){System.out.println("Already coded.");}}

An abstract method cannot be final, static nor native. Because an abstract class can't directly be instantiated, you must either instantiate a concrete sub-class or you instantiate the abstract class by implementing its abstract methods alongside a new statement:

ExampleCode section 1: Abstract class use.
AbstractClassmyInstance=newAbstractClass(){publicvoidabstractMethod(){System.out.println("Implementation.");}};

A private method cannot be abstract.


assert

[edit | edit source]

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 an AssertionError Assertions may be declared using the following syntax:

Computer code
assertexpression1[:expression2];

expression1 is a boolean that will throw the assertion if it is false. When it is thrown, the assertion error exception is created with the parameter expression2 (if applicable).

An example:

Computer code
assertlist!=null&&list.size()>0:"list variable is null or empty";Objectvalue=list.get(0);

Assertions are usually used as a debugging aid. They should not be used instead of validating arguments to public methods, or in place of a more precise runtime error exception.

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

boolean

[edit | edit source]

boolean is a keyword which designates the booleanprimitive 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 privateboolean field named initialized, and its use in a method named synchronizeConnection.

ExampleCode section 1: Connection synchronization.
privatebooleaninitialized=false;publicvoidsynchronizeConnection(){if(!initialized){connection=connect();initialized=true;}}

The previous code only creates a connection once (at the first method call). 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

[edit | edit source]

break is a Java keyword.

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

For example:

Computer code
for(inti=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.

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

For example:

Computer code
byteb=65;

or

Computer code
byteb='A';

The number 65 is the code for 'A' in ASCII.

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:

Computer code
inti=3;switch(i){case1:System.out.println("The number is 1.");break;case2:System.out.println("The number is 2.");break;case3:System.out.println("The number is 3.");// this line will printbreak;case4:System.out.println("The number is 4.");break;case5:System.out.println("The number is 5.");break;default:System.out.println("The number is not 1, 2, 3, 4, or 5.");}

catch

[edit | edit source]

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:

Computer code
try{//...thrownewMyException_1();//...}catch(MyException_1e){// --- Handle the Exception_1 here --}catch(MyException_2e){// --- Handle the Exception_2 here --}

See also:

char is a keyword. It defines a character primitive type. char can be created from character literals and numeric representation. Character literals consist of a single quote character (') (ASCII 39, hex 0x27), a single character, and a close quote ('), such as 'w'. Instead of a character, you can also use unicode escape sequences, but there must be exactly one.

Syntax:

char variable name1 = 'character1';
ExampleCode section 1: Three examples.
charoneChar1='A';charoneChar2=65;charoneChar3='\u0041';System.out.println(oneChar1);System.out.println(oneChar2);System.out.println(oneChar3);
Computer codeOutput for Code section 1
A A A 

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

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

ExampleCode section 2: char wrapping.
charaCharPrimitiveType='A';CharacteraCharacterObject=aCharPrimitiveType;

See also:

class

[edit | edit source]

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] classidentifier [extends-clause] [implements-clause] class-body extends-clause ::= extendsclass-name implements-clause ::= implementsinterface-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

[edit | edit source]

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

[edit | edit source]

continue is a Java keyword. It skips the remainder of the loop and continues with the next iteration.

For example:

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


results in

0 1 2 3 4 6 7 

See also

[edit | edit source]

default

[edit | edit source]

default is a Java keyword.

This is an optional part of the Embedded Systems/Atmel AVRswitch 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:

Computer code
do{//statements;}while(condition);

For example:

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

See also:

double

[edit | edit source]

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.

Syntax:

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

For example:

Computer code
doubled=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 ::= ifcondition-clausesingle-statement | block-statement [ elsesingle-statement | block-statement ] condition-clause  ::= ( Boolean Expression ) single-statement  ::= Statement block-statement  ::= {Statement [ Statement ] }

For example:

Computer code
if(expression){System.out.println("'True' statement block");}else{System.out.println("'False' statement block");}


See also:

Computer code
/** Grades of courses */enumGrade{A,B,C,D,F};// ...privateGradegradeA=Grade.A;


This enumeration constant then can be passed in to methods:

Computer code
student.assignGrade(gradeA);/** * Assigns the grade for this course to the student * @param GRADE Grade to be assigned */publicvoidassignGrade(finalGradeGRADE){grade=GRADE;}


An enumeration may also have parameters:

Computer code
publicenumDayOfWeek{/** Enumeration constants */MONDAY(1),TUESDAY(2),WEDNESDAY(3),THURSDAY(4),FRIDAY(5),SATURDAY(6),SUNDAY(0);/** Code for the days of the week */privatebytedayCode=0;/** * Private constructor * @param VALUE Value that stands for a day of the week. */privateDayOfWeek(finalbyteVALUE){dayCode=java.lang.Math.abs(VALUE%7);}/** * Gets the day code * @return The day code */publicbytegetDayCode(){returndayCode;}}


It is also possible to let an enumeration implement interfaces other than java.lang.Comparable and java.io.Serializable, which are already implicitly implemented by each enumeration:

Computer code
publicenumDayOfWeekimplementsRunnable{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY;/** * Run method prints all elements */publicvoidrun(){System.out.println("name() = "+name()+", toString() = \""+toString()+"\"");}}

extends

[edit | edit source]

extends is a Java keyword.

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

Syntax:

Computer code
publicclassMyClassextendsSuperClass{//...}publicinterfaceMyInterfaceextendsSuperInterface{//...}


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

Computer code
classFoo<TextendsNumber>{/*...*/}


See also:

final

[edit | edit source]

final is a keyword. Beware! It has distinct meanings depending whether it is used for a class, a method, or for a variable. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and after the static keyword.

ExampleCode section 1: Keyword order.
privatestaticfinallongserialVersionUID=-5437975414336623381L;

For a variable

[edit | edit source]

The final keyword only allows a single assignment for the variable. That is to say, once the variable has been assigned, its value is in read-only. If the variable is a primitive type, its value will no longer change. If it is an object, only its reference will no longer change. Keep in mind that its value can still be changed.

WarningCode section 2: Forbidden double assignment.
finalinta=1;a=2;
ExampleCode section 3: Only modify the value of the object.
finalArrayListlist=newArrayList();System.out.println(list.size());list.add("One item");System.out.println(list.size());
Standard input or outputConsole for Code section 3
0 1 

A final variable is often used for universal constants, such as pi:

ExampleCode section 4: Pi constant.
staticfinaldoublePI=3.1415926;

The final keyword can also be used for method parameters:

ExampleCode section 5: Final method parameter.
publicintmethod(finalintinputInteger){intoutputInteger=inputInteger+1;returnoutputInteger;}

It is useful for methods that use side effects to update some objects. Such methods modify the content of an object passed in parameter. The method caller will receive the object update. This will fail if the object parameter has been reassigned in the method. Another object will be updated instead. Final method parameter can also be used to keep the code clean.

The final keyword is similar to const in other languages and the readonly keyword in C#. A final variable cannot be volatile.

For a class

[edit | edit source]

The final keyword forbids the creation of a subclass. It is the case of the Integer or String class.

Computer codeCode listing 1: SealedClass.java
publicfinalclassSealedClass{publicstaticvoidmain(String[]args){}}

A final class cannot be abstract. The final keyword is similar to sealed keyword in C#.

For a method

[edit | edit source]

The final keyword forbids to overwrite the method in a subclass. It is useless if the class is already final and a private method is implicitly final. A final method cannot be abstract.

Computer codeCode listing 2: NoOverwriting.java
publicclassNoOverwriting{publicfinalvoidsealedMethod(){}}

Interest

[edit | edit source]

The final keyword is mostly used to guarantee a good usage of the code. For instance (non-static) methods, this allows the compiler to expand the method (similar to an inline function) if the method is small enough. Sometimes it is required to use it. For instance, a nested class can only access the members of the top-level class if they are final.

See also Access Modifiers.

finally

[edit | edit source]

finally is a keyword which is an optional ending part of the try block.

ExampleCode section 1: try block.
try{// ...}catch(MyException1e){// Handle the Exception1 here}catch(MyException2e){// Handle the Exception2 here}finally{// This will always be executed no matter what happens}

The code inside the finally block will always be executed. This is also true for cases when there is an exception or even executed return statement in the try block.

Three things can happen in a try block. First, no exception is thrown:

ExampleCode section 2: No exception is thrown.
System.out.println("Before the try block");try{System.out.println("Inside the try block");}catch(MyException1e){System.out.println("Handle the Exception1");}catch(MyException2e){System.out.println("Handle the Exception2");}finally{System.out.println("Execute the finally block");}System.out.println("Continue");
Standard input or outputConsole for Code section 2
Before the try block Inside the try block Execute the finally block Continue 

You can see that we have passed in the try block, then we have executed the finally block and we have continued the execution. Now, a caught exception is thrown: |

ExampleCode section 3: A caught exception is thrown.
System.out.println("Before the try block");try{System.out.println("Enter inside the try block");thrownewMyException1();System.out.println("Terminate the try block");}catch(MyException1e){System.out.println("Handle the Exception1");}catch(MyException2e){System.out.println("Handle the Exception2");}finally{System.out.println("Execute the finally block");}System.out.println("Continue");
Standard input or outputConsole for Code section 3
Before the try block Enter inside the try block Handle the Exception1 Execute the finally block Continue 


We have passed in the try block until where the exception occurred, then we have executed the matching catch block, the finally block and we have continued the execution. Now, an uncaught exception is thrown:

ExampleCode section 4: An uncaught exception is thrown.
System.out.println("Before the try block");try{System.out.println("Enter inside the try block");thrownewException();System.out.println("Terminate the try block");}catch(MyException1e){System.out.println("Handle the Exception1");}catch(MyException2e){System.out.println("Handle the Exception2");}finally{System.out.println("Execute the finally block");}System.out.println("Continue");
Standard input or outputConsole for Code section 4
Before the try block Enter inside the try block Execute the finally block 


We have passed in the try block until where the exception occurred and we have executed the finally block. NO CODE after the try-catch block has been executed. If there is an exception that happens before the try-catch block, the finally block is not executed.

If return statement is used inside finally, it overrides the return statement in the try-catch block. For instance, the construct

ExampleCode section 5: Return statement.
try{return11;}finally{return12;}

will return 12, not 11. Professional code almost never contains statements that alter execution order (like return, break, continue) inside the finally block, as such code is more difficult to read and maintain.

float

[edit | edit source]

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.

Syntax:

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

For example:

Computer code
floatprice=49.95;


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 ::= forcondition-clausesingle-statement | block-statement condition-clause  ::= ( before-statement;  Boolean Expression ; after-statement ) single-statement  ::= Statement block-statement  ::= {Statement [ Statement ] }

For example:

Computer code
for(inti=0;i<maxLoopIter;i++){System.println("Iter: "+i);}


See also:

goto is a reserved keyword, presently not being used.

if is a Java keyword. It starts a branching statement.

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

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

For example:

Computer code
if(booleanExpression){System.out.println("'True' statement block");}else{System.out.println("'False' statement block");}

See also:

implements

[edit | edit source]

implements is a Java keyword.

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

Syntax:

Computer code
publicclassMyClassimplementsMyInterface1,MyInterface2{...}


See also:

import

[edit | edit source]

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:

Computer code
importpackage.JavaClass;importpackage.*;


The static import construct allows unqualified access to static members without inheriting from the type containing the static members:

 import static java.lang.Math.PI; 

Once the static members have been imported, they may be used without qualification:

 double r = cos(PI * theta); 

Caveat: use static import very sparingly to avoid polluting the program's namespace!

See also:

instanceof

[edit | edit source]

instanceof is a keyword.

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

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

Syntax:

<object-reference> instanceof TypeName 

For example:

Computer code
classFruit{//... }classAppleextendsFruit{//...}classOrangeextendsFruit{//...}publicclassTest{publicstaticvoidmain(String[]args){Collection<Object>coll=newArrayList<Object>();Appleapp1=newApple();Appleapp2=newApple();coll.add(app1);coll.add(app2);Orangeor1=newOrange();Orangeor2=newOrange();coll.add(or1);coll.add(or2);printColl(coll);}privatestaticStringprintColl(Collection<?>coll){for(Objectobj:coll){if(objinstanceofObject){System.out.print("It is a Java Object and");}if(objinstanceofFruit){System.out.print("It is a Fruit and");}if(objinstanceofApple){System.out.println("it is an Apple");}if(objinstanceofOrange){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


Computer code
interfaceEdible{//...}


and the classes modified such that they implemented this interface


Computer code
classOrangeextendsFruitimplementsEdible{...}


we could ask if our object were edible.


Computer code
if(objinstanceofEdible){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.

Syntax:

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

For example:

Computer code
inti=65;


See also:

interface

[edit | edit source]

interface is a Java keyword. It starts the declaration of a Java Interface.

For example:

Computer code
publicinterfaceSampleInterface{publicvoidmethod1();//...}

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.

Syntax:

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

For example:

Computer code
longtimestamp=1269898201;


See also:

native

[edit | edit source]

native is a java keyword. It marks a method, that it will be implemented in other languages, not in Java. The method is declared without a body and cannot be abstract. It works together with JNI (Java Native Interface).

Syntax:

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

Native methods were used in the past to write performance critical sections but with java getting faster this is now less common. Native methods are currently needed when

  • You need to call from java a library, written in another language.
  • You need to access system or hardware resources that are only reachable from the other language (typically C). Actually, many system functions that interact with real computer (disk and network IO, for instance) can only do this because they call native code.

To complete writing native method, you need to process your class with javah tool that will generate a header code in C. You then need to provide implementation of the header code, produce dynamically loadable library (.so under Linux, .dll under Windows) and load it (in the simplest case with System.load(library_file_name) . The code completion is trivial if only primitive types like integers are passed but gets more complex if it is needed to exchange strings or objects from the C code. In general, everything can be on C level, including creation of the new objects and calling back methods, written in java.

To call the code in some other language (including C++), you need to write a bridge from C to that language. This is usually trivial as most of languages are callable from C.

See also

[edit | edit source]
  • [1] - JNI programming tutorial.
  • [2] - JNI specification.

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>(); 

For example:

Computer code
LinkedListlist=newLinkedList();int[]intArray=newint[10];String[][]stringMatrix=newString[5][10];


See also:

package

[edit | edit source]

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 ensure that the package name will be unique across vendors, usually the company url is used starting in backword.

Syntax:

package package; 

For example:

Computer code
packagecom.mycompany.myapplication.mymodule;


See also:

private

[edit | edit source]

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

Please note: Because access modifiers are not handled at instance level but at class level, private members of an object are visible from other instances of the same class!


Syntax:

privatevoid method(); 

See also:

protected

[edit | edit source]

protected is a Java keyword.

This keyword is an access modifier, used before a method or other class member to signify that the method or variable can only be accessed by elements residing in its own class or classes in the same package (as it would be for the default visibility level) but moreover from subclasses of its own class, including subclasses in foreign packages (if the access is made on an expression, whose type is the type of this subclass).

Syntax:

protected <returnType> <methodName>(<parameters>); 

For example:

Computer code
protectedintgetAge();protectedvoidsetYearOfBirth(intyear);


See also:

public

[edit | edit source]

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 encapsulation 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.

Computer codeCode listing: Length.java
packageorg.wikibooks.java;publicclassLength{privatedoublemagnitude;privateStringunits;publicLength(doublemagnitude,Stringunits){if((units==null)||(units.trim().length()==0)){thrownewIllegalArgumentException("non-null, non-empty units required.");}this.magnitude=magnitude;this.units=units;}publicdoublegetMagnitude(){returnthis.magnitude;}publicStringgetUnits(){returnthis.units;}}

return

[edit | edit source]

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

[edit | edit source]

short is a keyword. It defines a 16 bit signed integer primitive type.

Syntax:

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

For example:

Computer code
shortage=65;


See also:

static

[edit | edit source]

static is a Java keyword. It can be applied to a field, a method or an inner class. A static field, method or class has a single instance for the whole class that defines it, even if there is no instance of this class in the program. For instance, a Java entry point (main()) has to be static. A static method cannot be abstract. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and before the final keyword:

ExampleCode section 1: Static field and method.
publicstaticfinaldoublePI=3.1415926535;publicstaticvoidmain(finalString[]arguments){//…}

The static items can be called on an instantiated object or directly on the class:

ExampleCode section 2: Static item calls.
doubleaNumber=MyClass.PI;MyClass.main(newString[0]);

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

Interest

[edit | edit source]
  • Static variables can be used as data sharing amongst objects of the same class. For example to implement a counter that stores the number of objects created at a given time can be defined as so:
Computer codeCode listing 1: CountedObject.java
publicCountedObject{privatestaticintcounter;publicAClass(){counter++;}publicintgetNumberOfObjectsCreated(){returncounter;}}

The counter variable is incremented each time an object is created.

Public static variable should not be used, as these become global variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:

ExampleCode section 3: Constant definition.
publicstaticfinalStringCONSTANT_VAR="Const";
  • Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
Computer codeCode listing 2: ArithmeticToolbox.java
publicArithmeticToolbox{publicstaticintaddTwoNumbers(finalintfirstNumber,finalintsecondNumber){returnfirstNumber+secondNumber;}}
See also Static methods

strictfp

[edit | edit source]

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.

Syntax for classes:

publicstrictfpclass MyClass { //... } 

Syntax for methods:

publicstrictfpvoid method() { ... } 

See also:

super

[edit | edit source]

super is a keyword.

  • It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.
  • It is also used by class constructors to invoke constructors of its parent class.
  • Super keyword are not used in static Method.

Syntax:

super.<method-name>([zero or more arguments]); 

or:

super([zero or more arguments]); 

For example:

Computer codeCode listing 1: SuperClass.java
publicclassSuperClass{publicvoidprintHello(){System.out.println("Hello from SuperClass");return;}}
Computer codeCode listing 2: SubClass.java
publicclassSubClassextendsSuperClass{publicvoidprintHello(){super.printHello();System.out.println("Hello from SubClass");return;}publicstaticmain(String[]args){SubClassobj=newSubClass();obj.printHello();}}

Running the above program:

Computer codeCommand for Code listing 2
$Java SubClass 
Computer codeOutput of Code listing 2
Hello from SuperClass Hello from SubClass 

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

ExampleCode section 1: A lower bound on a wildcard type parameter.
publicvoidsort(Comparator<?superT>comp){...}

See also:


switch

[edit | edit source]

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:

Computer code
intvar= 3;switch(var){case1:System.out.println("Case: 1");System.out.println("Execute until break");break;case2:System.out.println("Case: 2");System.out.println("Execute until break");break;case3:System.out.println("Case: 3");System.out.println("Execute until break");break;case4: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":

Computer code
intvar= 3;if(var== 1 ) {System.out.println("Case: 1");System.out.println("Execute until break");}elseif(var== 2 ) {System.out.println("Case: 2");System.out.println("Execute until break");}elseif(var== 3 ) {System.out.println("Case: 3");System.out.println("Execute until break");}elseif(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

[edit | edit source]

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 [3].

The synchronized keyword can be used in two ways:

A synchronized block is marked as:

ExampleCode section 1: 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.}

The syntax to mark a method synchronized is:

ExampleCode section 2: Synchronized method.
publicsynchronizedvoidmethod(){// Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as// calling { synchronized(this) {…} }.}

The synchronization is always associated to an object. If the method is static, the associated object is the class. If the method is non-static, the associated object is the instance. While it is allowed to declare an abstract method as synchronized, it is meaningless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation.

As an example, we can show a thread-safe version of a singleton:

Computer codeCode listing 1: Singleton.java
/** * The singleton class that can be instantiated only once with lazy instantiation */publicclassSingleton{/** Static class instance */privatevolatilestaticSingletoninstance=null;/** * Standard private constructor */privateSingleton(){// Some initialisation}/** * Getter of the singleton instance * @return The only instance */publicstaticSingletongetInstance(){if(instance==null){// If the instance does not exist, go in time-consuming// section:synchronized(Singleton.class){if(instance==null){instance=newSingleton();}}}returninstance;}}

this is a Java keyword. It contains the current object reference.

  1. Solves ambiguity between instance variables and parameters .
  2. Used to pass current object as a parameter to another method .

Syntax:

this.method(); or this.variable; 

Example #1 for case 1:

Computer code
publicclassMyClass{//...privateStringvalue;//...publicvoidsetMemberVar(Stringvalue){this.value=value;}}

Example #2 for case 1:

Computer code
publicclassMyClass{MyClass(inta,intb){System.out.println("int a: "+a);System.out.println("int b: "+b);}MyClass(inta){this(a,0);}//...publicstaticvoidmain(String[]args){newMyClass(1,2);newMyClass(5);}}

throw

[edit | edit source]

throw is a keyword; it 'throws' an exception. In a throw statement, the three types of objects that can be thrown are: Exception, java:Throwable, and java:Error

Syntax:

throw <Exception Ref>; 

For example:

Computer code
publicCustomerfindCustomer(Stringname)throws'''CustomerNotFoundException'''{CustomercustRet=null;Iteratoriter=_customerList.iterator();while(iter.hasNext()){Customercust=(Customer)iter.next();if(cust.getName().equals(name)){// --- Customer find --custRet=cust;break;}}if(custRet==null){// --- Customer not found ---thrownew'''CustomerNotFoundException'''("Customer "+name+" was not found");}returncustRet}


See also

[edit | edit source]

throws

[edit | edit source]

throws is a Java keyword. It is used in a method definition to declare the Exceptions to be thrown by the method.

Syntax:

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

Example:

Computer code
classMyDefinedExceptionextendsException{publicMyDefinedException(Stringstr){super(str);}}publicclassMyClass{publicstaticvoidshowMyName(Stringstr)throwsMyDefinedException{if(str.equals("What is your Name?"))thrownewMyDefinedException("My name is Blah Blah");}publicstaticvoidmain(Stringa[]){try{showMyName("What is your Name?");}catch(MyDefinedExceptionmde){mde.printStackTrace();}}}

transient

[edit | edit source]

transient is a Java keyword which 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 intentionally.

Syntax:

privatetransient <member-variable>; or transientprivate <member-variable>; 


For example:

Computer code
publicclassFooimplementsSerializable{privateStringsaveMe;privatetransientStringdontSaveMe;privatetransientStringpassword;//...}

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 to any of the catch part of the block. If the Exception matches with one of the Exceptions 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:

Computer code
publicvoidmethod()throwsNoMatchedException{try{//...thrownew'''MyException_1'''();//...}catch(MyException_1e){// --- '''Handle the Exception_1 here''' --}catch(MyException_2e){// --- 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:

Computer code
publicvoidmethod(){//...return;// -- In this case the return is optional//and not necessary to use public but some changes will be there}

See also:

volatile

[edit | edit source]

volatile is a keyword.

When member variables are marked with this keyword, it changes the runtime behavior in a way that is noticeable when multiple threads access these variables. Without the volatile keyword, one thread could observe another thread update member variables in an order that is not consistent with what is specified in sourcecode. Unlike the synchronized keyword, concurrent access to a volatile field is allowed.

Syntax:

privatevolatile <member-variable>; or volatileprivate <member-variable>; 


For example:

Computer code
privatevolatilechangingVar;


See also:

while

[edit | edit source]

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 ::= whilecondition-clausesingle-statement | block-statement condition-clause  ::= ( Boolean Expression ) single-statement  ::= Statement block-statement  ::= {Statement [ Statements ] }

For example:

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

See also:


close