Single Choice Easy

QPredict the output:-

String str1 = "great";
String str2 = "minds";

System.out.println(str1.substring(0, 2).concat(str2.substring(1)));
System.out.println("WH" + (str1.substring(2).toUpperCase()));

ID: #22227 switch case in Java 103 views
Question Info
#22227Q ID
EasyDifficulty
switch case in JavaTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A
    grinds
    WHEAT
  • B
    gre
    WHEAT
  • C
    grind
    WHEA
  • D
    none of these
Correct Answer

Explanation

Let's analyze the given Java code step by step to predict its output:

Code:


String str1 = "great";
String str2 = "minds";

System.out.println(str1.substring(0, 2).concat(str2.substring(1)));
System.out.println("WH" + (str1.substring(2).toUpperCase()));
        

Explanation:

  1. First Line:

    System.out.println(str1.substring(0, 2).concat(str2.substring(1)));\
    - str1.substring(0, 2) extracts a substring from str1 starting at index 0 up to, but not including, index 2.
    For str1 = "great", str1.substring(0, 2) results in "gr".
    - str2.substring(1) extracts a substring from str2 starting at index 1 to the end of the string.
    For str2 = "minds", str2.substring(1) results in "inds".
    - Concatenating these results:
    "gr".concat("inds") results in "grinds".
    - Therefore, the first println statement prints "grinds".

  2. Second Line:

    System.out.println("WH" + (str1.substring(2).toUpperCase()));
    - str1.substring(2) extracts a substring from str1 starting at index 2 to the end of the string.
    For str1 = "great", str1.substring(2) results in "eat".
    - str1.substring(2).toUpperCase() converts this substring to uppercase.
    "eat".toUpperCase() results in "EAT".
    - Concatenating "WH" with the result:
    "WH" + "EAT" results in "WHEAT".
    - Therefore, the second println statement prints "WHEAT".

Conclusion:

The output of the code is:

  • grinds
  • WHEAT

Share This Question

Challenge a friend or share with your study group.