What is the differance between those two Strings in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
Why when we declare string in Java we can't use == to compare this string and it will always turn to false, but if we initialize the string from the beginning it will be true?
For example :
import java.util.Scanner;
public class MyString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
if(s=="Hello")
System.out.println("Hello");
String d = "Hello";
if(d=="Hello")
System.out.println("Hello");
}
}
What is the explanation for this behavior?

This is an example of String.intern() happening automatically for string literals but not in general.
If you change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String s = input.nextLine();
s = s.intern();
if(s=="Hello")
System.out.println("Hello");
String d = "Hello";
if(d=="Hello")
System.out.println("Hello");
}
you will see "Hello" printed twice upon entering "Hello" at the console, because then all the copies of the "Hello" will have been interned to the same copy.
You should of course not normally use == to compare Strings, but use
if (s.equals("Hello")
This "intern" process is a way of reducing memory usage supported by many languages including Java. When you call s.intern() the run-times looks for a copy of the string in a pool of interned strings, uses one if it's found, and makes one otherwise, so that there's only one copy of that string. For more on the general idea, see this Wikipedia article.

Use str.equals(str2). Otherwise you are comparing whether the objects have the same address.

The reason is that the string object returned by input.nextLine() is not interned. So, it's not the same string object as the one represented by the string literal "Hello".
With the following, if you enter "Hello", you should see the difference:
Scanner input = new Scanner(System.in);
String s = input.nextLine();
s = s.intern();
if (s == "Hello") {
System.out.println("Hello 1");
}
String d = "Hello";
if (d == "Hello") {
System.out.println("Hello 2");
}

use .equals() method to check string equality. == checks if two reference variables point to the same string object.

nextLine() adds a "\n" to the end of the entered string, rendering it unequal to "Hello".

Related

String comparison in java does not gives the desired results [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I tried with the following class :
public class EqualMethodTestWithNew {
public static void main(String[] args) {
String value = "xxx";
String name = new String("xxx") ;
System.out.println("hascode : value : "+value.hashCode());
System.out.println("hascode : name : "+name.hashCode());
if (value == name) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
}
}
though the hasCode is same for the both variable it prints the false == 1. could some one explain the reason why?
thanks
You need to understand what exactly is happening when you execute the 2 string statements.
String value = "xxx";
The above line creates a new compile time constant string which does into the String intern pool.
String name = new String("xxx") ;
But in this case, since you're using the new operator, it creates a new String object which goes in the object heap. It does not have the same address as the one which was created in the previous statement.
The hashCode() method is based on the contents of the String which are the same, but that doesn't mean that they both refer to the same String object in the memory.
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // would return same value for all String objects having the same content
To compare the values, you need to use equals() method.
And if you want to compare the object references use the == operator. In your case, since both refer to difference objects, you get the output as false.
Alternatively, you can ask the compiler to check and fetch the reference of a String with the same value already existing in the String pool by using the intern() method.
String value = "xxx";
String name = new String("xxx");
name = name.intern(); // getting reference from string pool
Now you'll get the output as equal == 1 when your do if (value == name) {.
You should be using equals method instead of == opertaor.
if (value.equals(name)) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
Note that:
== tests for reference equality.
.equals() tests for value equality.
Please see here for more information.
The reason why your code is not working is that == tests whether the reference to the object is the same, and that is not your case. To compare the value of the string, you need to use the .equals(String str) method.
if (value.equals(name)) {
...
}
String should be compared with equals() method, not ==. You are trying the check the equality of the memory address of both instances (actually they are not) instead of the value in the String instances. So, use
if(value.equals(name)) {
System.out.println("equal == 1");
}
Strings are compared using equal() method. == compares the two objects are equal are not.

Java Input Problems - how to compare strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This seems to be pretty simple, but I have been stucked here for a couple of hours.
I have a doubt when you have to compare two Strings in Java.
if I just do something like this:
String var1 = "hello";
String var2 = "hello";
and then compare these two words in another function, the result will clearly be true.
But the problem is when I have to compare two words that come from an input. Here is my code:
import java.util.Scanner;
public class Compare{
public static void main(String[] args){
Scanner Scanner = new Scanner (System.in);
System.out.println("Enter first word: ");
String var1 = Scanner.nextLine();
System.out.println("Enter second word: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println("Yes");
else
System.out.println("No");
}
public static boolean same (String var1, String var2){
if (var1 == var2)
return true;
else
return false;
}
}
I have tried several times (clearly entering the same word) and the result is always False.
I don't know why this happens. What am I missing?
This is my first time in Java. I will appreciate any kind of help. Thanks
You should change
if (var1 == var2)
{
return true;
}
else
{
return false;
}
to
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
See this answer for the difference between the two
To be more accurate, with Strings in Java sometimes you can use == instead of .equals, if your string has been interned. Remember that == always compares the object references, not the contents of the object. Interning a String means that you will get the same object reference back and this is why == works with interned Strings.
Please read the Javadoc here to understand this more clearly:
String.intern()
In Java the == is a reference equality operator.
It works with the following.
String var1 = "hello";
String var2 = "hello";
boolean cmp = var1 == var2;
just because they are string literals and they are allocated in the same place inside the string table, so both variables point to the same string.
If you are fetching data from another source the strings are dynamically allocated, hence you should use the var1.equals(var2) (and you should ALWAYS use that one when comparing two objects).
Instead of if (same (var1, var2)) use if (v1.equals(v2)). No need to create a new method to compare two Strings. That's what equals() does.
== is used to compares references, not the contents of each String object.
The equality operator(==) checks the refernce of string first then checks value of string.
While equals method checks the value first.
So,in this case equals method should be used instead of equality operator.
String s="hello";
String s1="hello";
String s3=new String("hello")
In the above code snippet if you use If(s==s1){System.out.print("Equal");}it would print equal.But if you check If(s==s3){System.out.print("unqual");}it wouldn't print unequal.
so,you can see that even strings s and s3 are equal,output is wrong.Therefore,in this scenario like program in question
Equals method must be used.
var1 == var2
sometimes works because VM allocates the same memory both the variables for memory optimization and thus having same reference. That cannot be always the case so it's better to use
var1.equals(var2)
If you want to compare their values and doesnt care about reference.

Reading and checking strings from user input

I have this code:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
if(answer == "yes"){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
}
}
But when I run it and type yes, it should be saying
"Yea I programmed this right!"
but it says
"Awww :("
You're comparing strings incorrectly. You must use the equals() method, like this:
if (answer.equals("yes"))
When you're programming in Java, the operator == is generally used for comparing primitive data types (int, double, etc.). If you use == for comparing two object types (like strings), you're comparing them for identity, that is, checking if they reference the same object in memory. In your case, what you need is to compare if they're equal: if they have the exact same value (a string of characters in this case) even if they're two different objects - and for that you must use the equals() method.
EDIT :
Even better, for preventing a NullPointerException, it's considered a good practice flipping the order of the comparison and writing first the string you're comparing with, like this:
if ("yes".equals(answer))
The explanation is simple: if for some reason answer is null, the above comparison will evaluate to false (meaning: answer is not "yes"), whereas the first version of the code would cause a NullPointerException when trying to call the equals() method on a null value.
if(answer == "yes"){
should be
if("yes".equals(answer)){
(== is not correct for String equality, and we handle the case where answer is null)
Use String.equals() instead of ==.
In Java, == is testing that the 2 Strings are the exact same instance, where "a" != "a". Instead, you need to test for "a".equals("a").
So replace
if(answer == "yes"){
with:
if("yes".equals(answer)){
Note that flipping the order here is intentional, as this can prevent a NullPointerException if answer was null - as "yes".equals(null) will simply return false, instead of throwing an exception. (Calling an operation on null would throw a NullPointerException, I.E. null.equals("yes").)
Change this
if(answer.equals("yes")){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
The equals() method compares this string (answer in your example) to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
It is important to understand that the equals() method and the == operator perform two different operations. As just mentioned, the equals() method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
/*Edit your next line as mine,u'll get the correct ans...*/
if("yes".equals(answer)){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
}
}
or you can try to use "compareTo()" function
private static Scanner input;
private static String choice;
public static void main(String[] args) {
// TODO Auto-generated method stub
input = new Scanner(System.in);
choice = input.nextLine();
if (choice.compareTo("yes") == 0) {
System.out.println("Yea I programmed this right!");
} else {
System.out.println("Awww :(");
}
}

String object creation - double quotes, how? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Strings are objects in Java, so why don't we use 'new' to create them?
In Java, class objects are created like-
MyClass a=new MyClass();
then how String class objects are created like-
String a="Hello";
What does this "Hello" does to create new object?
String a = "Hello" doesn't actually create a new object. Instead, when the compiler sees a string literal like "Hello", it adds the string to the string literal pool, from which it will be loaded later.
Providing a String as a literal finally makes it in the String Literal Pool of the JVM. Quoting from this article:
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.For example:
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
}
}
The result is
true
Unfortunately, when you use
String a=new String("Hello");
a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2 + " ");
System.out.print(str1.equals(str2));
}
}
The result is
false true

Object comparison: Address vs Content

Hey guys im just messing around and I cant get this to work:
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String x = "hey";
System.out.println("What is x?: ");
x = input.nextLine();
System.out.println(x);
if (x == "hello")
System.out.println("hello");
else
System.out.println("goodbye");
}
it is of course supposed to print hello hello if you enter hello but it will not. I am using Eclipse just to mess around. A little quick help please
Should be if (x.equals("hello")).
With java objects, == is used for reference comparison. .equals() for value comparison.
Don't use == when testing for equality of non basic types, it will test for reference equality. Use .equals(..) instead.
Look at the following diagram:
When using == you're comparing the addresses of the boxes, when using equals you're comparing their content.
You can't compare a string like that.Because String is a class.So if you want to compare its content use equals
if (x.equals("hello"))
System.out.println("hello");
else
System.out.println("goodbye");
x=="hello" compares the references not values , you will have to do x.equals("hello").
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
Use "hello".equals(x) and never reverse since it does not handle null.
== operator checks equality of references (not values). In your case you have 2 String type object which have different reference but same value "hello". String class has "equals" method for checking values equality. The syntax is if(str1.equals(str2)).
Try this as the comparison:
if (x.equals("hello"))
Use x.equals("hello");
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Take this sample program:
public class StringComparison {
public static void main(String[] args) {
String hello = "hello";
System.out.println(hello == "hello");
String hello2 = "hel" + "lo";
System.out.println(hello == hello2);
String hello3 = new String(hello);
System.out.println(hello == hello3);
System.out.println(hello3.equals(hello));
}
}
Its output would be:
true
true
false
true
Objects hello and hello3 have different references that's why hello == hello3 is false, but they contain the same string, therefore equals returns true.
The expression hello == hello2 is true because Java compiler is smart enough to perform concatenation of two string constants.
So to compare String objects, you have to use equals method.

Categories