Question:

Consider the following string variables:
String str1 = "Hello";
String str2 = "Java Programming";
Write the code statements for the following in Java: (a) To display the string str1 into upper case.
(b) To display the character at the index 6 in string str2.
(c) To display the index of the first occurrence of letter ‘l’ in the string str1.
(d) To display the string str1 after replacing letter ‘l’ with ‘*’.

Show Hint

Use toUpperCase() to convert all characters of a string to capital letters.
Use charAt(index) to retrieve a character from a specific position in a string.
indexOf('char') gives the position of the first occurrence of a character in the string.
Use replace(oldChar, newChar) to substitute characters in a string.
Updated On: Jul 14, 2025
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

(a) To convert a string to upper case in Java, the toUpperCase() method is used.
It returns a new string with all characters converted to uppercase.
System.out.println(str1.toUpperCase());
This statement prints the string "HELLO".
The original value of str1 remains unchanged, as strings in Java are immutable.
(b) Java strings use zero-based indexing. The character at index 6 is the 7th character.
The charAt() method returns the character at a given index.
System.out.println(str2.charAt(6));
In "Java Programming", index 6 corresponds to the letter 'r'.
(c) The indexOf() method returns the position of the first occurrence of a character or substring.
System.out.println(str1.indexOf('l'));
In the string "Hello", the first 'l' appears at index 2.
If the character is not found, indexOf() returns -1.
(d) The replace() method replaces all occurrences of the specified character with another.
System.out.println(str1.replace('l', '*'));
This will output: "He**o" — as both 'l's are replaced with '*'.
The original string remains unchanged because strings in Java are immutable.
Was this answer helpful?
0
0