Java Cheatsheet Fundamental

java

What does JNDI abbreviate for?
What does RMI abbreviate for?
What does RMI-IIOP abbreviate for?
What does JAX-RS abbreviate for?
What is the purpose of JAX-RS?
What does JMX abbreviate for?
What does JMS abbreviate for?
What does EJB abbreviate for?
What does JINI abbreviate for?
What is the purpose of JINI?
What does JSR abbreviate for?
What does Java SE abbreviate for?
What does Java EE abbreviate for?
What does Java ME abbreviate for?
What does Java FX abbreviate for?
What is Java SE?
What is Java EE?
What is Java ME?
What is Java FX?
How can we declare a constant?
What is the purpose of System.gc() method?
What is the purpose of the Runtime.gc() method?
What is the purpose of the System.runFinalization() method?
JNDI - Java Naming and Directory Interface
RMI (Remote Method Invocation)
RMI-IIOP (RMI over Internet Inter-ORB Protocol)
JAX-RS: standard for building RESTful web services
JMX: Java Management Extensions
JMS: Java Message Service
EJB: Enterprise Java Beans
JINI: (Apache River) a network architecture for the construction of distributed systems 
  in the form of modular co-operating services.

JSR: Java Specification Request
Java SE: Java Standard Edition
Java EE: Java Enterprise Edition
Java ME: Java Micro Edition (mobile or embedded devices)
Java FX: Use for creating rich internet applications using a lightweight user-interface API.

// declaring a constant
static final double PI = 3.141592653589793;

System.gc (); // or Runtime.gc
System.runFinalization ();

public class Bicycle {
    // this class has three fields
    public int cadence;
    public int gear;
    public int speed;

    // this class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    // public methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
}

// Extending / inheriting and using super keyword to 
// invoke a constructor from the parent class.
// If a constructor invokes another constructor, it must be the first statement
public class MountainBike extends Bicycle {
    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }        
}

// Implementing an interface
class MyClass extends MySuperClass implements YourInterface {
}

// Defining a method
public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) {
}

// Method that accepts an array of objects
public Polygon polygonFrom(Point[] corners) {
    // method body goes here
}

// Method that takes a variable number of arguments
public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)
                     * (corners[1].x - corners[0].x) 
                     + (corners[1].y - corners[0].y)
                     * (corners[1].y - corners[0].y);
    lengthOfSide1 = Math.sqrt(squareOfSide1);

    // more method body code follows that creates and returns a 
    // polygon connecting the Points
}

public int average( int ... numbers) {
  int total = 0;
  for (int x: numbers) {
    total += x;
  }
  return total / numbers.length;
}

// Enhanced for loop
public int findSumOfArray(int[] array) {
  int sum = 0;
  for (int number : array) {
    sum = sum + number;
  }
  return sum;
}

// Sample properties file
user=Crunchify
company1=Google
company2=eBay
company3=Yahoo

// Writing to a properties file
OutputStream output = new FileOutputStream("config.properties");
Properties prop = new Properties();
prop.setProperty("database", "localhost");
prop.store(output, null);  // save properties to project root folder

// Reading a properties file
props = new Properties();
InputStream in = FileInputStream(configFile);
props.load(in);
...
String key = "...";
String val = props.getProperty(key.trim());
if ((val == null)) {
  throw new Exception("Invalid Key: " + key + " (not found in config file)");
}

// Skeleton program
class HelloWorld {
    public static void main(String [] args) {
        System.out.println("...");
    }
}

// Without the public keyword, this class is only visible
// to other classes within the same package
class ClassName {
}

// Creating an instance
ClassName c = new ClassName();

// Invoking the parent class constructor
super(parameters)

// super() must be the first statement executed inside a sub-class constructor.

"C:\Program Files\Java\jdk1.7.0_04\bin\javac"  SVNTool.java 
    -cp ".;C:\parsers\commons-lang-2.4.jar;
             C:\parsers\svnkit-1.7.4-v1\lib\svnkit-cli-1.7.4-v1.jar;
             C:\parsers\svnkit-1.7.4-v1\lib\svnkit-1.7.4-v1.jar"
javac SVNTool.java -classpath ".;C:\parsers\commons\commons-lang-2.4.jar"
java -cp ".;c:\parsers\log4j\log4j-1.2.14.jar" ExperimentLog4J

java -cp target/MavenTestApp-1.0-SNAPSHOT.jar org.koushik.javabrains.App

// create an instance of a class given the name of the class as a string using Class.forName
Class c = null;
c = Class.forName(strServName);
ServletInterface pdhObj = (ServletInterface) c.newInstance();
pdhObj.processData(req, res, servctxt);

// Define an interface
interface Bicycle {
    //  wheel revolutions per minute
    void changeCadence(int newValue);
}

// Interface does not provide concrete implementation for any of its methods.

// Implement an interface
// Compiler will fail if we do not provide concrete implementation for the
// methods listed in the interface.
class ACMEBicycle implements Bicycle {
    void changeCadence(int newValue) {
        ...
    }
}

// Implementing an interface allows a class to become more formal about the behavior it promises to provide. 
// Interfaces form a contract between the class and the outside world, and this contract is enforced at build 
// time by the compiler. If your class claims to implement an interface, all methods defined by that interface 
// must appear in its source code before the class will successfully compile.

// Class literal
// formed by taking a type name and appending ".class"
String.class

// The instanceof operator compares an object to a specified type. You can use it to test if an object is an 
// instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {};
Parent obj1 = new Parent();
Parent obj2 = new Child();
obj1 instanceof Parent
obj1 instanceof Child
obj1 instanceof MyInterface

// When using the instanceof operator, keep in mind that null is not an instance of anything

// Constructor declarations look like method declarations—except that they use the name of the 
// class and have no return type.  You don't have to provide any constructors for your class, 
// but you must be careful when doing this. The compiler automatically provides a no-argument, 
// default constructor for any class without constructors. This default constructor will call the 
// no-argument constructor of the superclass. In this situation, the compiler will complain if 
// the superclass doesn't have a no-argument constructor so you must verify that it does. If 
// your class has no explicit superclass, then it has an implicit superclass of Object, which 
// does have a no-argument constructor.
// Constructors must have the same name as the class, and have no return type, not even void.

// From within a constructor, you can also use the this keyword to call another constructor in the same class.
public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

// The invocation of another constructor must be the first line in the constructor

// A class may be declared with the modifier public, in which case that class is visible to 
// all classes everywhere. If a class has no modifier (the default, also known as package-private), and
// it is visible only within its own package

// At the member level, the public modifier indicates that the member variable is accessible everywhere.
// The private modifier specifies that the member can only be accessed in its own class.
// If we do not specify an access modifier for a member variable, that member variable is 
// package-private, which means that it is visible to other classes within the same package, but it is not 
// visible to classes that are located in other packages.  The protected modifier specifies that the member 
// can only be accessed within its own package (as with package-private) and, in addition, by a subclass 
// of its class in another package.

// declare and initialize multiple variables of the same type on the same line
type identifier [=value][,identifier[=value]...];
int d=3, e, f=5;

// The finalize method is invoked before an object is destroyed.  If we need to run some code when an 
// object is destroyed, then we can implement / override this finalize method, but keep in mind that this 
// finalize method is not invoked until our object is destroyed or garbage-collected.  If our object never 
// go out of scope, it is never garbage collected, and therefore this finalize method is never invoked.

// Variables can be declared as final.  Doing so prevent its content from being modified.  This means 
// we must initialize the variable when we declare it
final int x = 1;

break: equivalent of last
continue: equivalent of next

switch(age) {
  case 1:
    ...
    break;
  case 2:
    ...
    break;
  default:
    ...
    break
}

// The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right 
// shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand 
// operand, and the number of positions to shift by the right-hand operand. The unsigned 
// right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost 
// position after ">>" depends on sign extension.

// Shift the bits inside the value of variableName n times (multiply by 2 each time)
// Fill the right with 0.
variableName << n  

// Shift the bits inside the value of variableName n times (divide by 2 each time)
// The leftmost bits in the result are set to the same value as the leftmost bit in the original number. 
// This is so that negative numbers remain negative.

// The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any 
// of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte 
// contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would 
// change its pattern to "11111111".

// The bitwise & operator performs a bitwise AND operation.  The bitwise ^ operator performs a 
// bitwise exclusive OR operation.  The bitwise | operator performs a bitwise inclusive OR operation.

int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // print "2"

// Using the ternary (?) operator
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;

// Overriding: When a sub-class define a method with the same name and signature as a 
// method in the parent class.  When we override a method, the new method must have the 
// same signature, return type, and scope.

// Overloading: When a class has multiple methods with the same name, but different signature.

// An abstract class is a class that is declared with the keyword 'abstract'.  We cannot create 
// an instance of this class, but we can use it for inheritance and polymorphism.
// An abstract method is a method that must be overridden.  To declare a method as abstract 
// (notice that we do not define the body for the method):
public abstract void eat();

// To make all instances of a class share the same variable, declare the variable with the static keyword

// Make random number
import java.util.Random;
Random dice = new Random();
int number = dice.nextInt(6); // generate a random number between 0 and 5
int number = 1 + dice.nextInt(6); // generate a random number between 1 and 6

// Determine the JDK version that was used to compile a class file
javap -verbose MyClass
javap -verbose MyClass | find "version" (Windows)
javap -verbose MyClass | grep version (Linux)

// The javap command disassembles one or more class files. Its output depends on the options used. 
// If no options are used, javap prints out the package, protected, and public fields and methods of the 
// classes passed to it. javap prints its output to stdout.

// Accessing environment variable using System.getenv
String username = System.getenv("USERNAME");

// Determine appropriate line terminator
String lineSeparator = System.getProperty("line.separator");

// We do not have to pre-declare a variable before it is used.  
// A variable can be declare on the same line when it is used.

// An interface can not contain a concrete implementation of a method.  
// It can only contain the signature of the methods.
// We can put constants inside an interface.  However we do not have to use 'public static final'.
interface SampleInterface {
  int SAMPLE_CONSTANT = 5;
  public void methodName();
  public void methodName();
}

// The final keyword when applied to a method means that a subclass cannot override that method.  
// When the final keyword is applied to a class, it means that we cannot extend that class.  When 
// applied to a data member, it means that we cannot change the value of that member after it is initialized.

// We can access the static variable via ClassName.variableName or instance.variableName

// We cannot declare a top-level class with the private access modifier.  However, the access 
// modifier private can be applied to inner class.

// Static initialization blocks are used to initialize static variables when it involve some logic.
// We can have as many static initialization blocks can we have in each class as we want.  
// Static initialization blocks are executed in the order that they are defined in the class.
// Static initialization blocks appear inside the class body but outside of any methods.
/  Example of static initialization block:
static { ... }

// Instead of using static initialization blocks, we can also write private static method.  The advantage of 
// private static methods is that they can be reused later if you need to reinitialize the class variable.

// Normal initialization blocks appear inside the class body, but outside any methods, and without the
// static keyword.  Example of normal initialization block:
{ ... }

// The compiler copies these normal initialization blocks into the body of each constructor.
// Using normal initialization block is a great way for us to share block of code among constructors.

// If a primitive type or a string is defined as a constant and the value is known at compile time, 
// the compiler replaces the constant name everywhere in the code with its value. This is called 
// a compile-time constant. If the value of the constant in the outside world changes (for example, 
// if it is legislated that pi actually should be 3.975), you will need to recompile any classes 
// that use this constant to get the current value. 

// To prevent a sub-class from overriding a method, declare it with the final keyword.
// A final method cannot be overridden in a subclass.

// Static methods only have access to static (class) variables.
// Static methods do not have access to instance variables.

// We should we avoid using the public access modifier except for constant.  This is for better data 
// hiding, so that we can avoid accidental changes.  Public fields tend to link you to a particular 
// implementation and limit your flexibility in changing your code.  Constants, on the other hand, 
// are constants.  We should not be changing them ever, so it is ok for them to be public, and beside, 
// other code cannot change them anyway, so there is no risk involve.  For constants, having direct 
// public access make it easier to use it rather than having to implement a method to retrieve 
// the constant.

// We can use interface names as return types. In this case, the object returned must implement 
// the specified interface.

// From within a constructor, you can also use the this keyword to call another constructor in the 
// same class. Doing so is called an explicit constructor invocation.  This must be the first statement
// inside the constructor.

// Covariant return type:  This is related to polymorphism.  Assume that we have a class named 
// Number, and another class ImaginaryNumber is a sub-class of Number.  If we have a function 
// that is declared to return an instance of the Number class.  This function can also return an 
// instance of the ImaginaryNumber.  The same is not true the other way around.  A function that 
// was declared to return an instance of ImaginaryNumber, cannot return an instance of Number.
// Covariant return type is allowed to vary in the same direction as the subclass.

// Reference data type parameters, such as objects, are also passed into methods by value. 
// This means that when the method returns, the passed-in reference still references the same 
// object as before. However, the values of the object's fields can be changed in the method, 
// if they have the proper access level.

// A class cannot inherit from multiple different classes.
// A class can implement multiple interfaces.
class MyClass extends MySuperClass implements InterfaceA, InterfaceB, InterfaceC {
}

// We can have methods with the same name but the complete method signature should be different.  
// However, we cannot declare more than one method with the same name and the same number 
// and type of arguments, because the compiler cannot tell them apart.  The compiler does not 
// consider return type when differentiating methods, so you cannot declare two methods with 
// the same signature even if they have a different return type.

// Overloaded methods should be used with careful consideration, as they can make code much less 
// readable.

// Constructor declarations look like method declarations—except that they use the name of the class 
// and have no return type.
public Bicycle(int startCadence, int startSpeed, int startGear) {
   ...
}

// People say that Java is not a pure object oriented language because Java has primitives 
// such as int that are not objects.

// Java is popular because it is platform-independent.  After you compile Java, you can take the compiled 
// file and deploy it anywhere without having to recompile from source.  With C or C++, we have to recompile 
// from source.  Java manage memory better than C++ through a process called Garbage Collection.
// C++ has pointers.  Java has no concept called pointers.  C++ support multiple inheritance.  Java does 
// not support multiple inheritance.  Java does not allow structural programming, and C++ does.  Java
// also have better support for concurrent programming.

// 3 different kind of class loader:
System class loader: load all classes in the CLASSPATH
Extension class loader: load all classes from the extension directories (jre, ext, lib, etc)
Bootstrap class loader: load all the Java core files

// Java starts with the Bootstrap class loader -> Extension class loader -> System class loader.

// When Java compiler cannot resolve a class, it displays "Cannot resolve ... to a type."

// The transient keyword in Java is used to indicate that a field should not be serialized.  For example, if 
// the value of a field can be derived from other fields, it should not be serialized (to conserve disk space).  
// At the time of deserialization, the readObject method is called to perform any operations necessary to 
// restore the state of the object back to the state at which the serialization occurred. 

Class c = "foo".getClass();
"foo".getClass() == String.class

System.console().getClass() == java.io.Console

// Since arrays are Objects, it is also possible to invoke getClass() on an instance of an array. 
// The returned Class corresponds to an array with component type byte.
byte[] bytes = new byte[1024];
Class c = bytes.getClass();

// If the type is available but there is no instance then it is possible to obtain a Class by appending 
// ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.
Class c = java.io.PrintStream.class;

// If the fully-qualified name of a class is available, it is possible to get the corresponding Class using 
// the static method Class.forName().
Class c = Class.forName("com.duke.MyLocaleServiceProvider");

// The variable cDoubleArray will contain the Class corresponding to an array of primitive type double 
// (i.e. the same as double[].class). The cStringArray variable will contain the Class corresponding to 
// a two-dimensional array of String (i.e. identical to String[][].class).
Class cDoubleArray = Class.forName("[D");
Class cStringArray = Class.forName("[[Ljava.lang.String;");

// The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type; 
// however there is another way to acquire the Class. Each of the primitive types and void has a wrapper 
// class in java.lang that is used for boxing of primitive types to reference types. Each wrapper class 
// contains a field named TYPE which is equal to the Class for the primitive type being wrapped.
Class c = Double.TYPE;

// There is a class java.lang.Double which is used to wrap the primitive type double whenever an Object 
// is required. The value of Double.TYPE is identical to that of double.class.

// Void.TYPE is identical to void.class.
Class c = Void.TYPE;

Class c = javax.swing.JButton.class.getSuperclass();

// Get all the public classes, interfaces, and enums that are members of the class including inherited members.
Class<?>[] c = Character.class.getClasses();

// Get all of the classes interfaces, and enums that are explicitly declared in this class. 
Class<?>[] c = Character.class.getDeclaredClasses();

// Returns the immediately enclosing class of the class. 
// The enclosing class of the enum Thread.State is Thread. 
Class c = Thread.State.class().getEnclosingClass();

// Exception handling
try {
  ...
} catch (Exception e) {
}

// Getting the stack trace of an exception as a string:
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String exceptionStack = sw.toString();

// If we are using import org.apache.commons.lang.exception.ExceptionUtils:
import import org.apache.commons.lang.exception.ExceptionUtils;
String stackTrace = ExceptionUtils.getStackTrace(e);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License