50 Java Keywords With Examples
50 Java Keywords With Examples
1) abstract: abstract keyword is used to implement the abstraction in java. A method which
doesnt have method definition must be declared as abstract and the class containing it must
be declared as abstract. You cant instantiate abstract classes. Abstract methods must be
implemented in the sub classes. You cant use abstract keyword with variables and
constructors.
In the computer science perspective, Abstraction is the process of separating ideas from their
action. (Courtesy: Wiki). Yes, In the computer science, Abstraction is used to separate ideas
from their implementation. Abstraction in java is used to define only ideas in one class so that
the idea can be implemented by its sub classes according to their requirements. For example,
Abstract Classes:
Abstract classes contain abstract methods (you can refer them as ideas) so that they can be
implemented in sub classes according to their requirements. They are also called as
incomplete classes as they have some unimplemented abstract methods(ideas).
Lets discuss some rules need to follow while using abstract classes and abstract methods.
Abstract classes and abstract methods are declared using abstractkeyword. We cant
create objects to those classes which are declared as abstract. But, we can create objects to
sub classes of abstract class, provided they must implement abstract methods.
abstract class AbstractClass
{
abstract void abstractMethod();
}
class ConcreteClass extends AbstractClass
{
void abstractMethod()
{
System.out.println("Abstract Method Implemented");
}
}
public class Abstraction
{
public static void main(String[] args)
{
//AbstractClass A = new AbstractClass(); Can't create objects to
Abstract class
ConcreteClass C = new ConcreteClass();
//ConcreteClass implements abstract method,
//so we can create object to ConcreteClass
AbstractClass A1 = C;
//ConcreteClass object is auto-upcasted to AbsractClass
}
}
The methods which are not implemented or which dont have definitions must be declared
with abstract keyword and the class which contains it must be also declared as abstract.
It is not compulsory that abstract class must have abstract methods. It may or may not have
abstract methods. But the class which has at least one abstract method must be declared as
abstract.
You cant create objects to abstract class even though it does not contain any abstract
methods.
abstract class AbstractClass
{
void methodOne()
{
//Concrete Method
}
void methodTwo()
{
//Concrete Method
}
}
public class Abstraction
{
public static void main(String[] args)
{
AbstractClass a = new AbstractClass(); //Compile time error
//You can't create objects to AbstractClass
//even though it does not contain any abstract methods.
}
}
Any class extending an abstract class must implement all abstract methods. If it does not
implement, it must be declared as abstract.
Inside abstract class, we can keep any number of constructors. If you are not keeping any
constructors, then compiler will keep default constructor.
Abstract methods can not be private. Because, abstract methods must be implemented
somehow in the sub classes. If you declare them as private, then you cant use them outside
the class.
Thats it for today. Tomorrow we will discuss about interfaces, another way of implementing
abstraction in java.
2) assert: assert keyword is used in the assertion statements. These statements will enable
you to test your assumptions about a program. Assertion statements provide the best way to
detect and correct the programming errors. Assertion statements take one boolean expression
as input and assumes that this will be always true. If the boolean expression returns false,
AssertionError will be thrown.
3) boolean: boolean keyword is used to define boolean type variables. boolean type variables
can hold only two values either true or false.
4) break: The break keyword is used to stop the execution of a loop(for, while, switch-case)
based on some condition.
5) byte: byte keyword is used to declare byte type of variables. A byte variable can hold a
numeric value in the range from -128 to 127.
byte b = 50;
6) switch 7) case: Both switch and case keywords are used in the switch-case statement.
8) try 9) catch 10) finally: try, catch and finally keywords are used to handle the
exceptions in java. The statements which are to be monitored for exceptions are kept in the
try block. The exceptions thrown by the try block are caught in the catch block. finally block
is always executed. [See more]
Today we will discuss about try, catch and finally keywords. Remaining keywords will be
discussed in subsequent concepts.
try, catch and finally keywords are main fundamentals of exception handling in java. The
syntax for using these three keywords is,
try
{
//This is the try block
//In this block, keep those statements which may
//throw run time exceptions
}
catch(Exception e)
{
//This is the catch block.
//It takes one argument of type java.lang.Exception
//This block catches the exceptions thrown by try block
}
finally
{
//This is the finally block.
}
try block : In try block, keep those statements which may throw exceptions during run time.
catch block : This block handles the exceptions thrown by try block. It takes one argument
of type java.lang.Exception.
finally block : Whether exception is thrown or not and thrown exception is caught or not,
this block will be always executed. For example,
In the above example, A string array, containing valid and invalid numeric values, is iterated
through for loop. Each element of an array is parsed to primitive int type. Element with valid
numeric value is parsed without throwing an exception. Element with invalid numeric value
can not be parsed to int type and it throws the NumberFormatException. This exception is
caught in catch block making the flow of the program normal. finally block is executed for
every iteration whether element is parsed or not.
When a statement throws an exception in the try block, the remaining part of the try block
will not be executed. Program control comes out of the try block and enters directly into
catch block.
try, catch and finally blocks form one unit. i.e You cant keep other statements in between
try, catch and finally blocks.
try
{
int i = 10/0; //This statement throws ArithmeticException
System.out.println("This statement will not be executed");
}
//You can't keep statements here
catch(ArithmeticException ex)
{
System.out.println("This block is executed immediately after an
exception is thrown");
}
//You can't keep statements here
finally
{
System.out.println("This block is always executed");
}
You can display the description of an exception thrown using Exception object in the catch
block.
11) char: char keyword is used to declare primitive char type variables. char represents the
characters in java.
char a = 'A';
char b = 'B';
char c = 'C';
class MyClass
{
class MyInnerClass
{
//Inner Class
}
}
13) continue: continue keyword is used to stop the execution of current iteration and start the
execution of next iteration in a loop.
14) default: default keyword is used to define the default methods in an interface (From Java
8). default keyword is also used in the switch-case statements.
interface MyInterface
{
public default void myDefaultMethod()
{
System.out.println("Default Method");
}
}
15) do: do keyword is used in a dowhile loop. do-while loop is used to execute one or more
statements repetitively until a condition returns false.
16) double: double keyword is used to declare primitive double type of variables.
17) if 18) else: if and else keywords are used in if-else block.
enum MyEnums
{
A, B, C, D;
}
20) extends: extends keyword is used in inheritance. It is used when a class extends another
class.
class SuperClass
{
//Super Class
}
class SubClass extends SuperClass
{
//Sub Class
}
21) final: final keyword is used when a class or a method or a field doesnt need further
modifications. final class cant be extended, final method cant be overridden and the value of
a final field cant be changed. [See more]
In this post, we will discuss some about 10 important points about final keyword which every
java programmer should know. Lets start with some simple basic things about final keyword
in java.
We cant create a subclass to the class or we cant extend a class or we cant modify a class
which is declared as final.
We cant override a method or we cant modify a method in the sub class which is declared
as final in the super class.
class SuperClass
{
final void methodOne()
{
//some statements
}
}
class SubClass extends SuperClass
{
@Override
void methodOne()
{
//Compile time error
//can not override final method
}
}
The value of a final variable can not be changed in the whole execution once it got initialized.
class AnyClass
{
final int i = 10;
void methodOne()
{
i = 20; //compile time error
//final field can not be re-assigned
}
}
1) Any class or any method can be either abstract or final but not both. abstract and final are
totally opposite. Because, abstract class or abstract method must be implemented or modified
in the sub classes but final does not allow this. This creates an ambiguity.
2) final method can be overloaded and that overloaded method can be overridden in the sub
class.
class SuperClass
{
final void methodOne()
{
//final method
}
void methodOne(int i)
{
//final method can be overloaded
}
}
class SubClass extends SuperClass
{
@Override
void methodOne(int i)
{
//Overloaded method can be overridden
}
}
3) final variable cannot be re-initialized but final variable can be used to initialize other
variables.
class AnyClassOne
{
final int i = 10;
void methodOne()
{
i++;
//above statement gives Compile time error.
//value of final variable can not be changed
int j = i;//final variable can be used to initialize other
variables.
System.out.println(i); //final variable can be used
}
}
4) When an array reference variable is declared as final, only variable itself is final but not
the array elements.
5) When a reference variable is declared as final, you cant re-assign a new object to it once it
is referring to an object. But, you can change the state of an object to which final reference
variable is referring.
class A
{
int i = 10;
}
public class UseOfFinalKeyword
{
public static void main(String[] args)
{
final A a = new A(); //final reference variable
a.i = 50;
//you can change the state of an object to which final reference
variable is pointing
a = new A(); //compile time error
//you can't re-assign a new object to final reference variable
}
}
6) Static variables, non-static variables and local variables all can be final. once the final
variables are initialized, even you cant re-assign the same value.
class A
{
static final int i = 10; //final static variable
final int j = 20; //final non-static variable
void methodOne(final int k)
{
//k is final local variable
k = 20; //compile time error
}
}
public class UseOfFinalKeyword
{
public static void main(String[] args)
{
A a = new ();
a.i = 10; //Compile time error
a.j = 20; //even you can't assign same value to final variables
a.methodOne(20);
}
}
7) If the global variables are not initialized explicitly, they get default value at the time of
object creation. But final global variables dont get default value and they must be explicitly
initialized at the time of object creation. Uninitialized final field is called Blank Final Field.
class A
{
int i; //Non-final global variable, no need to initialize them
final int j; //Blank Final Field
A()
{
j=20;
//final global variable must get a value at the time of object creation.
}
}
public class UseOfFinalKeyword
{
public static void main(String[] args)
{
A a = new A();
}
}
8) final non-static global variable must be initialized at the time of declaration or in all
constructors or in any one of IIBs Instance Initialization Blocks.
class A
{
final int i; //Final non-static global variable may be initialized
here OR
//may be initialized in any one of IIB's,
// because while object creation, all IIBs are called. OR
{
i = 30;
}
{
//i = 40;
}
//must be initialized in all constructors.
//because while object creation, only one constructor is called
A()
{
//i=20;
}
A(int j)
{
// i=j;
}
A(int j, int k)
{
// i = 50;
}
}
9) final static global variable must be initialized at the time of declaration or in any one of
SIBs Static Initialization Blocks. (final static global variable cant be initialized in
constructors)
A
{
static final int i; //final static global variable may be initialized here
OR
//may be initialized in any one of SIBs.
static
{
i = 30;
}
static
{
//i = 40;
}
//final static global variable can not be initialized in constructors
A()
{
//i=20;
}
A(int j)
{
//i=j;
}
A(int j, int k)
{
//i = 50;
}
}
10) The global variable which is declared as final and static remains unchanged for the whole
execution. Because, Static members are stored in the class memory and they are loaded only
once in the whole execution. They are common to all objects of the class. If you declare static
variables as final, any of the objects cant change their value as it is final. Therefore,
variables declared as final and static are sometimes referred to as Constants. All fields of
interfaces are referred as constants, because they are final and static by default.
22) float: float keyword indicates primitive float type of variables.
float f2 = 84.25f;
float f3 = f2 - f1;
System.out.println(f3);
}
}
23) for: for loop is used to execute the set of statements until a condition is true.
25) import: import keyword is used to import the members of a particular package into
current java file.
import java.sql.*;
import java.util.Arrays;
import java.util.Scanner;
Before discussing about static import in java, first lets know what normal import does.
Consider this java file.
package pack1;
public class A
{
//Member Of Pack1
}
If you want to use the member of pack1 (Class A) in another package, then you have to refer
it through package name like below.
package pack2;
//Member Of pack2
public class B
{
public static void main(String[] args)
{
pack1.A a = new pack1.A(); //Accessing member of pack1
}
}
It will be very annoying if pack1 member has to be used hundreds of times. Each time,
member has to be referred through its package name. You can avoid this using import
statement just after the package declaration statement. If you import the required package in
the current file, then you can access the members of that package without using package
name just like below.
package pack2;
import pack1.*; //Importing all members of pack1
//Member Of pack2
public class B
{
public static void main(String[] args)
{
A a = new A(); //Accessing member of pack1 without using package
name
}
}
Now come to static import in java. Using static import, you can access static members of a
class without referring them through their class name. For example,
package pack1;
public class A
{
public static int i; //Static Member
public static void methodOne()
{
//Static Member
}
}
The above static members of class A can be directly used in another package if you import
them as static.
package pack2;
import static pack1.A.*;//Importing all static members of Class A
public class B
{
public static void main(String[] args)
{
System.out.println(i);
//accessing static member of Class A without using class name.
methodOne();
//accessing static member of Class A without using class name.
}
}
Notes :
Using import statement, you can import only members of a package like classes, interfaces
etc into the current file.
Using static import, you can import only static members of a class like fields, methods etc
into the current file.
You can import only individual members of a package or a class like import pack1.A; or
import static pack1.A.i;
26) instanceOf: instanceOf is used to check whether an object is of specified type. The
syntax for using instanceOf keyword is Object_Reference instanceOf Type.
class A{ }
public class MainClass
{
public static void main(String[] args)
{
A a = new A();
if(a instanceof A)
{
System.out.println("a is of type A");
}
}
}
27) int: int keyword is used to declare primitive integer type of variables.
interface MyInterface
{
void myMethod();
}
29) long: long is used to define the primitive long type variables.
30) native: native keyword is used with a method to indicate that a particular method is
implemented in native code using Java Native Interfaces(JNI).
class AnyClass
{
public native void anyMethod(int i, double d);
}
31) new: new keyword is used while creating the instances of a class.
class A{ }
public class MainClass
{
public static void main(String[] args)
{
A a = new A();
}
}
32) package: package keyword is used to specify a package to which the current file belongs
to.
package pack1;
class A{ }
33) private: private keyword is used to declare a member of a class as private. private
methods and fields are visible within the class in which they are defined.
class A
{
private int i = 111; //private field
private void method()
{
//private method
}
}
class A
{
protected int i = 111; //protected field
protected void method()
{
//protected method
}
}
35) public: public keyword is used to declare the members of a class or class itself as public.
public members of a class are visible from anywhere and they can be inherited to any sub
classes.
public class A
{
public int i = 222; //public field
public A()
{
//public constructor
}
public void method()
{
//public method
}
}
36) return: return keyword is used to return the control back to the caller from the method.
class A
{
int method(int i)
{
return i*i; //method returning a value
}
}
37) short: short keyword is used to declare primitive short type variables.
short s1 = 11;
short s2 = 22;
38) static: static keyword is used to define the class level members of a class. static members
of a class are stored in the class memory and you can access them directly through class
name. No need to instantiate a class. [See more
class A
{
static int staticField = 555; //Static Field
static void staticMethod()
{
//Static method
}
}
public class MainClass
{
public static void main(String[] args)
{
System.out.println(A.staticField); //Accessing staticField via class name
A.staticMethod(); //Accessing staticMethod via class name
}
}
Static variables, Static Initialization Block and Static Methods these all are static
components or static members of a class. These static members are stored inside the Class
Memory. To access static members, you need not to create objects. Directly you can access
them with class name.
Static Initialization Block is used to initialize only static variables. It is a block without a
name. It contains set of statements enclosed within { }. The syntax of SIB looks like this,
static
{
//Set Of Statements
}
class StaticComponents
{
static int staticVariable;
static
{
System.out.println("StaticComponents SIB");
staticVariable = 10;
}
static void staticMethod()
{
System.out.println("From StaticMethod");
System.out.println(staticVariable);
}
}
public class MainClass
{
static
{
System.out.println("MainClass SIB");
}
public static void main(String[] args)
{
//Static Members directly accessed with Class Name
StaticComponents.staticVariable = 20;
StaticComponents.staticMethod();
}
}
Step 1: When you trigger >java MainClass, java command divides allocated memory into
two parts Stack and Heap. First, java command enters stack memory for execution. First, it
checks whether MainClass is loaded into heap memory or not. If it is not loaded, loading
operation of MainClass starts. Randomly some memory space is allocated to MainClass. It is
called Class memory. All static members are loaded into this class memory. There is only
one satic member in MainClass main() method. It is loaded into class memory of
MainClass.
Step 2: After loading all static members, SIB Static initialization Blocks are executed.
Remember, SIBs are not stored in the heap memory. They just come to stack, execute
their tasks and leaves the memory. So, after loading main() method, SIB of MainClass
enters stack for execution. There is only one statement (Line 22) in SIB. it is executed. It
prints MainClass SIB on console. After executing this statement, SIB leaves the stack
memory.
Step 3: Now, java command calls main() method for execution. main() method enters the
stack. First statement (Line 28) is executed first. First, It checks whether class
StaticComponents is loaded into memory. If it is not loaded, loading operation of
StaticComponents takes place. Randomly, some memory is allocated to Class
StaticComponents, then all static members of StaticComponents staticVariable and
staticMethod() are loaded into that class memory. staticVariable is a global variable. So,
first it is initialized with default value i.e 0.
Step 4: After loading all static members of StaticComponents, SIB blocks are executed. So,
SIB of class StaticComponents enters the stack for execution. First Statement (Line 7) is
executed. It prints StaticComponents SIB on the console. In the second statement, value 10
is assigned to staticVariable. There are no other statements left for execution, so it leaves
stack memory.
Step 5: Now control comes back to main() method. The remaining part of first statement i.e
value 20 is assigned to staticVariable of class StaticComponents, is executed. In the second
statement (Line 29), it calls staticMethod() of class StaticComponents for execution.
Step 6: staticMethod() of StaticComponents enters stack for execution. First statement (Line
13) is executed first. It prints From staticMethod on the console. In the second statement
(Line 14), it prints the value of staticVariable i.e 20 on the console. There are no statements
left. so, it leaves the stack.
Step 7: Again, control comes back to main() method. There are no other statements left in
main() method. so, it also leaves stack. java command also leaves the stack.
Output :
39) strictfp: strictfp keyword is used to implement the strict precision of floating point
calculations on different platforms. strictfp can be used with classes, interfaces and methods.
strictfp interface I
{
//strictfp applied on interface
}
strictfp class C
{
//strictfp applied on class
}
class A
{
strictfp void method()
{
//strictfp applied on method
}
}
40) super: super keyword is used to access super class members inside a sub class.
class A
{
int i;
public A(int i)
{
this.i = i;
}
void methodA()
{
System.out.println(i);
}
}
class B extends A
{
public B()
{
super(10); //Calling super class constructor
}
void methodB()
{
System.out.println(super.i); //accessing super class field
class AnyClass
{
synchronized void synchronizedMethod()
{
//Synchronized method
}
void anyMethod()
{
synchronized (this)
{
//Synchronized block
}
}
}
When a method or block is declared as synchronized, only one thread can enter into that
method or block. When one thread is executing synchronized method or block, the other
threads which wants to execute that method or block wait or suspend their execution until
first thread is done with that method or block. Thus avoiding the thread interference and
achieving thread safeness. This can be explained well with the help of an example.
class Shared
{
int i;
synchronized void SharedMethod()
{
Thread t = Thread.currentThread();
for(i = 0; i <= 1000; i++)
{
System.out.println(t.getName()+" : "+i);
}
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
final Shared s1 = new Shared();
Thread t1 = new Thread("Thread - 1")
{
@Override
public void run()
{
s1.SharedMethod();
}
};
Thread t2 = new Thread("Thread - 2")
{
@Override
public void run()
{
s1.SharedMethod();
}
};
t1.start();
t2.start();
}
}
In the above example, both threads t1 and t2 wants to execute sharedMethod() of s1 object.
But, sharedMethod() is declared as synchronized. So, whichever thread enters first into
sharedMethod(), it continues to execute that method. The other thread waits for first thread to
finish its execution of sharedMethod(). It never enters into sharedMethod() until first thread
is done with that method. That means, both threads are executing sharedMethod() one by one
not simultaneously. This protects the value of i in the memory for a particular thread.
The synchronization in java is built around an entity called object lock or monitor. Here is
the brief description about lock or monitor.
Whenever an object is created to any class, an object lock is created and is stored inside the
object.
One object will have only one object lock associated with it.
Any thread wants to enter into synchronized methods or blocks of any object, they must acquire
object lock associated with that object and release the lock after they are done with the
execution.
The other threads which want to enter into synchronized methods of that object have to wait
until the currently executing thread releases the object lock.
To enter into static synchronized methods or blocks, threads have to acquire class lock
associated with that class as static members are stored inside the class memory.
Synchronized Blocks:
Sometimes, you need only some part of the method to be synchronized not the whole method.
This can be achieved with synchronized blocks. Synchronized blocks must be defined inside
a definition blocks like methods, constructors, static initializer or instance initializer.
synchronized block takes one argument and it is called mutex. if synchronized block is
defined inside non-static definition blocks like non-static methods, instance initializer or
constructors, then this mutex must be an instance of that class. If synchronized block is
defined inside static definition blocks like static methods or static initializer, then this mutex
must be like ClassName.class.
class Shared
{
static void staticMethod()
{
synchronized (Shared.class)
{
//static synchronized block
}
}
void NonStaticMethod()
{
synchronized (this)
{
//Non-static synchronized block
}
}
void anotherNonStaticMethod()
{
synchronized (new Shared())
{
//Non-static synchronized block
}
}
}
1) You can use synchronized keyword only with methods but not with variables,
constructors, static initializer and instance initializers.
class Shared
{
synchronized int i;//compile time error, can't use synchronized keyword
with variables
synchronized public Shared()
{
//compile time error, constructors can not be synchronized
}
synchronized static
{
//Compile time error, Static initializer can not be synchronized
}
synchronized
{
//Compile time error, Instance initializer can not be synchronized
}
}
2) Constructors, Static initializer and instance initializer cant be declared with synchronized
keyword, but they can contain synchronized blocks.
class Shared
{
public Shared()
{
synchronized (this)
{
//synchronized block inside a constructor
}
}
static
{
synchronized (Shared.class)
{
//synchronized block inside a static initializer
}
}
{
synchronized (this)
{
//synchronized block inside a instance initializer
}
}
}
3) Both static and non-static methods can use synchronized keyword. For static methods,
thread need class level lock and for non-static methods, thread need object level lock.
class Shared
{
synchronized static void staticMethod()
{
//static synchronized method
}
synchronized void NonStaticMethod()
{
//Non-static Synchronized method
}
}
4) It is possible that both static synchronized and non-static synchronized methods can run
simultaneously. Because, static methods need class level lock and non-static methods need
object level lock.
5) A method can contain any number of synchronized blocks. This is like synchronizing
multiple parts of a method.
class Shared
{
static void staticMethod()
{
synchronized (Shared.class)
{
//static synchronized block - 1
}
synchronized (Shared.class)
{
//static synchronized block - 2
}
}
void NonStaticMethod()
{
synchronized (this)
{
//Non-static Synchronized block - 1
}
synchronized (this)
{
//Non-static Synchronized block - 2
}
}
}
7) Lock acquired by the thread before executing a synchronized method or block must
be released after the completion of execution, no matter whether execution is
completed normally or abnormally (due to exceptions).
10) Use synchronized blocks instead of synchronized methods. Because, synchronizing some
part of a method improves the performance than synchronizing the whole method.
42) this: this keyword is used to access other members of the same class.
class AnyClass
{
int i;
AnyClass()
{
System.out.println("First Constructor");
}
AnyClass(int j)
{
this(); //calling statement to First Constructor
System.out.println("Second Constructor");
}
void methodOne()
{
System.out.println("From method one");
}
void methodTwo()
{
System.out.println(this.i); //Accessing same class field
this.methodOne(); //Accessing same class method
}
}
Throwing An Exception :
We all know that Throwable class is super class for all types of errors and exceptions. An
object to this Throwable class or its sub classes can be created in two ways. First one is
using an argument of catch block. In this way, Throwable object or object to its sub classes
is implicitly created and thrown by java run time system. Second one is using new operator.
In this way, Throwable object or object to its sub classes is explicitly created and thrown by
the code.
An object to Throwable or to its sub classes can be explicitly created and thrown by using
throw keyword. The syntax for using throw keyword is, throw InstanceOfThrowableType.
where, InstanceOfThrowableType must be an object of type Throwable or subclass of
Throwable. Such explicitly thrown exception must be handled somewhere in the program,
otherwise program will be terminated. For example,
Re-throwing an Exception:
We all know that exceptions occurred in the try block are caught in catch block. Thus caught
exceptions can be re-thrown using throw keyword. Re-thrown exception must be handled
somewhere in the program, otherwise program will terminate abruptly. For example,
class ExceptionHandling
{
public static void main(String[] args)
{
try
{
methodWithThrow();
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException Re-thrown in
methodWithThrow() method will be handled here");
}
}
static void methodWithThrow()
{
try
{
String s = null;
System.out.println(s.length()); //This statement throws
NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is caught here");
44) throws: throws keyword is used to specify the exceptions which the current method may throw.
class A
{
void method() throws NumberFormatException
{
int i = Integer.parseInt("abc");
}
}
If a method is capable of throwing an exception that it could not handle, then it should
specify that exception using throws keyword. It helps the callers of that method in handling
that exception. The syntax for using throws keyword is,
where, exception_list is the list of exceptions that method may throw. Exceptions must be
separated by commas.
Lets see some of the points-to-remember about throws keyword. Multiple exceptions can be
declared using throws keyword separated by commas.
public class ExceptionHandling
{
static void methodWithThrows() throws NumberFormatException,
NullPointerException
{
int i = Integer.parseInt("abc");
//This statement throws NumberFormatException
String s = null;
System.out.println(s.length());
//This statement throws NullPointerException
}
public static void main(String[] args)
{
try
{
methodWithThrows();
}
catch(Exception ex)
{
System.out.println("This block can handle all types of
exceptions");
}
}
}
The main use of throws keyword in java is that an exception can be propagated through method
calls.
A
{
int i;
public A(String s) throws NumberFormatException
{
i = Integer.parseInt(s); //This statement throws
NumberFormatException
}
}
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
A a = new A("abc"); //Object creation statement
enclosed in try-catch block
}
catch (NumberFormatException ex)
{
System.out.println("NumberFormatException will be caught
here");
}
}
}
When a method is throwing unchecked type of exceptions, then you need not to mention it using
throws keyword. But for a method throwing checked type of exceptions, you must declare it with
throws keyword or enclose the statement which is throwing an exception in try-catch block. (We will
discuss about this in detail while covering checked and unchecked exceptions).
class ExceptionHandling
{
//method throwing Unchecked Exception declared without throws clause
static void methodThrowingUncheckedException()
{
int i = Integer.parseInt("abc");
//Above statement throws NumberFormatException which is unchecked
type of exception
}
//method throwing checked Exception declared with throws clause
static void methodThrowingCheckedException() throws
ClassNotFoundException
{
Class.forName("AnyClassName");
//Above statement throws ClassNotFoundException which is checked type of
exception
}
public static void main(String[] args)
{
try
{
methodThrowingUncheckedException();
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException will be caught
here");
}
try
{
methodThrowingCheckedException();
}
catch (ClassNotFoundException e)
{
System.out.println("ClassNotFoundException will be caught
here");
}
}
}
46) void: void keyword is used to indicate that method returns nothing.?
class A
{
void methodReturnsNothing()
{
//Method returns no value
}
}
47) volatile: volatile keyword is used in the concurrent programming. The value of a variable
which is declared as volatile will be written into or read from the main memory.
class A
{
public volatile int counter = 0;
}
Both goto and const are reserved words in java but they are currently not used.
Note: true, false and null are not the keywords. They are literals in java.
abstract: Abstract is used to implement the abstraction in java. A method which doesnt have
method definition must be declared as abstract and the class containing it must be declared as
abstract. You cant instantiate abstract classes. Abstract methods must be implemented in the sub
classes. You cant use abstract keyword with variables and constructors. In an abstract class, you can
keep abstract method(without body) and non-abstract method(with the body). By the help of
abstract keyword, we can make any class as abstract.
assert: (added in J2SE 1.4): Assert describes a predicate (a truefalse statement) placed in a java-
program to indicate that the developer thinks that the predicate is always true at that place. If an
assertion evaluates to false at run-time, an assertion failure results, which typically causes execution
to abort. Optionally enable by ClassLoader method.
boolean: Defines a boolean variable for the values "true" or "false" only. By default of the value of
boolean primitive type is false.
byte: The byte keyword is used to declare a field that can hold an 8-bit signed two's complement
integer. This keyword is also used to declare that a method returns a value of the primitive type
byte.
case: A statement in the switch block can be labeled with one or more case or default labels.
The switch statement evaluates its expression, then executes all statements that follow the
matching case label.
catch: Used in conjunction with a try block and an optional finally block. The statements in the
catch block specify what to do if a specific type of exception is thrown by the try block.
char: Defines a character variable capable of holding any character of the java source file's
character set.
class: A type that defines the implementation of a particular kind of object. A class definition
defines instance and class fields, methods, and inner classes as well as specifying the interfaces the
class implements and the immediate superclass of the class. If the superclass is not explicitly
specified, the superclass is implicitly Object. The class keyword can also be used in the form
Class.class to get a Class object without needing an instance of that class. For example, String.class
can be used instead of doing new String().getClass().
continue: Used to resume program execution at the end of the current loop body. If followed by a
label, continue resumes execution at the end of the enclosing labeled loop body.
default: The default keyword can optionally be used in a switch statement to label a block of
statements to be executed if no case matches the specified value, Alternatively, the default
keyword can also be used to declare default values in a Java annotation. From Java 8 onwards, the
default keyword is also used to specify that a method in an interface provides the default
implementation of a method.
do: The do keyword is used in conjunction with while to create a do-while loop, which executes a
block of statements associated with the loop and then tests a boolean expression associated with
the while. If the expression evaluates to true, the block is executed again; this continues until the
expression evaluates to false.
double: The double keyword is used to declare a variable that can hold a 64-bit double precision
IEEE 754 floating-point number. This keyword is also used to declare that a method returns a value
of the primitive type double.
else: The else keyword is used in conjunction with if to create an if-else statement, which tests a
boolean expression; if the expression evaluates to true, the block of statements associated with the
if are evaluated; if it evaluates to false, the block of statements associated with the else are
evaluated.
enum (added in J2SE 5.0): A Java keyword used to declare an enumerated type. Enumerations
extend the base class Enum.
extends: Used in a class declaration to specify the superclass; used in an interface declaration to
specify one or more superinterfaces. Class X extends class Y to add functionality, either by adding
fields or methods to class Y, or by overriding methods of class Y. An interface Z extends one or more
interfaces by adding methods. Class X is said to be a subclass of class Y; Interface Z is said to be a
subinterface of the interfaces it extends. Also used to specify an upper bound on a type parameter in
Generics.
final: Define an entity once that cannot be changed nor derived from later. More specifically: a
final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur
at most once as a left-hand expression on an executed command. All methods in a final class are
implicitly final.
finally: Used to define a block of statements for a block defined previously by the try keyword.
The finally block is executed after execution exits the try block and any associated catch
clauses regardless of whether an exception was thrown or caught, or execution left method in the
middle of the try or catch blocks using the return keyword.
float: The float keyword is used to declare a variable that can hold a 32-bit single precision IEEE
754 floating-point number. This keyword is also used to declare that a method returns a value of the
primitive type float.
for: The for keyword is used to create a for loop, which specifies a variable initialization, a boolean
expression, and an incrementation. The variable initialization is performed first, and then the
boolean expression is evaluated. If the expression evaluates to true, the block of statements
associated with the loop are executed, and then the incrementation is performed. The boolean
expression is then evaluated again; this continues until the expression evaluates to false.
As of J2SE 5.0, the for keyword can also be used to create a so-called "enhanced for loop", which
specifies an array or Iterable object; each iteration of the loop executes the associated block of
statements using a different element in the array or Iterable.
if: The if keyword is used to create an if statement, which tests a boolean expression; if the
expression evaluates to true, the block of statements associated with the if statement is executed.
This keyword can also be used to create an if-else statement.
Implements: Included in a class declaration to specify one or more interfaces that are
implemented by the current class. A class inherits the types and abstract methods declared by the
interfaces.
Import: Used at the beginning of a source file to specify classes or entire Java packages to be
referred to later without including their package names in the reference. Since J2SE 5.0, import
statements can import static members of a class.
Instanceof: A binary operator that takes an object reference as its first operand and a class or
interface as its second operand and produces a boolean result. The instanceof operator evaluates
to true if and only if the runtime type of the object is assignment compatible with the class or
interface.
int: The int keyword is used to declare a variable that can hold a 32-bit signed two's complement
integer. This keyword is also used to declare that a method returns a value of the primitive type int.
interface: Used to declare a special type of class that only contains abstract or default methods,
constant (static final) fields and static interfaces. It can later be implemented by classes that
declare the interface with the implements keyword. By the help of interface we can easily achieve
multiple inheritance in java. We can define one interface within another interface.
long: The long keyword is used to declare a variable that can hold a 64-bit signed two's
complement integer. This keyword is also used to declare that a method returns a value of the
primitive type long.
native: Used in method declarations to specify that the method is not implemented in the same
Java source file, but rather in another language.
new: Used to create an instance of a class or array object. Using keyword for this end is not
completely necessary (as exemplified by Scala), though it serves two purposes: it enables the
existence of different namespace for methods and class names, it defines statically and locally that a
fresh object is indeed created, and of what runtime type it is (arguably introducing dependency into
the code).
package: Java package is a group of similar classes and interfaces. Packages are declared with the
package keyword.
private: The private keyword is used in the declaration of a method, field, or inner class; private
members can only be accessed by other members of their own class.
protected: The protected keyword is used in the declaration of a method, field, or inner class;
protected members can only be accessed by members of their own class, that class's subclasses or
classes from the same package.
public: The public keyword is used in the declaration of a class, method, or field; public classes,
methods, and fields can be accessed by the members of any class.
return: Used to finish the execution of a method. It can be followed by a value required by the
method definition that is returned to the caller.
short: The short keyword is used to declare a field that can hold a 16-bit signed two's
complement integer. This keyword is also used to declare that a method returns a value of the
primitive type short.
static: Used to declare a field, method, or inner class as a class field. Classes maintain one copy of
class fields regardless of how many instances exist of that class. static also is used to define a
method as a class method. Class methods are bound to the class instead of to a specific instance,
and can only operate on class fields. (Classes and interfaces declared as static members of
another class or interface are actually top-level classes and are not inner classes.)
strictfp (added in J2SE 1.2): A Java keyword used to restrict the precision and rounding of
floating point calculations to ensure portability.
switch: The switch keyword is used in conjunction with case and default to create a switch
statement, which evaluates a variable, matches its value to a specific case, and executes the block
of statements associated with that case. If no case matches the value, the optional block labelled
by default is executed, if included.
synchronized: Used in the declaration of a method or code block to acquire the mutex lock for an
object while the current thread executes the code. For static methods, the object locked is the
class's Class. Guarantees that at most one thread at a time operating on the same object executes
that code. The mutex lock is automatically released when execution exits the synchronized code.
Fields, classes and interfaces cannot be declared as synchronized.
this: Used to represent an instance of the class in which it appears. this can be used to access
class members and as a reference to the current instance. The this keyword is also used to forward
a call from one constructor in a class to another constructor in the same class.
throw: Causes the declared exception instance to be thrown. This causes execution to continue with
the first enclosing exception handler declared by the catch keyword to handle an assignment
compatible exception type. If no such exception handler is found in the current method, then the
method returns and the process is repeated in the calling method. If no exception handler is found in
any method call on the stack, then the exception is passed to the thread's uncaught exception
handler.
throws: Used in method declarations to specify which exceptions are not handled within the
method but rather passed to the next higher level of the program. All uncaught exceptions in a
method that are not instances of RuntimeException must be declared using the throws
keyword.
transient: Declares that an instance field is not part of the default serialized form of an object.
When an object is serialized, only the values of its non-transient instance fields are included in the
default serial representation. When an object is deserialized, transient fields are initialized only to
their default value. If the default form is not used, e.g. when a serialPersistentFields table is declared
in the class hierarchy, all transient keywords are ignored.
try: Defines a block of statements that have exception handling. If an exception is thrown inside the
try block, an optional catch block can handle declared exception types. Also, an optional finally
block can be declared that will be executed when execution exits the try block and catch clauses,
regardless of whether an exception is thrown or not. A try block must have at least one catch
clause or a finally block.
void: The void keyword is used to declare that a method does not return any value.
volatile: Used in field declarations to specify that the variable is modified asynchronously by
concurrently running threads. Methods, classes and interfaces thus cannot be declared volatile, nor
can local variables or parameters.
while: The while keyword is used to create a while loop, which tests a boolean expression and
executes the block of statements associated with the loop if the expression evaluates to true; this
continues until the expression evaluates to false. This keyword can also be used to create a do-
while loop.
Unuseds
const: Although reserved as a keyword in Java, const is not used and has no function. For
defining constants in Java, see the final keyword.
goto: Although reserved as a keyword in Java, goto is not used and has no function.