There are near about 50 keywords ( reserved words) in core Java.The tables bellow demonstrate JAVA keywords with description and example and assigned alphabetically.Hope that you will find useful for learning or refreshing your memory......
Please inform me by posting comments if I am wrong...
keyword | description | example |
---|---|---|
Abstact | used in class and method declaration. Abstract class: 1) class must be declared with abstract keyword 2) methods in abstract class may or may not be abstract 3)If a class contains at-least one abstract method, the class must be declared as abstract. 4)Abstract methods must not be implemented in abstract class. Methods must be implemented in sub classes 5) An abstract class can not be instantiated, its solo mission is to be subclassed. |
abstact class Myclass // abstract class { public abstact void do();// is a abstract method public String getName() { } } |
Assert | followed by a boolean value (true or false), or an expression, to be evaluated at runtime, that returns a boolean value. If the boolean expression evaluates to false, then an AssertionError is thrown. | assert true; assert 50 == 50; // this will throw an Assertion Error: int test = 50; assert test == 100; |
boolean | is a data type which stores boolean value, i.e True or False. It is also used to declare methods that returns a value which is also a boolean. | boolean myFlag = true; |
break | One of the control statement to control the program flow. used to break the loop of switch statement. 1) Unlabeled Break statement 2) Labeled Break Statement | 1) Unlabeled Break statement for(int num =0; num < 5 ; var++) { System.out.println(“Num is : “ + num); if(num == 3) break; } 2)Labeled Break Statement Back: for(int num1=0; var1 < 10 ; num1++) { for(int num2 = 1; num2 < 10; num2++) { System.out.println(“num1:” + num1 + “, num2:” + num2); if(num1 == 5) break Back; } } |
byte | 8 bit signed 2's complement integer | byte b = -1; |
case | case is used in Switch statement |
switch ( value/variable to test ) {
case value: your code_here; break; case value: your code_here; break; default: value/variable_not_above;
}
|
catch | use with try block to catching exceptiion | try { code here} catch( exception ) {} |
char | character type in unicode | char test ="y" |
class | implementation of a particular kind of object which defines instance, class fields, methods,innner classes,interfaces as well as superclasses of class | class Person { private String name; public Person(String myName) { this.name = myName; } public void show() { System.out.println(name); } } classs Strudent extends Person { Pesron p = new Person(); p.show(); } |
const | is keyword in Java, but till now not used | |
continue | to skip the rest of the statement in body of the loop and continue with the next iteration of the loop 1)Unlabeled Continue 2)labeled Continue | 1)Unlabeled Continue for(int num1 =0; num1 < 15 ; num1++) { for(int num2=0 ; num2 <1 5 ; num2++) { if(num2 == 2) continue; System.out.println( num1 + num2); } } 2) Labeled Continue Back: for(int num1 =0; num1 < 5 ; num1++) { for(int num2=0 ; num2 < 5 ; num2++) { if(var2 == 2) continue Back; System.out.println( num1 + num2); } } |
default | can optionally be used in "Switch case" labelling a block of statement which is to be executed | see case |
do | use with while to form "do-while" loop uses boolean expression to execute block of statements | do { statement(s) } while (expression); |
double | 64-bit double precision IEEE 754 floating-point number | double mydouble = 0.05; |
else | use with "if " to form "if else" or "else if" statement tests boolean expression | int score = 79; char status; if (score >= 90) { status= 'A'; } else if (score >= 80) { status = 'B'; } else if (score >= 70) { status = 'C'; } else if (score >= 60) { status = 'D'; } else { status = 'F'; } System.out.println("status = " + grade); |
enum | enumeration is a type whose field consist of a fixed value of constant. It extends base class called Enum | public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } |
keyword | description | example |
---|---|---|
extends | use in declaration of subclass to specify the superclass for inheritance (inclusion of state and behaviour) | public name_of_ the_ subclass extends name_of _the_superclass { // code goes here.... } |
final | final can be applied in 1)method (can not overridden) 2)class (can not be subclassed ) 3) class variable (can not be change) 4)object (instantiate only once) | 1) class parent { final void print() { system.out.println("do this"); } } class child extends parent { final void print() // can not overridden { system.out.println("do") } } 2) String class can not be sub classed or instantiated 3) final int x=5; int x=10; // gives error 4) final Map map = new HashMap();
map.put(“param1”,”param2”);
map = new HashMap();
// error
|
finally | use in "try catch" block which is executed always | try { // code goes here } catch(exception){ //code goes here } finally { //code goes here } |
float | 32 bit single precision IEEE 754 floating point number | float b = 0.6F; |
for | Use for create a loop which separated by semicolon contains 1) an initialization 2) boolean expression 3) increment or decrement. The loop continue until boolean evaluates to false | for( initialization; boolean expression; ++/--) ie for(int i=0; i<=5; i++) { system.out.println(i); } |
goto | although is a keyword but not used | |
if | see else | |
implements | use for implementing "interface" which is abstract class and consists of abstract method/s | class myClass implements Test // here Test is an Interface { // methods here } |
import | use for import java class files or source files which are in package | import java.io.*; import myPackage.Test.*; |
instanceOf | is a operator takes an object reference as first operant and a class or interface as second operand and produces boolean result. | interface Animal{} class Mammal implements Animal{} class Dog extends Mammal { public static void main(String args[ ]) { Mammal m = new Mammal(); Dog d = new Dog(); System.out. println(m instanceof Animal); System.out. println(d instanceof Mammal); System.out. println(d instanceof Animal); } } // Out put true true true |
int | 32 bit signed 2's complement integer | int a=5; |
interface | is keyword used for declaring a by default abstract class in which methods are abstract and not implemented in that class and contains constant ( static final ) fields and static interfaces. 1) all the methods in interface are implicitly abstract and public 2) variable defined in interface are public, static and final so, we can say that interface can only declare constant , not instance variable 3)As interface methods are abstract, so they can not be marked as final or strictfp or native 4)Interface methods must not be final 5)Interface can extend one or more interfaces 6)Can only extend interface but not other thing. 7)Interface can not implement another class or interface 8)must be declared with keyword "interface" | public interface jumpable { abstract void jump(); void setJumpFactor(); } class Tire implements jumpable { public void jump( ) { //method implementation } public void setJumpFactor( ) { //method implementation } } |
long | 64 bit signed 2's complement integer | |
native | the "native" keyword is applied to method is implemented in native code using JNI (JAVA NATIVE INTERFACE). Native can be only applied to methods, not classes,not variables. netive method body must be a semicolon (;) directs that implementation is omitted. | |
new | use for creating new instance of class or object or array. The static class loading uses the "new" keyword. On error "NoClassDefFoundException" is thrown | class Parent{ private String name; public Person(String myName) { this.name = myName; } public void show() { System.out.println(name); } } classs child extends Person { // creating instance using new operator Pesron p = new Person(); p.show(); } |
null | NOT A KEYWORD in JAVA. It's a reserved constant to represent void reference | if( p!= null) { //code goes here } |
package | package is a folder where source files are stored and to use the file/files in the package use "import" statement. | package mypack; public class Test { public void do( String a) { } } To access the class in different package import mypack.Test; class class Test1 { Test t = new Test(); t.do(); } |
private | is an access modifier for class, methods and variables. Only inner class can be used as "private". Private members can only be accessed by other members of their own class. | |
protected | is an access modifier used in class, methods and variables. Protected class can be accessed 1)From same class 2)form any class in same package 3)from subclass in same package 4)from a subclass in different package via inheritance/extend 5)Not form any non subclass outside package | |
public | is an access modifier for class,method and variables can be accessed by the member of any class | |
return | is used to finish an execution of method ,I can be followed by a value required by the method definition that is returned to the caller. | int getId( ) { return id; } |
short | 16 bit signed Two's complement integer. This keyword also declared a method that returns a value of short | short length = 4; |
static | in nutshell static is feature which is unique to it's class but not to object to its class 1) static variable : multiple objects of a class use the same instance of a static variable ------------------------------- 2) static method : defined as static. A static method can be accessed without creating its object,just by using class name the method can be accessed. Static method can only access static variables, NOT LOCAL, GLOBAL or NON STATIC variables. STATIC METHOD CAN CALL ONLY STATIC METHODS, not non static method.Non static method can call STATIC METHOD. 3) a class can not be declared as static But a class is said to be static if all the variables and methods are declared with static and have a private constructor. Making the constructor private prevents the class to be instantiated, so the only possibility access is using the class name only. Nested class ( class with in class) are divided into 2 types a) static nested class b) non static nested or inner class | 1)satic variable: public class Counter{
private static int count=0;
private int
nonStaticcount=0;
public void
incrementCounter()
{
count++;
nonStaticcount++;
}
public int
getCount( )
{
return count;
}
public int
getNonStaticcount()
{
return nonStaticcount;
}
public static void
main(String args[ ])
{
Counter countObj1 =
new Counter( );
Counter countObj2 =
new Counter( );
countObj1.incrementCounter( );
countObj1.incrementCounter( );
System.out.println("Static count for Obj1: "+ countObj1.getCount( ));
System.out.println("NonStatic count for Obj1:
"+countObj1.getNonStaticcount());
System.out.println("Static count for Obj2:
"+countObj2.getCount())
System.out.println("NonStatic count for Obj2:
"+countObj2.getNonStaticcount( ))
}
}
Output:
Static count for Obj1: 2
NonStatic count for Obj1: 2
Static count for Obj2: 2
NonStatic count for Obj2: 0
-----------------------------
2) static method
public class Test{
public static void
printMe(){
System.out.println("Hello World");
}
}
public class
MainClass{
public static void
main(String args[]){
Test.printMe()
}
}
OutPut:
Hello World
----------------------------
3) static class
class OuterClass
{
... static class StaticNestedClass
{
... } class InnerClass
{
... } } |
strictfp | Use strict rules for floating-point computations to ensure portability ( platform Independent ) Strictfp is used with variable and class only. When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier. | strictfp class myEmp { // code here } class circleResult { static strictfp double circumference (double dim) { return Math . PI * dim; } |
super | is a keyword to invoke superclass constructor or method | public Teacher (String name, int Empno) { super(name); id = Empno; } public void print() { super.print(); System.out.println(id); } |
switch | a selection statement with association with 'case' and 'default' to construct switch statement which evaluates variables, matches value to specific case and excites block of statements which are adjacent with case. | switch (ch) { case 'R': case 'S: more = false; break; case ' '; break; default: process(ch); break; } Note: If you omit a break, processing continues with the next case. |
synchronized | keyword is used to prevent concurrency and can be use in static and non static method.If multiple methods/thread tries to access same method at same time, only one thread at a time can access synchronize method.Other methods have to WAIT for the execution of the method by one thread.Synchronized keyword provides a lock on the object thus prevent race condition. | public void synchronized method ( ) { } public void synchronized staticMethod( ) { } public void testMethod ( ) { synchronized(this); { //code here } } |
this | 1) is the implicit argument in a method 2) constructor of this class | public Student(String id) { this.id = id; } public Student( ) { this(" "); } |
throw | use to throw exception manually. Mainly used when the program fails to satisfy the conditions which are given, and it warns the application.The exception is thrown mainly subclass of Throwable |
public void
parent( ){
try{
child( );
}
catch(MyCustomException e) { }
}
public void child{
String
iamBound=null;
if(
iamBound
==
null){
throw (new
MyCustomException("Throwing exception using throw keyword");
}
|
throws | If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration. |
public void parent( ){
try{
child( );
}catch(MyCustomException e){ }
}
public void child
throws MyCustomException{
//put some logic
so that the exception occurs.
}
|
transient | marks data that should not be persistent I.e if the some properties of the class need not to be serialize then variables are marked by transient. When the object is deserialized the transient variables retains default values depending on the type of the variables declared so, lost its original value. | class teacher { private transient Data cachedData; ... } |
try | a block of code that traps exceptions | try { try { fred.print(out); } catch (PrinterException ex) { ex.printStackTrace(); } } finally { out.close(); } |
void | a method that returns no value | public void myMethod( ) { // code goes here } |
volatile | ensures that a field is coherently accessed by multiple threads. In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues. | class Student { private volatile int nextId; ... } |
while | see do while | |
No comments:
Post a Comment