difference between creating java string with and without new operator [duplicate] - java

This question already has answers here:
What is the difference between strings allocated using new operator & without new operator in java J2ME?
(5 answers)
Closed 8 years ago.
With new operator String create the string in heap and put a copy in string const pool so the result of hashcode is same in below case;
String s1 = new String("Test");
String s2 = new String("Test");
System.out.println(s1.hashCode() + " "+ s2.hashCode() + " " + s1.equals(s2));
But without using new operator its still giving the same hashcode
String s1 = new String("Test");
String s2 = "Test";
System.out.println(s1.hashCode() + " "+ s2.hashCode() + " " + s1.equals(s2));
Then what is the differnce between above two notation of string creation although they are referening to same string in string const. pool

Based on Effective java.
It is often appropriate to reuse a single object instead of creating a
new function- ally equivalent object each time it is needed. Reuse can
be both faster and more stylish. An object can always be reused if it
is immutable. As an extreme example of what not to do,
consider this statement:
String s = new String("stringette"); // DON'T
DO THIS!
The statement creates a new String instance each time it is
executed, and none of those object creations is necessary. The
argument to the String construc- tor ( "stringette" ) is itself a
String instance, functionally identical to all of the objects created
by the constructor. If this usage occurs in a loop or in a frequently
invoked method, millions of String instances can be created
needlessly.
The improved version is simply the following:
String s = "stringette";
This version uses a single String instance, rather than creating a new
one each time it is executed. Furthermore, it is guaranteed that the
object will be reused by any other code running in the same virtual
machine that happens to con- tain the same string literal
therefore creating unnecessary new Object of String or any other Objects are expensive.

From docs and Java.lang.String class, Internal Implementation of hashCode()
/**
* Returns a hash code for this string. The hash code for a
* String object is computed as
*
* s[0]*31^(n-1) + s1*31^(n-2) + ... + s[n-1]
*
* using int arithmetic, where s[i] is the
* ith character of the string, n is the length of
* the string, and ^ indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* #return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
More about String hashcode here

Both expression gives you String object, but there is difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. String s2 = "Test"; it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), if it's already exists. Otherwise it will create a new string object and put in string pool for future re-use.
for further reading see:here

String str = new String("String");
always create a new object on the heap.
Here creates a new String having for value the value of the constant "String" and assignates its reference to the variable str.
String str = "String";
uses the String pool
Here assignates the reference associated to the constant "String" to the variable str

Related

Using only 1 System.out.print() instead of 3. More details below [duplicate]

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

Build a String with String Operators [duplicate]

This question already has answers here:
String Constant Pool
(5 answers)
Closed 7 years ago.
In this example I thought that the result was true. I thought that the variable stored in the string pool.
The answer was: returns false because the two String objects are not the same in memory. One comes directly from the string pool and the other comes from building using String operations.
String a = "";
a += 2;
a += 'c';
a += false;
if ( a == "2cfalse") System.out.println("==");
I do not understand where the variable a was stored
Okay, so two responses to this. First, the ethically correct one, do never test strings with ==, always use .equals() or .equalsIgnoreCase().
Secondly, it's true that indeed, "a" == "a" because the strings are stored in, as you call it, the same pool. The problem here is that you append to it. Appending to a string causes it to become a different string, which is not stored in the string pool. The string pool is only generated on-compile, and as the second string is calculated on runtime, it won't match the one generated on-compile.
Imagine a string-pool to work like this:
a = "test";
b = "te";
c = "st";
d = "test";
The compiler translates this into
sp1 = "test";
sp2 = "te";
sp3 = "st";
a = sp1;
b = sp2;
c = sp3;
d = sp1;
Now == will check if two variables refer to the same sp. If you run b + c java will not go back and check if any of the sp's is the same as that. It only does that on compile.

Does "==" only apply to certain data types? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
In this program below:
public class medianTemp {
public static void main(String[] args){
int length = args.length;
int[] n = new int[length];
n[0] = Integer.parseInt(args[0]);
System.out.print(n[0] + " ");
for (int i = 1; i < length; i++ ){
String c = args[i];
if (c.equals(".")){
n[i] = n[i-1] + 0;
System.out.print(n[i] + " ");
}
if (c.equals("+")){
n[i] = n[i-1] + 1;
System.out.print(n[i] + " ");
}
if (c.equals("-")){
n[i] = n[i-1] - 1;
System.out.print(n[i] + " ");
}
Inside the for loop and inside the if statements. If I use for example args[i] == "." (instead of converting args[i] to string), the code above doesn't work and only the initial integer is displayed. Can someone please tell me why this happens?
== compares objects based on their memory location when they are not primitives. Strings are not primitives, so while the content of 2 String objects may be equal the address of each one in memory is different and == returns false.
In java, String objects (and nearly all objects) need to be compared with equals(). Two String objects may have the same value but be different objects (i.e. duplicates in memory a la new String()). The == comparison compares references.
You just need to use equals for string comparison.
Example from this website : http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);
It returns false, while the following code returns true.
String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));
== is a relational operator, referring to the relationships that values can have with one another.
Also, the == operator obviously means "Equal To" and only works for raw data types.
These types include double, int, and float. However, the == operator will not work in a boolean expression (only true/false works).
So in sum, it's really how you put your program together to get this operator to work. I recommend reading JAVA programming books such as the "JAVA 2" Series. Hope this helped!

Java String pool Storage doubts [duplicate]

This question already has answers here:
Testing string equality using hashCode()
(10 answers)
Closed 9 years ago.
why hashcode are same of string object ???
I'm trying to understand how string pool works.I have gone through many sites and finally i'm more confused now. Let me put down my doubts here. Someone help me in understanding them.
class cov {
public static void main(String[] args) {
String s = "abc"; //Object on string pool
System.out.println(s.hashCode());
String str = new String("abc"); //This statement does two things
System.out.println(str.hashCode());
}
}
A String's hashCode() method is calculated based on the chars it contains. If two String objects contain the same chars with the same case and in the same order, then they will have the same hashCode().
The String class has a hashCode method that calculates the hash code from its content, not from its memory location. So if two strings are identical (but not necessarily equal), they will have the same hash code.
If this were not the case, a structure such as HashSet<String> would be unusable - every new String would turn out not to be in the set, even when a String with the same characters had already been added.
Below is the source code which is used for generating hashCode
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
And as described in other answers hashCode is generated from the contents of the String not the place where it is residing. e.g heap stack or constant pool

How is + implemented in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java String concatenation
Sources tell us that concat is implemented as follows:
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
Does + implementation differ when it comes to Strings? How? Is there a performance difference between + and concat. When should one be chosen over another?
This is a test I just made:
I created a class with those 3 instructions:
String s1 = "foo";
String s2 = "bar";
String s3 = s1 + s2;
Then I took the generated .class file and I decompiled using JAD decompiler.
This is how the code show up in the regenerated source:
String s = "foo";
String s1 = "bar";
String s2 = (new StringBuilder()).append(s).append(s1).toString();
So: this is the difference between + and concat.
I guess concat() is always better than StringBuilder, because it requires less objects to be created. You may chose StringBuilder if you want to append string repeatedly in a loop; in this case concat may create a new String each time, while StringBuilder may just expand the internal buffer. But, if StringBuilder is best in this last scenario, we can say that still concat() is better than +, in loops.

Categories