Technical Interview

Home
Added Recently
Data Structures
Puzzles
Google & Microsoft
C/C++ Questions
Java Interview Questions
Quantitative Problems
Algorithms
Featured Articles
Amazon Interview Question
Compaq Interview Question
Technical Interview
Interview Process
Introduction Questions
Object Oriented
Google Pages
Fundamental Questions
Resume Tips
Links
Contact Us
Submit Question/Answer

Question:

In Java, You can create a String object as below :
String str = "abc"; & String str = new String ("abc");
Why can’t a button object be created as: Button bt = "abc”.  Why is it compulsory to create a
button object as:
Button bt = new Button ("abc")








Answer: String is not just another class in Java.  There are a lot of special cases in String class.  If you
notice carefully, String is an Immutable class where as that's not true for Button or most of the other
classes.  Java compiler as well as '+' and '+=' operators convert quoted characters in to String.  I
believe Java designers wanted to treat Strings as close to primitive types as possible and hence some
of the differences.
Important to not that you are NOT calling a java.lang.String constructor when you type String s =
"abc"; for example:
String x = "abc";
String y = "abc";

refer to the same object.
While

String x1 = new String ("abc");
String x2 = new String ("abc");

refer to two different objects.