File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Integer Class returns differently when we change the value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Integer Class returns differently when we change the value" Watch "Integer Class returns differently when we change the value" New topic
Author

Integer Class returns differently when we change the value

Laxman Nagalla
Greenhorn

Joined: Feb 01, 2008
Posts: 10
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


Thanks & Regards<br />Laxman N
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

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....


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19066
    
  40

Agreed, it should be "not equals" for both values. There is some code that is not being shown here.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Markus Klein
Greenhorn

Joined: Aug 29, 2008
Posts: 19
everytime i run this code the output is "Not Equal" ....
Laxman Nagalla
Greenhorn

Joined: Feb 01, 2008
Posts: 10
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

Joined: Nov 01, 2008
Posts: 1
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.
 
Consider Paul's rocket mass heater.
 
subject: Integer Class returns differently when we change the value