Strings in Java Programming
Strings in Java Programming: In Java, a String is a sequence of characters. It is not a primitive data type but an object of the String class in the java.lang package. Strings are immutable – once a string object is created, it cannot be changed.If you modify a string, Java creates a new string object in memory.
Example:
String name = “Basant”;
Creating Strings in Java
There are two ways to create strings in Java, and these methods are Using String literals and using the new Keyword.
1. Using String Literals: In this method, the string is stored in a special memory area called the String Constant Pool. If another string with the same value is created, it will reuse the existing object instead of creating a new one. This helps in saving memory. Example
String s1 = "Java"; String s2 = "Java"; // Reuses the same object as s1 System.out.println(s1 == s2); // true (both refer to the same object)
2. Using new Keyword: In this method, a new object is always created in the heap memory, even if the same string already exists in the String Pool. This does not reuse objects and always allocates fresh memory. Example:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); // false (different objects in heap)Example Program: Demonstrating Both Methods
public class StringCreation { public static void main(String[] args) { // Method 1: Using String literal String s1 = "Hello"; String s2 = "Hello"; // Points to the same object // Method 2: Using new keyword String s3 = new String("Hello"); String s4 = new String("Hello"); // Creates new objects // Comparisons System.out.println("s1 == s2 : " + (s1 == s2)); // true System.out.println("s3 == s4 : " + (s3 == s4)); // false System.out.println("s1.equals(s3) : " + s1.equals(s3)); // true } }
Java program that creates a string using the new keyword:
public class StringExample { public static void main(String[] args) { // Creating a string using the new keyword String str = new String("Hello, World!"); // Printing the string System.out.println("The string is: " + str); } }
String manipulation method in Java
String manipulation method in Java means performing operations like joining, cutting, replacing, comparing, or changing strings using Java’s built-in methods. Here’s a list of the most commonly used String methods in Java with simple explanations and examples:
1. length()
Definition: Returns the total number of characters in a string.
Syntax:
String s = "Hello";
System.out.println(s.length()); // Output: 52. toUpperCase() / toLowerCase()
Definition: Converts all characters of the string to uppercase or lowercase.
Syntax:
String s = "Java";
System.out.println(s.toUpperCase()); // Output: JAVA
System.out.println(s.toLowerCase()); // Output: java
3. charAt(int index)
Definition: Returns the character at a specific position (index starts at 0).
Syntax:
String s = "World";
System.out.println(s.charAt(0)); // Output: W
System.out.println(s.charAt(3)); // Output: l
4. substring(int beginIndex, int endIndex)
Definition: Extracts a part of the string starting from beginIndex up to endIndex - 1.
String s = "Programming";
System.out.println(s.substring(0, 6)); // Output: Progra
System.out.println(s.substring(6)); // Output: mming
5. equals() / equalsIgnoreCase()
Definition: Compares two strings. equals() checks case-sensitivity, equalsIgnoreCase() ignores case.
Syntax:
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // Output: false
System.out.println(s1.equalsIgnoreCase(s2)); // Output: true
6. concat()
Definition: Joins one string with another.
Syntax:
String s1 = "Good ";
String s2 = "Morning";
System.out.println(s1.concat(s2)); // Output: Good Morning
7. replace()
Definition: Replaces characters or substrings with new ones.
Syntax:
String s = "Java is fun";
System.out.println(s.replace("fun", "powerful"));
// Output: Java is powerful
8. trim()
Definition: Removes spaces from the beginning and end of the string.
Syntax:
String s = " Hello World ";
System.out.println(s.trim()); // Output: Hello World
9. split()
Definition: Breaks a string into multiple parts based on a given delimiter.
Syntax:
String s = "apple,banana,orange";
String[] fruits = s.split(",");
for(String fruit : fruits) { System.out.println(fruit);
}
// Output: apple // banana // orange10. indexOf() / lastIndexOf()
Definition: Finds the position (index) of a character or substring.
Syntax:
String s = "Programming";
System.out.println(s.indexOf("g")); // Output: 3
System.out.println(s.lastIndexOf("g")); // Output: 10
Question: Write a Java program to find the length of the string
“Hello Java”.
Solution:
public class LengthExample { public static void main(String[] args) { String str = "Hello Java"; System.out.println("Length: " + str.length()); } } // Output: Length: 10
2 Question: Convert the string “Java Programming” to uppercase.
Solution:
public class UpperCaseExample { public static void main(String[] args) { String str = "java programming"; System.out.println(str.toUpperCase()); } } // Output: JAVA PROGRAMMING
3. Question: Convert the string “HELLO WORLD” to lowercase.
Solution:
public class LowerCaseExample { public static void main(String[] args) { String str = "HELLO WORLD"; System.out.println(str.toLowerCase()); } } // Output: hello world
4. Question: Print the 5th character of the string Programming.
Solution:
public class CharAtExample { public static void main(String[] args) { String str = "Programming"; System.out.println("5th character: " + str.charAt(4)); } } // Output: 5th character: r
5. Question: Extract "Java" from "I love Java programming".
Solution:Â
public class SubstringExample { public static void main(String[] args) { String str = "I love Java programming"; System.out.println(str.substring(7, 11)); } } // Output: Java
6. Question: Check if "Hello" is equal to "hello".
Solution:
public class EqualsExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; System.out.println(str1.equals(str2)); } } // Output: false
7. Question: Compare "Hello" and "hello" ignoring case.
Solution
public class EqualsIgnoreCaseExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; System.out.println(str1.equalsIgnoreCase(str2)); } } // Output: true
8.Question: Concatenate "Good" and "Morning" into one string.
Solution:
public class ConcatExample { public static void main(String[] args) { String str1 = "Good"; String str2 = "Morning"; System.out.println(str1.concat(" ").concat(str2)); } } // Output: Good Morning
9. Question: Replace "fun" with "awesome" in "Java is fun".
Solution:
public class ReplaceExample { public static void main(String[] args) { String str = "Java is fun"; System.out.println(str.replace("fun", "awesome")); } } // Output: Java is awesome
10. Question: Remove extra spaces from ” Hello World “.
Solution:
public class TrimExample { public static void main(String[] args) { String str = " Hello World "; System.out.println(str.trim()); } } // Output: Hello World
11.Question: Split "apple,banana,orange" using , and print each fruit.
Solution:
public class SplitExample { public static void main(String[] args) { String str = "apple,banana,orange"; String[] fruits = str.split(","); for(String fruit : fruits) { System.out.println(fruit); } } } // Output: // apple // banana // orange
12Question: Find the first and last position of 'g' in "Programming".
Solution:
public class IndexOfExample {
public static void main(String[] args) {
String str = "Programming";
System.out.println("First position: " + str.indexOf('g'));
System.out.println("Last position: " + str.lastIndexOf('g'));
}
}
// Output:
// First position: 3
// Last position: 10
StringBuffer Class in Java
The StringBuffer class in Java is used to create mutable strings, which means the content of the string can be modified after it is created. Unlike the String class (which creates immutable strings), StringBuffer allows you to append, insert, delete, or reverse characters in the same object without creating a new string. Common methods include: append(), insert(), delete(), reverse(), replace(), capacity().
Compiled by Er. Basant Kumar Yadav
Table of Contents
Toggle