String in Java is immutable and stored in memory pool. Learn about StringBuffer, StringBuilder, and string manipulation techniques in Java.

 

In Java, String represents a sequence of characters. It is an immutable object, meaning once it is created, its value cannot be modified. If a string is updated, a new String object is created with the same reference. This behavior makes string manipulation in Java memory-efficient and secure.

Let’s start with a basic example:

String str = "India";
System.out.println(str);  // Output: India
String ctr = new String("India");
String ptr = "India";
String ktr = str;
str = str + "n";  // Now str points to a new object
System.out.println(str); // Output: Indian

How many objects and references?

  • Number of references: 4 (str, ctr, ptr, ktr)

  • Number of objects: 3

Ways to Create a String

  1. By string literal:

String str = "India";
  1. By using new keyword:

String ptr = new String("India");

Java String Pool

The Java String Pool is a memory area inside the heap where string literals are stored. It helps in memory optimization by avoiding the creation of duplicate strings.

Common Java String Methods

Java provides many built-in string methods in Java that help in manipulating and analyzing string data. These are part of the java.lang.String class.

String str = "Welcome to Cyberinfomines.com";
System.out.println(str);

Frequently Used Java String Functions:

  • length() – Returns the length of the string.

int size = str.length();
System.out.println("Length: " + size); // 29
  • charAt(int index) – Returns character at specific index.

  • substring(int beginIndex) – Extracts substring from beginIndex.

  • substring(int begin, int end) – Extracts substring from begin to end-1.

  • indexOf(String s) – Returns first index of given substring.

  • contains(CharSequence s) – Checks if the string contains a specific sequence.

  • toUpperCase(), toLowerCase() – Converts string to upper/lowercase.

  • trim() – Removes leading/trailing whitespace.

  • split(String regex) – Splits string into array using regex.

  • concat(String str) – Appends given string.

  • equals(), equalsIgnoreCase() – Compares strings.

  • compareTo(), compareToIgnoreCase() – Lexicographic comparison.

  • hashCode() – Returns hash code.

  • isEmpty() – Checks if string length is 0.

  • lastIndexOf() – Finds last index of a character or substring.

  • valueOf() – Converts different types (boolean, char, int, etc.) to string.

These java string methods are widely used in interview questions and real-world development scenarios.

Use Case: Short Name Generation

public class StringBasic {
    public static String getShortName(String firstName, String lastName, String surName) {
        String shortName = firstName.toUpperCase().charAt(0) + "." +
                lastName.toUpperCase().charAt(0) + "." +
                surName.toUpperCase().charAt(0) + surName.toLowerCase().substring(1);
        return shortName;
    }
    public static void main(String[] args) {
        System.out.println(getShortName("Sanjay", "kumar", "Chandel"));
        System.out.println(getShortName("sanjay", "kumar", "chandel"));
        System.out.println(getShortName("SANJAY", "KUMAR", "CHANDEL"));
    }
}

Use Case: Abbreviation Generator

public static void getShortName(String str) {
    String ans = "";
    String[] arr = str.split(" ");
    if (arr.length != 3) {
        System.out.println("Requirement is not enough, pass 3 words");
    } else {
        for (String i : arr) {
            ans += i.toUpperCase().charAt(0);
        }
    }
    System.out.println(ans);
}

Test Inputs:

  • Input: "Integrated Development Environment" → Output: IDE

  • Input: "Local area NETWORK" → Output: LAN

Use Case: Palindrome Check

public static int palindrome(String st) {
    int start = 0, end = st.length() - 1;
    if (st.length() < 3) return -1;
    for (int i = 0; i < st.length() / 2; i++) {
        if (st.charAt(start) == st.charAt(end)) {
            start++;
            end--;
        } else return 0;
    }
    return 1;
}

Test:

  • "Madam" → Palindrome

  • "computer" → Not Palindrome

  • "Vt" → Input too short

StringBuffer in Java

The StringBuffer class represents mutable strings. Unlike String, modifications can be made to the existing object.

StringBuffer buffer = new StringBuffer("Hello");
buffer.append(", World!");
System.out.println(buffer); // Hello, World!

Common String Buffer Methods:

  • append() – Appends content.

  • insert() – Inserts content at a specific index.

  • delete() – Deletes content between start and end.

  • replace() – Replaces content.

  • reverse() – Reverses the characters.

Because it is synchronized, StringBuffer is thread-safe and useful in multi-threaded environments.

StringBuilder vs StringBuffer

Both support mutable strings, but they differ in thread safety:

  • StringBuilder is not synchronized, hence faster in single-threaded applications.

  • StringBuffer is synchronized, hence safer in multi-threaded applications.

StringBuilder builder = new StringBuilder("Hello");
builder.append(", World!");
System.out.println(builder);

Both support:

  • append()

  • insert()

  • delete()

  • reverse()

  • replace()

Java Tokenization with StringTokenizer

StringTokenizer is a legacy class in Java used to split strings into tokens.

import java.util.StringTokenizer;
StringTokenizer tokenizer = new StringTokenizer("This is a sample sentence.");
while (tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

Example Use Cases of String Tokenizer:

  1. Word Count:

int wordCount = new StringTokenizer("This is a sentence").countTokens();
  1. Reverse Words: Use StringBuilder to reverse tokens.

  2. Extract Numbers: Check if token matches digits.

Frequently Asked Java String Interview Questions

  • Why is String immutable in Java?

  • What is the difference between String, StringBuffer and StringBuilder?

  • How is String Pool implemented in Java?

  • What happens in memory during string concatenation?

  • Why is String class final?

  • How do you create your own immutable class in Java?

String Programming Interview Questions in Java for Experienced

  • How to check if a string is a palindrome without using reverse()?

  • Find the first non-repeating character in a string.

  • Count frequency of characters in a string.

  • Detect anagram strings.

  • Remove duplicate characters.

These questions test your grasp on string coding questions in Java and help in real-time development as well.

Summary

In this article, you learned everything from basic to advanced about string in Java, including java string methods, java string functions, use of StringBuilder vs StringBuffer, and how java tokenization works using StringTokenizer. Understanding these concepts will help you in writing memory-efficient and high-performance Java applications.

Thank you for learning with us! Ready to start your Java journey or level-up your coding skills?

📞 Call us: +91-8587000904, 8587000906, 9643424141
🌐 Visit: www.cyberinfomines.com
📧 Email: vidhya.chandel@cyberinfomines.com

Download Lecture Pdf..

Leave a Comment

Get a Call Back from Our Career Assistance Team Request Callback
WhatsApp