I am bit confused when to use new with String and when to not use as String is a class to make an object we had to write String s = new Srtring("Hello"); But h ow does the following code works where we are not making an object public class MyClass { public static void main(String args[]) { String s = "HelloWorld"; if ((s != null) && (s.length() > 6)) System.out.println("The value of s is " + s ); } }
Regards, aakash
Arun Boraiah
Ranch Hand
Joined: Nov 28, 2001
Posts: 233
posted
0
Class like String are inbuilt JDK class with behaves little different than other class. Example like the one you have mentioned. This is feature given to increases programmer flexibility (in the form of giving different option to create string object). Internally they are infact-allocating memory as other class gets but diffrence here is that if any variable referring to same string value JVM points to same memory location. Where as if an instance is created even same string content will be referring to different memory location.
Sharing is learning
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
String s = new String("Hello");
This actually involves two String objects. The "Hello" is one String, and new String() creates a second string with identical contents. There is really no purpose to writing code that does this sort of thing, unless it's for teaching purposes or to test or discuss things like garbage collection or the string intern pool.