Strings in Java

 

💫 Strings in Java 

In Java, strings are among the most widely used data types. Every program — whether simple or complex — deals with text, and Strings make that possible.

Let’s explore everything about Strings in Java, step by step! 🚀


🔹 What is a String?

A String in Java is a sequence of characters enclosed in double quotes (" ").

Example:

String name = "Alice";

Here, "Alice" is a String literal.


🔹 Strings are Objects

In Java, Strings are objects of the String class, which is part of the package:

java.lang

Even though you can create Strings just like primitive data types, under the hood, they are objects with many useful methods.


🔹 Ways to Create Strings

1️⃣ Using String Literals

String s1 = "Hello"; String s2 = "World";

Strings created this way are stored in a special memory area called the String Constant Pool.


2️⃣ Using the new Keyword

String s3 = new String("Hello");

This creates a new String object in heap memory, even if the same value exists in the String pool.


🔹 Example: Creating Strings

public class StringCreation { public static void main(String[] args) { String str1 = "Hello"; String str2 = new String("World"); System.out.println(str1); System.out.println(str2); } }

Output:

Hello World

🔹 String Immutability

Strings in Java are immutable, meaning once created, their value cannot be changed.

Example:

String s = "Hello"; s.concat(" World"); System.out.println(s);

Output:

Hello

Here, the original String s remains unchanged.
If we assign it back:

s = s.concat(" World"); System.out.println(s);

Output:

Hello World

A new String object is created with the modified value.


🔹 Common String Methods

The String class provides many useful methods. Let’s explore the most important ones 👇

MethodDescriptionExampleOutput
length()Returns number of characters    "Hello".length()5
charAt(int index)Returns character at index    "Java".charAt(2)v
toUpperCase()Converts to uppercase    "java".toUpperCase()JAVA
toLowerCase()Converts to lowercase    "HELLO".toLowerCase()hello
concat(String s)Joins two strings    "Hello".concat(" World")Hello World
equals(Object s)Compares two strings (case-sensitive)    "Java".equals("java")false
equalsIgnoreCase(String s)Case-insensitive comparison    "Java".equalsIgnoreCase("java")true
contains(String s)Checks if substring exists    "Machine             Learning".contains("Learn")true
substring(int start, int end)Returns substring    "Programming".substring(0, 7)Program
replace(char old, char new)Replaces characters"banana".replace('a', 'o')bonono
trim()Removes leading/trailing spaces" Hello ".trim()Hello

🔹 Example 1: Using String Methods

public class StringMethods { public static void main(String[] args) { String text = "Java Programming"; System.out.println("Length: " + text.length()); System.out.println("Uppercase: " + text.toUpperCase()); System.out.println("Substring: " + text.substring(5, 16)); System.out.println("Contains 'Pro'? " + text.contains("Pro")); } }

Output:

Length: 16 Uppercase: JAVA PROGRAMMING Substring: Programming Contains 'Pro'? true

🔹 String Comparison

1️⃣ Using ==

Compares references (memory locations), not content.

String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); // true (same String pool reference)
String s3 = new String("Hello"); System.out.println(s1 == s3); // false (different memory)

2️⃣ Using .equals()

Compares actual content of Strings.

System.out.println(s1.equals(s3)); // true

✅ Always use .equals() for comparing text values.


🔹 Example 2: Comparing Strings

public class StringCompare { public static void main(String[] args) { 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 } }

🔹 String Concatenation

Strings can be joined using either:

  1. The + operator

  2. The concat() method

Example:

String first = "Data"; String second = "Science"; String result1 = first + " " + second; String result2 = first.concat(" ").concat(second); System.out.println(result1); System.out.println(result2);

Output:

Data Science Data Science

🔹 String and Character Array Conversion

String → Char Array

String word = "Hello"; char[] letters = word.toCharArray(); for (char c : letters) System.out.print(c + " ");

Output:

H e l l o

Char Array → String

char[] chars = {'J', 'a', 'v', 'a'}; String s = new String(chars); System.out.println(s);

Output:

Java

🔹 Example 3: Palindrome Check

A palindrome reads the same forwards and backwards.

public class PalindromeCheck { public static void main(String[] args) { String str = "madam"; String rev = ""; for (int i = str.length() - 1; i >= 0; i--) { rev += str.charAt(i); } if (str.equals(rev)) System.out.println("Palindrome"); else System.out.println("Not Palindrome"); } }

Output:

Palindrome

🔹 StringBuffer and StringBuilder

Since String is immutable, Java provides mutable alternatives for string modification:

Class        Mutability        Thread-SafeFaster
String    ❌ Immutable            ✅ Yes            ❌ Slower
StringBuffer    ✅ Mutable            ✅ Yes            ⚙️ Moderate
StringBuilder    ✅ Mutable            ❌ No            ⚡ Fastest

Example:

StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb);

Output:

Hello World

🔹 Key Points to Remember

✅ Strings are objects, not primitive types.
✅ They are immutable — any change creates a new object.
✅ Use .equals() to compare content.
✅ Use StringBuilder or StringBuffer for frequent string modifications.
✅ Many built-in methods make text processing easy and efficient.



💡 Summary

Strings form the backbone of almost every Java program.

Understanding how they work, their immutability, and their rich set of methods helps you write cleaner, safer, and more efficient code.

Example Programs

1️⃣ Program to Count Vowels in a String

public class CountVowels { public static void main(String[] args) { String text = "Java Programming"; text = text.toLowerCase(); int count = 0; for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { count++; } } System.out.println("Number of vowels: " + count); } }

Output:

Number of vowels: 5

2️⃣ Program to Check Whether a String is a Palindrome

public class PalindromeCheck { public static void main(String[] args) { String str = "madam"; String rev = ""; for (int i = str.length() - 1; i >= 0; i--) { rev += str.charAt(i); } if (str.equals(rev)) System.out.println("Palindrome"); else System.out.println("Not Palindrome"); } }

Output:

Palindrome

3️⃣ Program to Reverse Each Word in a Sentence

public class ReverseWords { public static void main(String[] args) { String sentence = "Java is fun"; String[] words = sentence.split(" "); System.out.println("Reversed words:"); for (int i = 0; i < words.length; i++) { String word = words[i]; String rev = ""; for (int j = word.length() - 1; j >= 0; j--) { rev += word.charAt(j); } System.out.print(rev + " "); } } }

Output:

Reversed words: avaJ si nuf

4️⃣ Program to Compare Two Strings Ignoring Case

public class CompareStrings { public static void main(String[] args) { String str1 = "Java"; String str2 = "java"; if (str1.equalsIgnoreCase(str2)) System.out.println("Strings are equal (ignoring case)"); else System.out.println("Strings are not equal"); } }

Output:

Strings are equal (ignoring case)

5️⃣ Program to Convert a String to Uppercase Without Using toUpperCase()

public class UppercaseASCII { public static void main(String[] args) { String text = "java programming"; String result = ""; for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); // if character is lowercase letter if (ch >= 'a' && ch <= 'z') { ch = (char)(ch - 32); // convert to uppercase using ASCII difference } result += ch; } System.out.println("Uppercase string: " + result); } }

Output:

Uppercase string: JAVA PROGRAMMING


Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism