Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparing string and primitive with equals( )

 
Preeti Yarla
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Preeti Yarla
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
Preeti Yarla
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic