Java Tips

The Ternary Conditional Operator ?:

I usually forget this: myVal = (a < b; a ? b);
Another usage is like:
boolean a;
a = b > c ? true : false;

How to Iterate a Map

Iterator it = themap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry);

It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.

Enhanced For Loop Since 1.5

This is also called foreach.

for (MyObject myobj : theCollection)
        myobj .do();

String Concatenation

The + operator performs string concatenation if and only if at least one of its operands is of type String; otherwise, it performs addition.
In this case 'a' + 'b' prints an int number not the string ab.
To force this into a String concatenation we can prepend an empty string; use a string buffer; or if you are using release 5+, use the printf facilities.


It stands for Not a Number. The specification says that NaN is not equal to any floating-point value, including itself. Any floating-point operation evaluates to NaN if one or more of its operands are NaN. So in case of Nan, the statement i != i; is correct.


class x {
    static fields;
    public static void main() {}
  • A static field/method exists one per class loader. They are associated with a class rather than with an object.
  • A VM uses classes loaded by one or more class loaders.

This is the way static fields are treated by JVM:

  • JVM inits class
  • Static fields are set to their default values (objects to null, boolean to false, int to 0,…) in order of appearance
  • Static fields are executed if they have eager initialization, etc (in order)

See the section related to the order of execution in a class in the same page.

Variable Initialization

private static final int sum = someMethod();   //eager initialization
private static final int sum;    //lazy initialization

Fields that are declared but not initialized will be set to a reasonable default by the compiler.
The compiler never assigns a default value to an uninitialized local variable. Accessing an uninitialized local variable will result in a compile-time error.


Private constructors are useful in alternate constructor invocation.

public class x {
    public X () {
        this(int i);   //calls a private constructor
    private X (int i) {}   //private constructor

They are also used in singleton pattern

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.

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

A non default constructor always calls the no arg default constructor of the super class implicitly. We can explicitly call non default constructors of the super class using the super keyword.

<init> vs <clinit>: <init> is the (or one of the) constructor(s) for the instance, and non-static field initialization. <clinit> are the static initialization blocks for the class, and static field initialization. So the order of invocation for "new Foo().getname()" is always <clinit>,<init>,getname().

class X {
   static Log log = LogFactory.getLog(); // <clinit>
   private int x = 1;   // <init>
      // <init>
   static {
      // <clinit>


Always watch out for immutables. All wrapper classes such as String, BigDecimal, Integer, Long, Short, Byte, Character, Boolean, Float, Double, … are immutable. They also have some misleading methods.

BigInteger sum = new BigInteger("1");
BigInteger base = BigInteger.ZERO;

add method will not do sum + base and we need to do: base = base.add(sum);


Integer literals beginning with a 0 are interpreted as octal values so watch out for things like: int i = 012;

Get rid of duplicates in a list

Simply dump your list into a set or a LinkedHashSet if you want to preserve the order. In case the elements are objects make sure you have equals and hashcode properly implemented for them.

Split a String

Use split method of strting. Forget about StringTokenizer as it will be deprecated soon.

static String[] parse(String string) {
    return string.split(",\\s*");

Autoboxing and Unboxing

You can’t put an int (or other primitive value) into a collection. Collections can only hold objects, so you have to box primitive values into the appropriate wrapper class. When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is automated in Java 5.

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Test: Integer i = null; int j = i; Value of j?
Answer: Unboxing happens via calling Number.longValue(), Number.intValue() so above throws a NPE.

Hiding, Shadowing, Obscuring

Whatever they are just avoid them! You might not even use them once in a lifetime! Also avoid name re-using.
In case of a method you can not hide a an inherited method (you can override it) but you can do for variables which is not a good practice.
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super. We don't recommend hiding fields as it makes code difficult to read.

public class Base {
    public String ss;
    public void testme(){}
public class Derived extends Base {
    private String ss; // this does not give compile error and hides which is not a good thing
    private void testme(){} // this gives compile error


Final modifier means something completely different on methods and fields. On a method, final means that the method may not be overridden but on a field, final means the field may not be assigned more than once (cannot change).

We can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful when creating an immutable class like the String class.


Method Scope

When calling a method, the compiler searches for the method in the innermost enclosing scope containing a method with the correct name; this may not always be what we want! For more info see JLS.


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.

Package Scope

You can define variables to have private, protected, public or "package private" scopes:

    public class MyClass {
            private int x;     // private scope
            protected int y;   // protected scope
            int z;             // package scope
            public int w;      // public scope

Singleton and Serialization

A singleton class that implements Serializable must have a readResolve method that returns its sole instance. Watch out when your singleton extends or implements a class which has Serializable in its hierarcy.


  • Throw exceptions as early as possible.
  • Catch exceptions as later a possible. Let come come up in the hierarchy and catch when really needed.
  • Reuse Java's exceptions and do not write your exceptions all the time.
  • 3 types of exceptions: checked (FileNotFoundException), error (OIError), runtime (NullPointerException)
  • The finally block always executes when the try block exits. If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
  • In java 7 we have try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement, can be used as a resource.
try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();

| |_VirtualMachineError
| |_RuntimeException


An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.

There are empty interfaces in Java such as Cloneable, Serializable, … These are known as marker (tag) interfaces. They just categorise the derived classes into a category based on their purpose. Marker interfaces are understood by the JVM. For example, all classes that implement the Cloneable interface can be cloned (the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface, if not, you will get a compile error.
You can write marker interfaces yourself as well. Context interface in Apache Chain is a marker interface. It doesn't do anything and just extends Map but defines a category for objects that implement it or extend the ContextBase.


Stupid Comparator

There is a big flaw in this comparator. if i2 is a big integer and i1 is a small negative integer then the result could be a long number and goes beyond integer and the comparator behaves stupidly. Always beware of CLEVER codes your write!!

Comparator<Integer> cmp = new Comparator<Integer>() {
    public int compare(Integer i1, Integer i2) {
        return i2 - i1;

Comparator Based On Two Fields

See the following object. I want to write a comparator based on its two fields.

public class MyObject {
    private Integer speed;
    private Integer sequence;
    //getters and setters

"speed" is the main (outer) field and "sequence" is the second (inner) fields that I want to compare based on them. When two objects have same "speed" then I will compare based on "sequence":

public class PlanSortComparator implements Comparator<MyObject> {
    public int compare(MyObject o1, MyObject o2) {
        Integer speed1 = o1.getSpeed();
        Integer speed2 = o2.getSpeed();
        if (speed1 == null && speed2 == null)
            return new DisplayOrderComparator().compare(o1, o2);
        else if (speed1 == null)
            return -1;
        else if (speed2 == null)
            return 1;
        else if (speed1.intValue() == speed2.intValue())
            return new DisplayOrderComparator().compare(o1, o2);
            return speed1.compareTo(speed2);
    public class DisplayOrderComparator implements Comparator<MyObject> {
        public int compare(MyObject o1, MyObject o2) {
            Integer sequence1 = o1.getSequence();
            Integer sequence2 = o2.getSequence();
            if (sequence1 == null && sequence12 == null)
                return 0;
            else if (sequence1 == null)
                return -1;
            else if (sequence2 == null)
                return 1;
                return sequence1.compareTo(sequence2);

With this code if we do sorting then MyObject1(speed=33,sequence=8) will come before MyObject2(speed=39,sequence=4) and MyObject1(speed=33,sequence=5) will come before MyObject2(speed=33,sequence=9).

new Integer(int) OR Integer.valueOf(int) ?

Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.

Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.

Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.

Order of execution in a class

  1. Static variables and blocks (in the order of appearance) are initialized
  2. Class variables are initialized
  3. Constructor is run

Limit Float points to two decimal points

Limiting the precision points:

DecimalFormat dec = new DecimalFormat(".##");
Always use Double instead of Float!

Using floats

Avoid float and double when exact answer is required. Use BigDecimal, int or long instead. Specially when working with money. Also use BigDecimal(string) not BigDecimal(double) constructor.

Convert Array To List

java.util.List list = Arrays.asList(array);

Send Email Asynchronously

private class SendMailThread extends Thread  {
    private Message message;
    public void run(){
    private void sendMessage(Message message){
        this.message = message;
// and  in client:
SendMailThread mailThread = new SendMailThread();

Create a List with one element

List list = Collections.singletonList(object)

Just notice that this method creates an immutable list so that cannot be changed. Doing list.add() will throw exception.

By Value/Reference

  • Everything in Java is passed by value. Objects, however, are never passed at all; their reference is passed by value.
  • The passed-in object reference (into a method ) references the same object as before. However, the values of the object's fields can be changed in the method.
  • Primitives are passed by value (see example below)
  • Instead of passing an object to a void method and using the modified object, it is better modify the method to return a value and use the return value of the method.
  • Java doesn't let you pass methods into methods. But you can pass an object into a method and then invoke the object's methods.
public class Product {
    public String name;
    public Product(String name){ = name;
    public Product(){}
public class Test {
    public void test(){
        Product p = new Product("ali");
        System.out.println(; //--> change
    public void test2(){
        List<Product> ps = new ArrayList<Product>();
        Product p = new Product("ali");
        System.out.println(ps.get(0).name);// --> change
    public void test4(){
        List<Product> ps = new ArrayList<Product>();
        Product p = new Product("ali");
        System.out.println(ps.get(0).name);// --> change
    public void test3(){
        Long i = 9l;
        System.out.println(i);// --> 9    
    void passListIn(List<Product> ps) {
        for(Product p : ps){
    void passObjectIn(Product p){ = "change";
    void passPrimitiveIn(Long l){
        l = 7l;

Running a java class with VM args

java \ \ \

JMX Client

//for jboss
final InitialContext ic = getInitialContext("server-name", 8391);
final MBeanServerConnection jmx = (MBeanServerConnection) ic.lookup("jmx/invoker/RMIAdaptor");
Map<String, DiagnosticMBean> mbeans = JMXUtils.findMBeans(
                YourMBeanInterface.class, YourMbeanImpl.class,
ObjectName on = new ObjectName("com.test:myservice=what");
Object[] params = {Boolean.TRUE};
String [] signature = {"boolean"};
jmx.invoke(on, "methodName",  params, signature); //methodName gets a boolean only
static InitialContext getInitialContext(String host, int port) throws NamingException {
        Properties properties = new Properties();        
        properties.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");            
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");            
        properties.put(Context.PROVIDER_URL, host + ":" + port);
        return new InitialContext(properties);

Variable Args

Since JDK 5 we can have: "type … variableName" for method args.

    public static void test(String ...strings){
                //strings is an array of String
    //then we can call test("a") and test("a","b")

Memory Dump

List of Java processes: jps -v

java 5:

    java -Xrunhprof:format=b,file=snapshot1.hprof Classname 
    then ctrl-c is supposed to dump the heap

java 6: 

    use jps -v
    jmap -dump:format=b,file=dumpfile.bin 3220

The you can analyze the dump using Eclipse Memory Analyzer.


java Test

Referring to classpath:
javac -classpath ./somejar.jar
javac -classpath .;somejar.jar
java -classpath .;somejar.jar Test

Running a Jar:
java -jar somejar.jar

java -classpath .:./somejar.jar Test

Include current dir in the classpath: .:/home/me/newLibrary.jar.

Nested Classes

Inner class instantiation:

Out out = new Out();
Out.Inner inner = Inner();

Types of nested classes:

  • static nested class (not inner)
  • inner [non-static] class
    • local class
    • anonymous class

Static nested classes do not have access to other members of the enclosing class.
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Anonymous Classes enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name
Anonymous classes are expressions.

public class Test {
     interface HelloWorld {
        public void greet();
    private void test(){
            //anonymous class
        HelloWorld frenchGreeting = new HelloWorld() {
            public void greet() {
         frenchGreeting.greet();    //using 


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.

Parameter vs Argument

Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

test(int param)

Equals & Hashcode

The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. This is good for primitive types but not objects.
The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.
By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.


Character is a wrapper object (immutable) for primitive type char.
Strings are a sequence of characters.


StringBuilder and StringBuffer are similar to String except they can be modified and are not mutable. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.
They have more method for string modification.
Strings should always be used unless these provide an advantage in terms of simpler code or better performance.
StringBuffer is exactly the same as the StringBuilder class, except that it is thread-safe by virtue of having its methods synchronized.

Package and Import

Companies use their reversed Internet domain name to begin their package names, for example, com.telstra
Static import is for static methods and constants: import static java.Math.PI or import static java.Math.cos



In Windows:   C:\> set CLASSPATH
In Unix:      % echo $CLASSPATH


In Windows:   C:\> set CLASSPATH=
In Unix:      % unset CLASSPATH; export CLASSPATH


In Windows:   C:\> set CLASSPATH=C:\users\george\java\classes
In Unix:      % CLASSPATH=/home/george/java/classes; export CLASSPATH


  • A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time and an output stream to write data to a destination.
  • Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
  • Stream objects that implement formatting are instances of either PrintWriter, a character stream class, or PrintStream, a byte stream class.
  • A more advanced alternative to the Standard Streams (System.out, is the Console class.
  • Streams can be categoriesed in byte, character, buffered, data, object streams.

Byte Stream

FileInputStream and FileOutputStream (file io byte stream)

Character Stream

  • All character stream classes are descended from Reader and Writer.
  • For character files we can user FileReader and FileWriter
  • Character streams are often "wrappers" for byte streams

Bufferred Stream

  • All above classes are unbuffered. Usually it is best to use the buffered versions.
  • There are four buffered stream classes used to wrap unbuffered streams:
  • BufferedInputStream and BufferedOutputStream create buffered byte streams
  • BufferedReader and BufferedWriter create buffered character streams

BufferedReader inputStream = new BufferedReader(new FileReader("xanadu.txt"));

Data Stream

  • Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values.
  • All data streams implement either the DataInput interface or the DataOutput interface. Famous interfaces are : DataInputStream and DataOutputStream.

DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

Object Stream

  • Object streams support I/O of objects. The object stream classes are ObjectInputStream and ObjectOutputStream.
  • An object stream can contain a mixture of primitive and object values.


  • All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.


Every compiler warning belongs to a category. Java lists two categories: "deprecation" and "unchecked." The "unchecked" warning can occur when interfacing with legacy code written before the advent of generics. To suppress more than one category of warnings, use the following syntax:

@SuppressWarnings({"unchecked", "deprecation"})


useful file classes (from java 7): FileSystem, FileSystems, Path, Paths, Files, DiskUSage, FileStore

fileArray = Files.readAllBytes(file)
fileArray = Files.readAllLines()
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {}

using Path input = file.toPath() we can bridge java 7 features with older codes as most java 7 methods use Path instead of File.

Concurrency and Threads

See concurrency_threads


System.out.format("%d property value for %s is %s %n ", counter, name, strValue ,"\n" );

Security Manager

A security manager is an object that defines a security policy for an application. This policy specifies actions that are unsafe or sensitive. Any actions not allowed by the security policy cause a SecurityException to be thrown. An application can also query its security manager to discover which actions are allowed.

Typically, a web applet runs with a security manager provided by the browser or Java Web Start plugin. Other kinds of applications normally run without a security manager, unless the application itself defines one. If no security manager is present, the application has no security policy and acts without restrictions.

Jar Files

JAR files are packaged with the ZIP file format.

create jar cf jar-file input-files/dirs
view jar tf jar-file ( t stands for table of content )
extract jar xf jar-file
update jar uf jar-file input-files (adds/updates the input files into the jar file)
run java -jar jar-file (in order for this to work we must have Main-Class: classname set in the manifest as the entry point)

Sign a Jar

  • The Java platform enables signing and verification by using public and private keys.
  • Public and private keys alone, however, aren't enough to truly verify a signature. Even if you've verified that a signed file contains a matching key pair, you still need some way to confirm that the public key actually comes from the signer that it purports to come from. This is where we need a certificate.
  • A certificate is a digitally signed statement from a recognized certification authority that indicates who owns a particular public key.
  • When you sign a JAR file your public key is placed inside the archive along with an associated certificate so that it's easily available for use by anyone wanting to verify your signature.
  • To sign a JAR file, you must first have a private key. Private keys and their associated public-key certificates are stored in password-protected databases (file) called keystores. A keystore can hold the keys of many potential signers. Each key in the keystore can be identified by an alias which is typically the name of the signer who owns the key.
sign jarsigner jar-file alias
verify jarsigner -verify jar-file


When calling super in a consctructor it should always be the first statement. We cannot have if (…) super();


Javabeans are very similar to POJOs and is basically a convention. They are different from enterprise javabeans (EJBs). They can be use to represent a real world data. You can use them everywhere to store, transfer and access data.

Conventions of creating a javabean:

  • The class must have a public default constructor (with no-arguments). 
  • The class properties are private but have public getters and setters
  • The class should be serializable. 
  • It can have other public methods
  • It can have events (in case it is used in the context of swing applications)

Double Buffering

The traditional notion of double-buffering in Java applications is fairly straightforward: create an offscreen image, draw to that image using the image's graphics object, then, in one step, call drawImage using the target window's graphics object and the offscreen image. Swing uses this technique in many of its components, usually enabled by default, using the setDoubleBuffered method.

Primitive Datatypes

byte 8bit < short 16bit < int 32bit < long 64bit

byte has a minimum value of -128 and a maximum value of 127 (inclusive).
short has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
int has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)
long has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)

char: The char data type is a single 16-bit Unicode character.

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code: long creditCardNumber = 1234_5678_9012_3456L;


You can create a Locale with any combination of valid language and country codes, but that doesn't mean that you can use it. Remember, a Locale object is only an identifier. You pass the Locale object to other objects, which then do the real work. These other objects, which we call locale-sensitive, do not know how to deal with all possible Locale definitions.
At the moment, farsi/iran is not a supported locale in java.

The Collator class performs locale-sensitive String comparison. You use this class to build, searching and sorting routines for natural language text.

        Locale list[] = DateFormat.getAvailableLocales();
        for (Locale aLocale : list) System.out.println(aLocale.getDisplayName());

++ Operator

Both ++a and a++ increment "a" but ++a evaluates to the incremented value, whereas a++ evaluates to the original value.

        int a = 6;
        int b = a++;
        int c = ++a;


Assertions should not be used in a production code. They are turned off by default. If they are turned on using "java -ea" then the following expression throws AssertionError:

assert toString(ACE) == "Ace";


Unicode is a 16-bit character.
A Java String is internally always encoded in UTF-16.
Unicodes are represented as hex in java. They range from 0x0000 to 0xFFFF (2^16 = 65,536) which is not enough to represent all the world characters so it was extended to 0x10FFFF.
The characters with values that are outside of the 16-bit range, and within the range from 0x10000 to 0x10FFFF, are called supplementary characters and are defined as a PAIR of char values.
To express a character in Unicode, the hexadecimal value is prefixed with the string U+. The code point value for the Latin character A is U+0041.
Unicode representation in java uses \u escape character for example: Character letter = new Character('\u00F6');


When a ref to an object exist but the object itself is not used anymore. In these cases best is to set that object to null.


Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License