Sunday, August 17, 2014

Java Keyword Cheat Sheet - Meaning and Usage

Knowing keywords of a programming language is very important to understand its features, and Java has rich set of keyword, going along with rich set of functionalities. The first keyword, I learn while writing Java program was public, static and void, not surprisingly they are picked from main method. Our instructor explained meaning of each keyword, saying that its, always remember why main is public, static and void main Java. From then, I have learned and used almost every keywords in Java language, except some of the reserved one e.g. goto. Some lesser known and confusing keywords includes strictfp, transient and volatile. You can actually divide all keyword in Java on different categories, depending upon their meaning and context on which they are used. For example, private, protected and public keyword are collectively known as access modifiers and part of Java's wonderful encapsulation and data hiding feature. byte, short, char, int, long, float and double are also keyword but they are collectively known as primitive types in Java and represent numeric values both integral and floating points. synchronized and volatile are used in multi-threading, transient is used in serialization process, while static and final are modifiers, which makes a variable, class or a method special. final, is particularly important because it can seriously limit your ability to extend a class, its used to denote completeness. So if you want to make sure that no one overrides a particular method of a class, you make it final. A final variable is like constants in Java, they can not be reinitialized. They are often initialized at the same time they are created, except blank final variables, which are actually initialized at constructors. There are few more keywords to represent a code unit, known as class and interface. A class can have both state and behavior, where state is provided by member variables, while behavior is givn by methods. Similarly you have abstract as keyword. Here is the list of Java keyword with their meaning and examples, sorted in alphabetical order for quick reference.


Java Keyword CheatSheet and Examples
Here is the list of keywords in Java, with simple explanations and examples. If you don't know any of these keyword and want to learn it in detail, you can always checkout my blog for relevant articles.

abstract
It can be applied to method or class, but you can not make a variable abstract. Here is an example of abstract class in Java
public abstract class Compressor {
public abstract void compress(Scheme scheme);
private void save(String filename) {
// save compressed file
}
}


assert
Used for validation during development. If assertions enabled, by default they are disabled, it throws an error if condition not fulfilled.
For example assert argument != null; Note: Run with -ea or -enableassertion to enable assertions in JVM.

boolean
the Boolean type with values true and false

boolean more = false;

if(more){
    System.out.println("Wait there is some more work to do");
}



break
breaks out of a switch or loop

while ((ch = in.next()) != -1) { if (ch == '\n') break; process(ch); } Note: Also see switch


byte
The 8-bit integer type
byte b = -1; // Not the same as 0xFF Note: Be careful with bytes < 0

case a case of a switch see switch
catch the clause of a try block catching an exception see try

char the Unicode character type char input = 'Q';

class defines a class type

class Person {
private String name;
public Person(String aName) {
   name = aName;

public void print() {
 System.out.println(name);
}

}

const not used

continue continues at the end of a loop
while ((ch = in.next()) != -1) {
 if (ch == ' ') {
continue;
}
 process(ch);
 }

default the default clause of a switch see switch

do the top of a do/while loop do { ch = in.next(); } while (ch == ' ');

double the double-precision floating-number type double oneHalf = 0.5;

else the else clause of an if statement see if

enum an enumerated type enum Mood { SAD, HAPPY };

extends defines the parent class of a class
class Student extends Person {
private int id;
public Student(String name, int anId) {
 ...
}

 public void print() { ... }

 }

final a constant, or a class or method that cannot be overridden public static final int DEFAULT_ID = 0;

finally the part of a try block that is always executed see try
float the single-precision floating-point type float oneHalf = 0.5F;

for a loop type
for (int i = 10; i >= 0; i--) {
System.out.println(i);
}

 for (String s : line.split("\\s+")) {
System.out.println(s);
}
Note: In the "generalized" for loop, the expression after the : must be an array or an Iterable

goto not used

if a conditional statement if (input == 'Q') System.exit(0); else more = true;

implements defines the interface(s) that a class implements
class Student implements Printable { ... }

import imports a package
import java.util.ArrayList; import com.dzone.refcardz.*;


instanceof tests if an object is an instance of a class
if (fred instanceof Student) {
value = ((Student) fred).getId();
}
Note: null instanceof T is always false


int the 32-bit integer type int value = 0;


interface an abstract type with methods that a class can implement interface Printable { void print(); }


long the 64-bit long integer type long worldPopulation = 6710044745L;


native a method implemented by the host system


new allocates a new object or array Person fred = new Person("Fred");


null a null reference Person optional = null;


package a package of classes package com.dzone.refcardz;


private a feature that is accessible only by methods of this class see class

protected a feature that is accessible only by methods of this class, its children, and other classes in the same package class Student { protected int id; ... }

public a feature that is accessible by methods of all classes see class

return returns from a method int getId() { return id; }


short the 16-bit integer type short skirtLength = 24;


static a feature that is unique to its class, not to objects of its class
public class WriteUtil {
public  static void write(Writable[] ws, String filename);

public static final String DEFAULT_EXT = ".dat";

}
strictfp Use strict rules for floating-point computations
super invoke a superclass constructor or method public Student(String name, int anId) {
super(name); id = anId; } public void print() { super.print(); System.out.println(id); }

switch a selection statement switch (ch) { case 'Q': case 'q': more = false; break; case ' ';

break; default: process(ch); break; } Note: If you omit a break, processing continues with the next case.

synchronized a method or code block that is atomic to a thread
public synchronized void addGrade(String gr) { grades.add(gr); }

this the implicit argument of a method, or a constructor of this class public Student(String id) {this.id = id;} public Student() { this(""); }

throw throws an exception if (param == null) throw new IllegalArgumentException();

throws the exceptions that a method can throw public void print() throws PrinterException, IOException

transient marks data that should not be persistent class Student { 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 denotes a method that returns no value
public void print() { ... }

volatile
ensures that a field is coherently accessed by multiple threads
class Student {
private volatile int nextId;
}

while
a loop
while (in.hasNext()){
 process(in.next());
}

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.