KnowledgeBoat Logo

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));

Java

Java String Handling

ICSE Sp 2025

2 Likes

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));

  1. x.charAt(0): Retrieves the character at index 0 of x'G'.

  2. y.charAt(0): Retrieves the character at index 0 of y'G'.

  3. Comparison: 'G' == 'G'true.

(b) System.out.println(x.compareTo(y));

  1. x.compareTo(y): Compares x ("Galaxy") with y ("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).
  2. Result:

  • x.compareTo(y)108 - 109 = -1.

Answered By

3 Likes


Related Questions