• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

String concatenation

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When i ran this :

class equals
{
public static void main(String args[]) {
Object o1= new Object();
Object o2 = new Object();
boolean b = (o1==o2);
System.out.println("== Magic " +b);;
}

}

It gave me result : == Magic false

But when i ran this:

class equals
{
public static void main(String args[]) {
Object o1= new Object();
Object o2 = new Object();
System.out.println("== Magic " +o1==o2);;
}

}

result was : false,

the == Magic string was lost, can some one explains me why?
 
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


I put o1==o2 in parenthesis like above. And I received the correct output.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by hewitt charlotte:
...System.out.println("== Magic " +o1==o2);...


...is what you have equivalent to...
System.out.println( "== Magic " + (o1 == o2) );
...or...
System.out.println( ("== Magic " + o1) == o2 );
 
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look when you using ("some string"+object1 == object2);

it will be converted to:

(("some string"+object1.toString())==object2)

so if you want the result of the latter expression to be concatenated to the string literal
use should use brackets with expression
same is true with int and string addition
e.g.

print("hello"+1+2);

output: hello12

print(1+2+"hello");

output: 3hello
 
reply
    Bookmark Topic Watch Topic
  • New Topic