Monday, July 30, 2012

public static void main (String[] args)

public : as it is accessible from anywhere for jvm
static: no need to create objects to call method.
void: no returning of value
main: syntax- main method - name to be followed
String[] args - syntax- to be followed

== vs equals in java

public class EqualsTest {
public static void main(String[] args) {

String s1 = "abc";

String s2 = s1;

String s5 = "abc";

String s3 = new String("abc");

String s4 = new String("abc");

System.out.println("== comparison : " + (s2 == s4));

System.out.println("== comparison : " + (s1 == s2));

System.out.println("Using equals method : " + s1.equals(s2));

System.out.println("== comparison : " + s3 == s5);

System.out.println("Using equals method : " + s3.equals(s4));

}

}
 
Output
 
== comparison : false


== comparison : true

Using equals method : true

false

Using equals method : true

Equals comapares the content, == compares the references(memory location), hence when new keyword is used to create string, == shows false.


Friday, March 9, 2012

Exception Rules in Java

It's just opposite in the case of constructors and methods. A overriding method cannot throw broader checked exceptions than the overridden method in the super class. But in case of constructors, subclass constructor can throw broader checked exception but not narrower checked exception of the super class constructor. This behavior is opposite as constructors are not overridden...

Thursday, March 8, 2012

How many ways we can create objects in Java

there are 4 ways
1) using new operator and default constructor
MyObject object = new MyObject();
2) using Class.forname
MyObject object = (MyObject) Class.forName(MyObject).newInstance();
3) using clone
MyObject object = anotherObject.clone();

4) using deserialization
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject();