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:
-
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".
-
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: