-
Hajipur, Bihar, 844101
In Java, a String is one of the most commonly used data types. A string represents a sequence of characters enclosed within double quotes. It can contain letters, numbers, symbols, and spaces — for example, "Hello Java" or "12345". Strings are widely used in almost every Java program, whether it’s for taking user input, displaying output, or handling text data.
A String in Java is an object of the String class, which is part of the java.lang package. Unlike some other languages where strings are primitive types, in Java they are objects, meaning they have built-in methods that help perform different operations like comparison, concatenation, and modification.
Example:
String message = "Welcome to Java!";
System.out.println(message);
Here, message is a String variable that stores the text "Welcome to Java!".
There are two main ways to create a string in Java:
Using String Literal
Using the new Keyword
When you create a string using double quotes, Java automatically stores it in the String Pool for memory optimization.
Example:
String name = "Aarohi";
If you create another string with the same value, Java reuses the existing one from the String Pool.
new KeywordYou can also create a string using the new keyword. This method forces Java to create a new object in memory, even if the same value already exists.
Example:
String city = new String("Delhi");
Although this approach is valid, using string literals is generally preferred because it’s more memory-efficient.
The String class provides many useful methods that allow you to manipulate and analyze text data easily. Let’s go through the most common ones.
length()Returns the total number of characters in a string.
String word = "Programming";
System.out.println(word.length()); // Output: 11
toUpperCase() and toLowerCase()Converts all characters to upper or lower case.
String text = "Java";
System.out.println(text.toUpperCase()); // JAVA
System.out.println(text.toLowerCase()); // java
charAt()Returns the character at a specific index.
String name = "Riya";
System.out.println(name.charAt(2)); // y
concat()Joins two strings together.
String first = "Hello ";
String second = "World";
System.out.println(first.concat(second)); // Hello World
contains()Checks whether the string contains a specific sequence of characters.
String text = "Learning Java";
System.out.println(text.contains("Java")); // true
equals() and equalsIgnoreCase()Compares two strings for equality. The equalsIgnoreCase() method ignores letter case.
String a = "Hello";
String b = "hello";
System.out.println(a.equals(b)); // false
System.out.println(a.equalsIgnoreCase(b)); // true
substring()Extracts a portion of the string.
String word = "JavaProgramming";
System.out.println(word.substring(0, 4)); // Java
replace()Replaces a specific character or substring with another.
String text = "I like C";
System.out.println(text.replace("C", "Java")); // I like Java
trim()Removes leading and trailing spaces.
String text = " Hello ";
System.out.println(text.trim()); // Hello
indexOf() and lastIndexOf()Finds the position of a character or substring.
String sentence = "Hello Java World";
System.out.println(sentence.indexOf("Java")); // 6
System.out.println(sentence.lastIndexOf("World")); // 11
Concatenation means joining two or more strings. You can do this using the + operator or the concat() method.
Example:
String firstName = "Aarohi";
String lastName = "Sharma";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Aarohi Sharma
Java also allows concatenating strings with other data types, and it automatically converts them to strings.
Example:
int age = 22;
System.out.println("Age: " + age); // Age: 22
Comparing strings is very common, especially when checking passwords, user input, or conditional statements. Java provides multiple ways to compare strings.
Using equals() — compares values.
Using == — compares memory references.
Using compareTo() — compares lexicographically.
Example:
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true
Strings in Java are immutable, meaning once created, their value cannot be changed. When you modify a string, Java creates a new object instead of updating the old one.
Example:
String str = "Hello";
str.concat(" World");
System.out.println(str); // Output: Hello
Even though we used concat(), the original string str remains unchanged. To reflect changes, you need to reassign it:
str = str.concat(" World");
System.out.println(str); // Hello World
When you need to modify strings frequently (like in loops or large data operations), it’s better to use StringBuffer or StringBuilder because they are mutable.
StringBuffer — Thread-safe (synchronized)
StringBuilder — Faster but not synchronized
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
System.out.println(sb); // Hello Java
Strings are an essential part of Java programming. They help manage text data efficiently and come with powerful methods for manipulation.
Strings are objects, not primitive types.
They are immutable.
You can use methods like substring(), replace(), equals(), and concat() for various operations.
For better performance in repeated string modifications, use StringBuilder or StringBuffer.
Mastering Java strings is crucial because they appear in almost every real-world application.
Write a Java program that takes a string input from the user and prints its length using the length() method.
Create a program that compares two strings using both equals() and equalsIgnoreCase() methods, then prints whether they are the same or not.
Write a Java program that concatenates two strings using the + operator and the concat() method, then displays the final result.
Develop a Java program that takes a string and converts it to uppercase and lowercase using toUpperCase() and toLowerCase() methods.
Write a Java program that checks whether a given substring exists in a string using the contains() method and displays the position using indexOf().
Create a program that reverses a string using a loop without using any built-in reverse methods.
Write a Java program that replaces all occurrences of a specific word in a string with another word using the replace() method.
Develop a Java program that trims extra spaces from the beginning and end of a string using the trim() method and prints the cleaned version.
Write a program that splits a sentence into words using the split() method and prints each word on a new line.
Create a Java program that counts the number of vowels and consonants in a given string using loops and conditional statements.