aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes comparing string and primitive with equals( ) 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 "comparing string and primitive with equals( )" Watch "comparing string and primitive with equals( )" New topic
Author

comparing string and primitive with equals( )

Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
When I try the following piece of code



it compiles and runs fine, without throwing any errors or exception, evaluating to false. Since equals() in String takes an Object as an argument how come the above code works fine?


SCJP
Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69

so it's always syntactically valid to provide any object to a method that accepts an Object parameter


But i is a primitive. Can we pass a primitive when asked for an object?
(I am missing something!)
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Apologies, I just realized moments ago that I misread your question. To avoid confusion, I deleted my original reply, but it looks like you already responded before I finished the deletion.

Anyway, the behavior you're seeing is a result of auto-boxing, a new feature of Java 1.5. Basically, the compiler will automatically wrap and unwrap primitives for you in most cases when you use them in place of an object (or vice versa). For example, these statements are all now valid syntax:

Integer i = 42;
Boolean b = true; if (b) { /* ... */ }
Float f = 3.14; float g = f + 0.56;


SCJP 5.0
Preeti Yarla
Ranch Hand

Joined: Sep 08, 2007
Posts: 69
Thanks Kelvin! I am preparing for 1.4 so I haven't looked into autoboxing till now. And to add to that I am preparing for 1.4 by running code on Java 1.5. Not a good thing!
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14347
    
  22

If you're preparing for SCJP 1.4, then you should indeed use Java 1.4, not Java 5, otherwise you'll encounter some confusion, as you have noticed.

JDK 1.4.2 is still available for download on Sun's website.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy, just to make it clear



this compiles with java 5, but not earlier.

So be clear what exam you are in when you are sitting in the prometrics center.
The question "does this compile" would be different on 1.4 and 1.5 exam.


Yours,
Bu.


all events occur in real time
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: comparing string and primitive with equals( )