Introduce Java Strings and give examples
Java Strings are a sequence of characters used to represent text in Java programming. They are objects of the String
class, which is part of the java.lang
package. Strings in Java are immutable, meaning that once a String
object is created, its value cannot be changed. However, you can create new String
objects based on existing ones.
You can create a String
in Java in two main ways:
Using String Literals:
String str1 = "Hello, World!";
Using the new
Keyword:
String str2 = new String("Hello, World!");
Java provides a variety of methods to manipulate and interact with strings. Here are some commonly used methods:
Length:
String str = "Hello";
int length = str.length(); // Returns 5
Substring:
String str = "Hello, World!";
String sub = str.substring(7, 12); // Returns "World"
Concatenation:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // Returns "Hello World"
Character at a Specific Index:
String str = "Hello";
char ch = str.charAt(1); // Returns 'e'
String Comparison:
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // Returns false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // Returns true
Finding a Character or Substring:
String str = "Hello, World!";
int index = str.indexOf("World"); // Returns 7
Replacing Characters:
String str = "Hello, World!";
String newStr = str.replace("World", "Java"); // Returns "Hello, Java!"
Converting to Uppercase/Lowercase:
String str = "Hello, World!";
String upper = str.toUpperCase(); // Returns "HELLO, WORLD!"
String lower = str.toLowerCase(); // Returns "hello, world!"
Trimming Whitespace:
String str = " Hello, World! ";
String trimmed = str.trim(); // Returns "Hello, World!"
Here’s a simple Java program that demonstrates some of the string operations:
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello, World!";
// Length of the string
System.out.println("Length: " + greeting.length());
// Substring
System.out.println("Substring: " + greeting.substring(7, 12));
// Concatenation
String name = "Java";
String message = greeting + " Welcome to " + name + "!";
System.out.println("Message: " + message);
// Character at index
System.out.println("Character at index 1: " + greeting.charAt(1));
// String comparison
System.out.println("Equals 'Hello, World!': " + greeting.equals("Hello, World!"));
// Replace
System.out.println("Replaced: " + greeting.replace("World", "Java"));
// Uppercase
System.out.println("Uppercase: " + greeting.toUpperCase());
// Trim
String spacedString = " Hello, World! ";
System.out.println("Trimmed: '" + spacedString.trim() + "'");
}
}
Java Strings are a powerful and flexible way to handle text in your applications. Understanding how to create and manipulate strings is fundamental for any Java programmer.