Tuesday, August 10, 2010

In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc"); Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String’s case?

Button buttonObj = "Submit"; It is because "Submit" is a literal string (slightly different than a String object)
 and buttonObj is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String.
 Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "Submit";
 For example String a = "Submit"; String b = "Submit"; refer to the same object. While String a1 = new String("Submit");
String b1 = new String("Submit"); refer to two different objects.

No comments:

Post a Comment