Ticker

6/recent/ticker-posts

Java String toLowercase() and toUpperCase() Methods


Java String toLowercase() and toUpperCase() Methods

Introduction

In Java, the String class provides two useful methods for converting the case of strings: toLowerCase() and toUpperCase(). These methods allow you to transform the characters in a string to either lowercase or uppercase, respectively. This can be helpful when you need to perform case-insensitive comparisons or manipulate strings based on their case.

1. toLowerCase() Method

Description

The toLowerCase() method in Java is used to convert all the characters in a given string to lowercase. The original string remains unchanged, and the method returns a new string with all lowercase characters.

Syntax

java
public String toLowerCase()

Example

java
public class ToLowerCaseExample {
public static void main(String[] args) {
String originalString = "Hello, World!";
String lowercaseString = originalString.toLowerCase();

System.out.println("Original String: " + originalString);
System.out.println("Lowercase String: " + lowercaseString);
}
}

Output


Original String: Hello, World!
Lowercase String: hello, world!

Explanation

In the above example, we first declare a String variable named originalString containing the value "Hello, World!". Then, we use the toLowerCase() method to convert all the characters in originalString to lowercase, and the result is stored in the lowercaseString variable. The original string remains unchanged.

2. toUpperCase() Method

Description

The toUpperCase() method in Java is used to convert all the characters in a given string to uppercase. Like toLowerCase(), the original string remains unchanged, and the method returns a new string with all uppercase characters.

Syntax

java
public String toUpperCase()

Example

java
public class ToUpperCaseExample {
public static void main(String[] args) {
String originalString = "Hello, World!";
String uppercaseString = originalString.toUpperCase();

System.out.println("Original String: " + originalString);
System.out.println("Uppercase String: " + uppercaseString);
}
}

Output


Original String: Hello, World!
Uppercase String: HELLO, WORLD!

Explanation

In the above example, similar to the previous one, we have a String variable named originalString with the value "Hello, World!". We then use the toUpperCase() method to convert all the characters in originalString to uppercase, and the result is stored in the uppercaseString variable.

Conclusion

In this documentation, we have learned about the toLowerCase() and toUpperCase() methods in Java's String class. These methods are helpful for transforming the case of strings, which is useful in various string manipulation scenarios. Remember that both methods return new strings and do not modify the original string.

Post a Comment

0 Comments