Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings

 
Anju sethi
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question: What is the output of following if the return value is
"the value 0 if the argument string is equal to this string;
a value less than 0 if this string is lexicographically less than the string argument;
and a value greater than 0 if this string is lexicographically greater than the
string argument" (Assuming written inside main)

String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6));
System.out.println(s6.compareTo(s5));
System.out.println(s6.compareTo(s6));

Ans
a) -32
32
0
b) 32
32
0
c) 32
-32
0
d) 0
0
0

As per me answer should be c. But mock exam Question says it is a. Please explain how???
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What output did it generate when you ran the code?
 
Anju sethi
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am unable to sun this code as i am in a cyber cafe right now .
and found this problem just now in one of the mock exams.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here the answer is A)

because


s5.compareTo(s6)

It starts comparing from the left side each character..

Here the first character is different and the difference is -32

A is 65 and a is 97




s6.compareTo(s5)



Same as above ..but now it is 97-65 =32


s6.compareTo(s6)


Here all the characters in both the objects are same and so difference is not there ....So 0.


Hope you got it...
 
Anju sethi
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx Sir. I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic