In Java, you can convert a string to uppercase using the toUpperCase
method of the String
class. This method returns a new string with all the characters in the original string converted to uppercase, according to the rules of the default locale.
Here is an example of how to use the toUpperCase
method to convert a string to uppercase:
String str = "hello world"; String upper = str.toUpperCase(); System.out.println(upper); // prints "HELLO WORLD"
You can also use the toUpperCase
method with a specific locale by passing the locale as an argument. For example:
String str = "hello world"; String upper = str.toUpperCase(Locale.FRENCH); System.out.println(upper); // prints "HELLO WORLD" in uppercase using the French locale
Note that the toUpperCase
method does not modify the original string, but rather returns a new string with the converted characters. If you want to modify the original string, you can assign the result of the toUpperCase
method back to the original string variable.
String str = "hello world"; str = str.toUpperCase(); System.out.println(str); // prints "HELLO WORLD"
If you want to convert only certain characters in a string to uppercase, you can use the toUpperCase
method along with the charAt
method to retrieve specific characters from the string, and the String.valueOf
method to convert individual characters to strings. For example:
String str = "hello world"; String upper = String.valueOf(str.charAt(0)).toUpperCase() + str.substring(1); System.out.println(upper); // prints "Hello world"
This code converts the first character of the string to uppercase and concatenates it with the rest of the original string to create a new string with the first character in uppercase.