Java Programming/Keywords
Navigate Language Fundamentals topic: ) |
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
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
[edit] abstract
abstract
is a Java keyword. ... It declares a class abstract
, not all its methods are defined/implemented. Objects are not normally created from an abstract
class. Rather, they are created from either a non-abstract subclass, or by having the functions declared alongside a new statement (which is not recommended).
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
class
ClassName orabstract
public
class
ClassName
and for methods in an abstract class :
public
abstract
void methodName(); // --- No body, no implementation --- orabstract
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 and gives a default behavior. --- public void normalMethod() { ... } } |
[edit] assert
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
.
Assertions may be declared using the following syntax:
![]() |
assert expression1 [: 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:
![]() |
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, 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.
[edit] boolean
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 synchronized
.
![]() |
private boolean initialized = false;
public synchronized void { 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.
[edit] break
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:
[edit] byte
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:
![]() |
byte b = 65;
|
or
![]() |
byte b = 'A'
|
The number 65 is the code for 'A' in ASCII.
See also:
[edit] case
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."); } |
[edit] catch
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:
[edit] char
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 a char
value but an object reference is required.
Syntax:
char
<variable-name> = '<character>';
For example:
![]() |
char oneChar1 = 'A';
char oneChar2 = 65; |
65 is the numeric representation of character 'A' , or its ASCII code.
![]() |
System.out.println( oneChar1 );
System.out.println( oneChar2 ); |
outputs the following:
A A
See also:
[edit] class
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:
[edit] const
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.
[edit] continue
continue
is a Java keyword. It skips the remainder of the loop and continues 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:
[edit] default
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:
[edit] do
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 { //statements; } while (condition); |
For example:
![]() |
do { i++; } while ( i < maxLoopIter ); |
See also:
[edit] double
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:
![]() |
double d = 65.55;
|
See also:
[edit] else
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 ( expression ) {
System.out.println("'True' statement block"); } else { System.out.println("'False' statement block"); } |
See also:
[edit] enum
enum
is a keyword since Java 1.5.
This keyword defines a group of constants.
For example:
![]() |
/** Grades of courses */
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);
/** * Assigns the grade for this course to the student * @param GRADE Grade to be assigned */ public void assignGrade(final Grade GRADE) { grade = GRADE; } |
An enum may also have parameters:
![]() |
public enum DayOfWeek {
/** Enumeration constants */ MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(0); /** Code for the days of the week */ private byte dayCode = 0; /** * Private constructor * @param VALUE Value that stands for a day of the week. */ private DayOfWeek(final byte VALUE) { dayCode = java.lang.Math.abs(VALUE%7); } /** * Gets the day code * @return The day code */ public byte getDayCode() { return dayCode; } } |
An enum may also implement interfaces besides java.lang.Comparable
and java.io.Serializable
, which it already implicitly implements:
![]() |
public enum DayOfWeek implements Runnable {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; /** * Run method prints all elements */ public void run() { System.out.println("name() = " + name() + ", toString() = \"" + toString() + "\""); } } |
[edit] extends
extends
is a Java keyword.
Used in class
and interface
definition to declare the class or interface that is to be extended.
Syntax:
![]() |
public class MyClass extends SuperClass
{ //... } public interface MyInterface extends SuperInterface { //... } |
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> { /*...*/ }
|
See also:
[edit] final
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 thefinal
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:
[edit] finally
finally
is a keyword.
It is an optional part of a try
block. 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:
- 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.
If return
statement is used inside finally, it overrides the return statement in the try-catch block. For instance, the construct
![]() |
try {
return 11; } finally { return 12; } |
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.
See also:
- Java Programming/Keywords/try
- Java Programming/Keywords/catch
- Java Programming/Throwing and Catching Exceptions#Catching Rule
[edit] float
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:
![]() |
float price = 49.95;
|
See also:
[edit] for
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:
[edit] goto
goto
is a reserved keyword, presently not being used.
[edit] if
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:
[edit] implements
implements
is a Java keyword.
Used in class
definition to declare the Interfaces that are to be implemented by the class.
Syntax:
![]() |
public class MyClass implements MyInterface1, MyInterface2
{ ... } |
See also:
- Java Programming/Creating Objects
- Java Programming/Keywords/class
- Java Programming/Keywords/interface
[edit] import
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.*; |
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:
[edit] instanceof
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 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:
![]() |
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"); } |
[edit] int
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:
![]() |
int i = 65;
|
See also:
[edit] interface
interface
is a Java keyword. It starts the declaration of a Java Interface.
For example:
![]() |
public interface SampleInterface
{ public void method1(); //... } |
See also:
[edit] long
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:
![]() |
long timestamp = 1269898201;
|
See also:
[edit] native
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();
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 other 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] new
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:
![]() |
LinkedList list = new LinkedList();
int[] intArray = new int[10]; String[][] stringMatrix = new String[5][10]; |
See also:
[edit] package
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:
![]() |
package com.mycompany.myapplication.mymodule;
|
See also:
[edit] private
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!
Syntact:
private
void
method();
See also:
[edit] protected
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 not 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:
![]() |
protected int getAge();
protected void setYearOfBirth(int year); |
See also:
[edit] public
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.
![]() |
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; } } |
[edit] return
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 orreturn
; // --- Returns nothing
[edit] short
short
is a keyword. It defines a 16 bit signed integer primitive type.
Syntax:
short
<variable-name> = <integer-value>;
For example:
![]() |
short age = 65;
|
See also:
[edit] static
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.
Syntax for variables:
public
static
variableName;
Syntax for methods :
public
static
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) { //... } |
[edit] strictfp
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:
public
strictfp
class
MyClass { //... }
Syntax for methods:
public
strictfp
void
method() { ... }
See also:
[edit] super
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 can not be called. Only public and protected methods can be called by the
super
keyword. - It is also used by class constructors to invoke constructurs of its parent class.
Syntax:
super
.<method-name>();
For example:
![]() |
public class SuperClass
{ public void printHello() { System.out.println( <code><font style="color:DarkGreen; text-decoration: none; font-weight: bold;">"Hello from SuperClass"</font></code> ); return; } } //... public class SubClass extends SuperClass { public void printHello() { super.printHello(); System.out.println( <code><font style="color:DarkGreen; text-decoration: none; font-weight: bold;">"Hello from SubClass"</font></code> ); 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) { ... }
[edit] switch
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:
[edit] synchronized
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:
- Mark a method
synchronized
- Create a
synchronized
block
The syntax to mark a method synchronized
is
public
synchronized
void
method() { // Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as // calling { synchronized(this) {…} }. }
A synchronized
block is marked as
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.
}
[edit] Singleton example
As an example, we can show a thread-safe version of a singleton:
/** * The singleton class that can be instantiated only once with lazy instantiation */ public class Singleton { /** Static class instance */ private volatile static Singleton instance = null; /** * Standard private constructor */ private Singleton() { // Some initialisation } /** * Getter of the singleton instance * @return The only instance */ public static Singleton getInstance() { if (instance == null) { // If the instance does not exist, go in time-consuming // section: synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } }
[edit] this
this
is a Java keyword. It contains the current object reference.
Syntax:
this
.method(); orthis
.variable;
Example #1:
![]() |
public class MyClass
{ //... private String _memberVar; //... public void setMemberVar( String value ) { this._memberVar= value; } } |
Example #2:
![]() |
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); } } |
[edit] throw
throw
is a keyword. It 'throws' an exception.
Syntax:
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:
[edit] throws
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
{
...
}
Example:
![]() |
class MyDefinedException extends Exception
{ public MyDefinedException(String str) { super(str); } } public class MyClass { public static void showMyName(String str) throws MyDefinedException { if(str.equals("What is your Name?")) throw new MyDefinedException("My name is Blah Blah"); } public static void main(String a[]) { try { showMyName("What is your Name?"); } catch(MyDefinedException mde) { mde.printStackTrace(); } } } |
[edit] transient
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:
private
transient
<member-variable>; ortransient
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
[edit] try
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:
- Java Programming/Keywords/catch
- Java Programming/Keywords/finally
- Java Programming/Throwing and Catching Exceptions#Catching Rule
[edit] void
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:
[edit] volatile
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:
private
volatile
<member-variable>; orvolatile
private
<member-variable>;
For example:
![]() |
private volatile changingVar;
|
See also:
[edit] while
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: