Java String Split Method Error? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Why does (("+k").split("k"))[0] not equal "+"? I am so confused.
Program:
//The Control Test
String a = "+";
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
//The Error
a = (("+k").split("k"))[0];
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
Output:
+
43
true
+
43
false -- Why?
So why in the world does a "+" not equal a "+"?!

You shouldn't compare Strings with ==. You should compare them with .equals() instead.
if(a.equals("+"))
{
// ...
}
This person explained it very well so there is no need for me to explain it again: look at this answer to a similar question.

String literals (strings placed directly in code) are stored in String pool and if some string literal is used few times same object from String pool is used. Since == compares references it will return true for
String a = "+";
System.out.println(a == "+");
Now Strings that are results of methods are separate objects that are not placed in String pool so in
String a = (("+k").split("k"))[0];
String object stored in a is different then "+" from String pool that is why == returns false.
To get rid of this problem you need to use equals method which will compare characters stored in String objects.

Related

Why does setting the value of two string the same and using == to compare them return true? [duplicate]

This question already has answers here:
Why does == return true for a String comparison? [duplicate]
(1 answer)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
String str1 = "apple";
String str2 = "apple";
System.out.println(str1 == str2);
Why does the 3rd line return true? I thought you couldn't compare strings like that
I understand that compareTo should be used for strings, why can I do ==
Because '==' is used to compare the reference of the objects
String string1 = new String("apple");
String string2 = new String("apple");
// Is false, they are two different objects
string1 == string2;
// Is true, their value are the same
string1.equals(string2);
// Is true because java uses the same object if you don't create a new one explicitly
"apple" == "apple";
Read this chapter of the article and you will understand.
The behavior you observe has to do with String literals where the JVM usually optimizes the storage by creating new literals if they don't already exist, otherwise providing the existing reference.
This should not be the way that you handle Strings though as they are still objects and you want to compare them by their content and not their memory reference which is what is happening when you use == .
This is why oracle explicitly advices for Strings to be compared using the equals method. There are many cases where a different object reference would be returned for some string that already exists in memory.
Check the following example to see one of those cases
public static void main(String[] args) {
String str1 = "apple";
String str2 = "apple";
System.out.println(str1==str2); //prints true
String str3 = "apple2";
String str4 = str3.replaceFirst("2","");
System.out.println(str1); //prints apple
System.out.println(str4); //prints apple
System.out.println(str1==str4); //prints false
System.out.println(str1.equals(str4)); //prints true
}

What will be output and explanation? [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 3 years ago.
Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
Use equals to compare string, it will return true for this case.
The == operator compares that the Strings are exactly the same Object.
This might theoretically happen in case of internalized strings, but you cannot rely on this. For your case, comparing String values, use str.equals(str2).
str and str2 are both assigned the same String instance, since String literals are automatically stored in the String pool. Therefore str == str2 is true.
However, you are printing the expression "==" + str == str2. That expression is evaluated from left to right, so first "==" + str is evaluated, and results with the String "==Bee". Then the == operator is applied to "==Bee" and "Bee", which returns false.
If you change the statement to:
System.out.println("==" + (str == str2));
you'll get true, since now the comparison will take place prior to the String concatenation.

getting == operator comparison false while comparing reference concatenated with literal with other reference [duplicate]

This question already has answers here:
Java String literals concatenation
(2 answers)
Closed 6 years ago.
When I perform the == operator comparison, I'm seeing false though I'm expecting the value to be true.
Why does this happen?
public class String1 {
public static void main(String[] args) {
//case 1
String s1="Hello";
String s2=s1+"Java";
String s3="HelloJava";
System.out.println(s2.equals(s3));// true
System.out.println(s2==s3);// expected True but getting output False
System.out.println(s2);
System.out.println(s3);
// case 2
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y);// TRUE as exepected
}
}
In Java the == operator tests reference equality -> same object
.equals() tests for value equality
in both of your cases you have different objects (s1, s2, x, y)
== compares references (i.e. pointer values) of objects.
In case 2 the compiler can shorten "he" + "llo" to "hello" as opposed to the first case where the concatination is performed at runtime.
Also string literals are cached in a pool. Thus two occurences of "hello" will normally refer to the same object. This is possible because strings are immutable.
Strings follow the same rule as every other object. If you want to compare pointers use ==, if you want to compare content use equals.

What is the difference between this two ways of initializing String [duplicate]

This question already has answers here:
What is Java String interning?
(8 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 6 years ago.
This two codes have defferent outputs and i don't know why.
String a="abc";
String b="abc";
System.out.println(a==b + " " + a.equals(b));
The output is "true true"
String a="abc";
String b=new String("abc");
System.out.println(a==b + " " + a.equals(b));
The output is "false true"
when you use this
String a="abc";
String b="abc";
the java creates only one object in memory which is abc and here a and b are pointing to same object and == don't check the string content instead it check the reference value. but as soon as you do this
String b=new String("abc");
java creates a new object b in memory which is different from a ,now b and a are pointing to two different objects hence if you compare contents with equals function result will be true but if you compare reference now, result will be false
Read about it's usage
This has to be a duplicate of a large number of questions, but I will comment by saying that when you do the following:
String a = "abc";
String b = "abc";
The JVM creates a single String object in the constant pool which contains the String abc. Hence, the a and b Strings simply point to the same string in the pool.
However, when you do the following:
String a = "abc";
String b = new String("abc");
a new object is created even though abc already exists in the pool. Hence the comparison a == b returns false, although the contents of both these strings remains equivalent.

Confused in appending Strings in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have a situation of appending String. And i'm confused ..
public static void foo() {
String s = "str4";
String s1 = "str" + s.length();
System.out.println("(s==s1) = " + (s1 == s));
}
And
public static void bar() {
String s = "str4";
String s1 = "str" + "4";
System.out.println("(s==s1) = " + (s1 == s));
}
In 1st case it's returning 'false' but in 2nd case 'true'
As i understand in both cases 'str4' object is being created on the heap. So it should return true in both cases. But it's not.
Kindly someone help me out why it's so. ? Thanks.!
Use
s1.equals(s)
to compare strings, otherwise you compare references.
In second case it returns true because String s1 = "str" + "4"; would be optimized to String s1 = "str4"; and s and s1 would refer to the same String.
The == operator in Java only returns true if both references refer to the same object. If you are trying to compare two Strings for equivalent content, you must use the equals() method.
you need to use .equals() for this
.equals() // if you dont want to ignore case
.equalsIgnoreCase() // if you want to ignore case
== compare the references.
In the second case both strings are equal .So references are also equal.
String s = "str4";
String s1 = "str" + "4"; .//finally str4
Here s1 ans s2 contents are equal.So they have same reference.
In my own understanding :
"str" => String
"4" => String
However,
s.length() => int
With ==, memory locations are compared.
Using the first example, Java creates another String which is in another memory location other than the location of 's' because you are trying to do String + int = String.
The second example returns true because it is just the same memory location as your 's' only that the value is changed. String + String = Concatenated String
Since you are trying to compare if the two strings have the same characters inside but not necessarily the same location, then s.equals(s1) is the best solution.
However, should you want to test if both variables are pointing to the same object then == must be used because of its shallow comparison.

Categories

Resources