File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String class" Watch "String class" New topic
Author

String class

aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
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
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: 18671
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'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String class