the question about output format

D

David

class CompStr {
public static void main(String[] args) {
compare("first", "first");
compare("first", "second");
}
static void compare(String a,String b) {
System.out.println(a+"=="+b+": "+ a==b);
System.out.println(a+"!="+b+": "+ a!=b);
System.out.println(a+"="+b+": "+ a.equals(b));
}
}

i write this code for testing string comparision, however, when i execute
it,
System.out.println(a+"!="+b+": "+ a!=b);
System.out.println(a+"="+b+": "+ a.equals(b));
just output its boolean value, why.

the most interesting is when i change System.out.println(a+"=="+b+": "+
a==b)//--output value is false--// into System.out.println(a==b),the output
is true,

why is that???
 
T

Tor Iver Wilhelmsen

David said:
System.out.println(a+"!="+b+": "+ a!=b);
System.out.println(a+"="+b+": "+ a.equals(b));
just output its boolean value, why.

Operator left-associativity. You are in effect comparing the string

a+"!="+b+": "+a

against the string

b

You need to put a parenthesis around the last expression, e.g.

System.out.println(a+"!="+b+": "+ (a!=b));
^ ^
 
N

N.V.Dev

David said:
class CompStr {
public static void main(String[] args) {
compare("first", "first");
compare("first", "second");
}
static void compare(String a,String b) {
System.out.println(a+"=="+b+": "+ a==b);
System.out.println(a+"!="+b+": "+ a!=b);
System.out.println(a+"="+b+": "+ a.equals(b));
}
}

i write this code for testing string comparision, however, when i execute
it,
System.out.println(a+"!="+b+": "+ a!=b);
System.out.println(a+"="+b+": "+ a.equals(b));
just output its boolean value, why.

the most interesting is when i change System.out.println(a+"=="+b+": "+
a==b)//--output value is false--// into System.out.println(a==b),the output
is true,

why is that???


Well, as far as my understanding goes, below are the details.

a) when object is compared with another object then it is compared not
by value but by reference. Since, reference/address cannot be same, it
returns 'false'

which is a=b

when this done S.o.p() actually works on the basis of rule of
precedence.
remember right to left..... so, when compared, it is false and only
*boolean* is returned.

b) the same when changed from

System.out.println(a+"=="+b+": "+ a==b); to

System.out.println(a+"=="+b+": "+ a.equals(b) );

would print

first==first: true

NOTE: even if values of a = "first" and b = "fIrst" it would
display
first==fIrst: false


Any comments is appreciated.

Thanks in advance!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top