hi ,
I am new to java.Can anyone what is the different between the following code for the java String Declaration.

import java.io.*;
import java.util.*;

class Sample1
{
	public static void main(String args[])throws IOException
		{
			String str="First String";
			String Str1=new String("Second String");
			System.out.println("The variable is "+str);
			System.out.println("The variable is "+Str1);
		}
}

Thank you,

With Regards,
Prem

Literal Strings are "interned" and exist only once regardless of how many times they are used in a program. new String(...) creates a String that is not interned and is completely independent to anything else (and doing it with a literal string in the constructor means that two string get constructed, the interned literal string and the object created by the call to new).

commented: Good knoledge +6

They are the same. The second version is the universal way of creating a new instance of any class, The first version is a special case for Strings, just for convenience.
The same thing applies to creating an array froma literal, as in
int[] arr = {1,2,3};

Literal Strings are "interned" and exist only once regardless of how many times they are used in a program. new String(...) creates a String that is not interned and is completely independent to anything else (and doing it with a literal string in the constructor means that two string get constructed, the interned literal string and the object created by the call to new).

I may be wrong... but I believe that the optimisation of string storage by only storing a value once is a deep optimisation that applies to all strings, regardless of how they are created. There's an old chestnut that goes like this:

String a = "hello fred";
String b = "hello";
a = null;

will the String object "hello fred" be garbage collected?
Answer: no, because b will have been optimised to point to the appropriate chars in "hello fred", thus keepinga reference to it active.

With interned Strings, yes, of course, but that "new" call creates a new String with its own char array. Now, if both statements used literal strings where one had a 100% match in the other (which they currently don't) then only two objects would be created, one literal interned string and one from the "new" call. As it is, since both Strings are different and there is no 100% overlap, three Strings are created, two interned Strings and one on the heap.

Thanks for clarifying that masijade. :-) J.

Literal Strings are "interned" and exist only once regardless of how many times they are used in a program. new String(...) creates a String that is not interned and is completely independent to anything else (and doing it with a literal string in the constructor means that two string get constructed, the interned literal string and the object created by the call to new).

So, we can pass any string values by using the new String..Here i mentioned the below coding.

class Sample1
      {
        public static void main(String args[])throws IOException
      {
        String str="First String";
        String Str1=new String(args[0]);
        System.out.println("The variable is "+str);
        System.out.println("The variable is "+Str1);

      }
   }

Thank you,

args[0] is already a String, there is no reason to wrap it in a new String call (the same with the literal string in the earlier code). Actually, there is, pretty much, no good reason to use "new String(string)". If you don't want to refer to the String using args[0], but rather with str1 then do "String str1 = args[0];"

What is it that you don't understand here? What is it that you are trying to figure out? I'm not at all sure what it is you're asking here.

args[0] is already a String, there is no reason to wrap it in a new String call (the same with the literal string in the earlier code). Actually, there is, pretty much, no good reason to use "new String(string)". If you don't want to refer to the String using args[0], but rather with str1 then do "String str1 = args[0];"

What is it that you don't understand here? What is it that you are trying to figure out? I'm not at all sure what it is you're asking here.

I cant able to understand clearly.If you have any links for basic concepts in java Strings.
Please send it .Thank you for your valuable responses.

Thank you,

Prem - to keep it simple, here's a few simple things that you can accept as true. Later you can go into why they work this way, but for now:

1) You never need to declare a new String using the constructor form. Java will take care of it for you - Strings are not primitives, but Java has built in some special handling. That is, you'll never need to write

String thisString = new String();

Someone please correct me if I'm wrong, but I can't think of a case where you'd need to use that form.

2) If you have a need to assign a new String, just declare it, either as a literal:

String myString = "This is my String!";

or by reference to an existing string:

String yourString = myString;

3) If you're amending a string, use the StringBuffer instead. That is, if you're taking in a String and adding to it, substituting, or otherwise monkeying around with it, it's almost always going to be better to start with a StringBuffer and assign it to a String value when you're done.
So you're not going to need to declare a new String and then start adding stuff to it - you'll do that with StringBuffers.

StringBuffer sb = new StringBuffer(myString);
sb = sb.delete(8,10);
sb = sb.insert(8, "Prem's");
System.out.println(sb.toString());

The StringBuffer class is well documented by Sun, so read that before you ask about how to use it. Why to use it? Well, just trust me on this for now.

EDIT -----------------------
Please ignore the primitive "advice" here. It was a bad day. See two posts further.
EDIT -----------------------

That is, you'll never need to write

String thisString = new String();

Someone please correct me if I'm wrong, but I can't think of a case where you'd need to use that form.

Yes you will, just not with another String. If you have a byte[] or char[] you should use new String. Also, to get a String representation of any primitive type (unless it is simply part of another String) you should ue it.

I.E. if you have a boolen and you want to create a String that has "This boolen is true", you do

String str = "This boolean is " + booleanVar;

But, if all you want is "true" then you should do

String str = new String(booleanVar);

rather than what many novices do

String str = "" + booleanVar

as that form is horribly ineffecient. It creates an "interned" empty String, then it creates a StringBuffer using that interned String, then creates a String of the value of booleanVar adding that to the StringBuffer, then creates a String using that StringBuffer. That's a lot of steps as compared to simply creating a String using the booleanVar as

new String(booleanVar);

StringBuffer class is synchronized. The vast majority of the cases which don't need this synchronization are better off using its non-synchronized counterpart; StringBuilder.

> String str = new String(booleanVar);

I don't think there is any String constructor which takes a boolean. Anyways, the most efficient way to convert a boolean to String would be:

boolean bVar = true;
String bStr = Boolean.valueOf(bVar).toString();

It always returns the interned strings ("true" or "false").

The most commonly used String constructor is the one which accepts a byte[] or char[], which is normally required when reading from a char/byte based store.

Aach, yeah. Idiot. I was thinking of the valueOf method. Still applies that new String is useful when you have a byte[] or char[]. ;-) Oh, well. One of those days I guess.

Also, I was not advocating using a StringBuffer. I was listing the steps that are taken by the JVM when someone does "" + primitive (and the system does use StringBuffer). Much better to use String.valueOf(primitive) (which the "" + primitive also uses, but using it directly avoids the interned String and StringBuffer).

I.E.

String.valueOf(boolean)

rather than

"" + boolean

or

Boolean.valueOf(boolean).toString()

although that is still better than "" + boolean process.

Any particular reason to use
Boolean.valueOf(boolean).toString()
rather than new Boolean(boolean).toString()
?

> Also, I was not advocating using a StringBuffer

It wasn't meant for you but Jon who was mentioned using StringBuffer. :-)

> Any particular reason to use

The domain for a boolean type consists of only two values: true and false. The Boolean class has built-in two static variables; TRUE and FALSE representing truth and false values respectively.

AFAIK, new Boolean() always creates a new Boolean object (which isn't exactly required as explained above) whereas Boolean.valueOf(booleanVariable) returns one of Boolean.TRUE or Boolean.FALSE based on the passed in boolean to valueOf method.

Similar thing is with the Integer class, it is always recommended to use Integer.valueOf(int) instead of new Integer(int) since the Integer class maintains its own internal cache which returns cached objects for integer values in the range of -128 to 127. These cached objects don't present an issue given that the wrapper classes are immutable. :-)

~s.o.s~

AFAIK, new Boolean() always creates a new Boolean object (which isn't exactly required as explained above) whereas Boolean.valueOf(booleanVariable) returns one of Boolean.TRUE or Boolean.FALSE based on the passed in boolean to valueOf method.

thanks for that. J.

Oh, way too quick James. I kinda updated the original post with some more content. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.