File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String class

 
aakash bhatt
Ranch Hand
Posts: 182
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 233
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic