Computer Applications
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));
Answer
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.
Related Questions
How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }Predict the output of the following code snippet:
char ch='B', char chr=Character.toLowerCase(ch); int n=(int)chr-10; System.out.println((char)n+"\t"+chr);A student is trying to convert the string present in x to a numerical value, so that he can find the square root of the converted value. However the code has an error. Name the error (syntax / logical / runtime). Correct the code so that it compiles and runs correctly.
String x= "25"; int y=Double.parseDouble(x); double r=Math.sqrt(y); System.out.println(r);