Friday, August 27, 2010

Executing Java program without main() function

The title of post seems strange but it is fact. You can develop a Java program without main() function.
Try to execute following program.

class MainMethodNot
{
    static
    {
        System.out.println("This java program have run without the run method");
        System.exit(0);
        
    }
}

The reason that this program executes because static block is executed as soon as the class is loaded. However JVM throws an exception because it doesn't find main() method which can be avoided by using System.exit() function.

Immutable strings in Java

Strings are said to be immutable in Java.Immutability refers to ability toprevent change in value.
It means whenever you change the value of String, you create a new object and make that variable refer to new object.Appending a string is also a same kind of operation internally.

Each time you use "+" operator or ( String.concat() ) , a new string is created, old data is copied and new data is appended. Old string will be garbage collected.

When to use "+":

1). Multiline Strings

  
String text=
    "line a\n"+
    "line l\n"+
    "line b";
 
2) Short messages
System.out.println("x:"+x+" y:"+y); 


When you have multiple string blocks to concat use StringBuilder or 
StringBuffer( if multithreading is used ) class.