• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Integer Class returns differently when we change the value

 
Laxman Nagalla
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Integer i=new Integer("11");
if(i.toString() == i.toString())
System.out.println("Equals");
else
System.out.println("Not Equal");

When i run the program it returns "Not Equal" .
The problem is when i change the value 11 as 10.
The output it was generating "Equals". Can any one tells why it behaves
different when we change the value.

Thanks
Laxmana
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is this the complete code that you have written or is there any statement above it which has "10" in it??? That's because I tried the program and it prints Not Equal for both 11 and 10....
 
Henry Wong
author
Marshal
Pie
Posts: 21005
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed, it should be "not equals" for both values. There is some code that is not being shown here.

Henry
 
Markus Klein
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
everytime i run this code the output is "Not Equal" ....
 
Laxman Nagalla
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Thanks For the very quick reply.

I am using the RAD6.0 Where it was Showing "Not Equals" and "Euals".
After your reply i checked with jdk5.0. Where its showing "Not Equals" "Not Equals" when i change the value 11 as 10. LEt me investigate where the exact issue.

:roll:
 
Umut Dogan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this example Java's pass-by-value and reference related knowledge is queried?

If you compile and run this code like below, it will print "Equals".



But if you compile and run as your code, it always prints out "Not Equals". This is because i.toString() creates different objects everytime and equality operator checks this objects if they are referencing the same.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic