2(vi)
Write the output of the following String methods:
String x= "Galaxy", y= "Games";
(a) System.out.println(x.charAt(0)==y.charAt(0));
(b) System.out.println(x.compareTo(y));
Show SolutionHide Solution↓
The outputs are:
(a) true
(b) -1
Explanation:
Given Strings:
String x = "Galaxy"; String y = "Games";
(a) System.out.println(x.charAt(0) == y.charAt(0));
x.charAt(0): Retrieves the character at index0ofx→'G'.y.charAt(0): Retrieves the character at index0ofy→'G'.Comparison:
'G' == 'G'→true.
(b) System.out.println(x.compareTo(y));
x.compareTo(y): Comparesx("Galaxy") withy("Games") lexicographically (character by character based on Unicode values). The comparison is based on the first differing character:'G' == 'G'→ Equal, move to the next characters.'a' == 'a'→ Equal, move to the next characters.'l' == 'm'→'l'(Unicode 108) is less than'm'(Unicode 109).
Result:
x.compareTo(y)→108 - 109 = -1.