Aug 27, 2024

Strings in Java with Coding Examples

Strings are very important in Java or any other programming language because they are used to store and manipulate text data. We cannot even imagine an application or website without having text on it. In almost every application, we need to work with text data, whether it is accepting input from the user or displaying a message to the user. It is also important to know about Strings and how it works internally if you are preparing for Java interviews. So knowing about Strings in Java is very important for both students and job seekers.

In this tutorial, we will learn what is a String in Java with its different types like String, StringBuffer, and StringBuilder. 


   What is a String?


A string in Java is a sequence of characters. In simple terms, it's a collection of letters, numbers, or symbols enclosed within double quotes. For example, "Hello, World!" is a string. In Java, strings are objects, which means they come with methods that allow us to perform various operations on them, like finding their length, converting them to uppercase, and more.


Types of Strings in Java

There are three main types of strings in Java:
  1. String
  2. StringBuffer
  3. StringBuilder
Let’s explore each one with examples.


1. String

A String is an immutable object in Java, that simply means once you create a string, you cannot change it.  If we try to modify a string then it will create a new string object.

Example of String:
String greet = "Welcome to ";
greet = greet + " BoldCoder";
System.out.println(greet); // Output: Welcome to BoldCoder
In the above code, even though it looks like we have modified the greet string, it has actually created a new string called "Welcome to BoldCoder" and assigned it back to greet. So, the value of the original string remains unchanged.

OUTPUT:

Welcome to BoldCoder



2. StringBuffer

StringBuffer is a mutable sequence of characters, which means you can modify the content of a StringBuffer object without creating a new object. StringBuffer is thread-safe, which means it is synchronized and can be safely used in a multi-threaded environment.

Example of StringBuffer:
StringBuffer sb = new StringBuffer("Bold");
sb.append("Coder");
System.out.println(sb); // Output: BoldCoder

In the above example, the append() method will add "Coder" to the existing StringBuffer object. Unlike String, it will not create a new object. So after appending the StringBuffer object(sb) value will be "BoldCoder".

OUTPUT:

BoldCoder



3. StringBuilder

StringBuilder is similar to StringBuffer but is not synchronized i.e. it is not thread-safe. This simply means it is faster than StringBuffer in situations where synchronization is not necessary, like in a single-threaded environment.

Example of StringBuilder:
StringBuilder sb = new StringBuilder("Bold");
sb.append("Coder");
System.out.println(sb); // Output: BoldCoder

Just like StringBuffer, StringBuilder is also a mutable class, which means it allows us to modify the original string. The difference is that StringBuilder is better in terms of performance when thread safety is not required.

OUTPUT:

BoldCoder



Now let's explore some of the mostly asked string coding interview questions or practice questions. Below is the list of String coding examples with their solutions.


   More String Examples:


1. Find the character at the given index in the String.

The below program prints the character at the given index in a String. To find a character at the given index we can use the charAt() method of String class.

import java.util.Scanner;

public class CharAtIndex {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Input the string
        System.out.print("Enter a string: ");
        String str = scanner.nextLine();
        
        // Input the index
        System.out.print("Enter the index: ");
        int index = scanner.nextInt();
        
        // Check if the index is within the valid range
        if (index >= 0 && index < str.length()) {
            // Find the character at the given index
            char character = str.charAt(index);
            System.out.println("Character at index " + index + " is: " + character);
        } else {
            System.out.println("Invalid index!" );
        }
        
        scanner.close();
    }
}



OUTPUT:

Enter a string: Bold Coder 
Enter the index: 1

Character at index 1 is o



2. Write a Java program to compare two strings, ignoring case sensitivity.

In the below program, we will compare two strings called str1 and str2 using equalsIgnoreCase()  method to ignore case sensitivity.

public class StringComparisonIgnoreCase {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "java";

        // Comparing two strings ignoring case
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("str1 and str2 are equal ignoring case.");
        } else {
            System.out.println("str1 and str2 are not equal ignoring case.");
        }
    }
}
OUTPUT:
str1 and str2 are equal ignoring case.


3. Write a Java program to reverse a given String.

Below program shows how to reverse a given string using reverse() method
public class ReverseStringExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Learn Java");
        
        // Reverse the string
        sb.reverse();
        
        // Print the reversed string
        System.out.println("Reversed String: " + sb.toString());
    }
}
OUTPUT:

Reversed String: avaJ nraeL


4. Write a Java program to reverse a given String without using the reverse() method.

In the below program, we will reverse a given string without using the reverse() method. Here, we will first convert a string to a character array using toCharArray() method and then we will use for loop to print the string in reverse order.

class HelloWorld {
    public static void main(String[] args) {
       
       String str = "I Love BoldCoder!";
       
       //converting a string to character array
       char[] strArray = str.toCharArray();
       
       //printing a string in reverse order
       for(int i=str.length()-1; i >= 0; i--){
           System.out.print(strArray[i]);
       }
       
    }
}

OUTPUT:
!redoCdloB evoL I



5. Find the length of the given string without using the length() method.

To find the length of a given string, we first convert the string into a character array. Then, we traverse the elements of the array using a loop. We increment a counter variable by one for each character in the array until we reach the end of the array.

class StringLength {
    public static void main(String[] args) {
        String str = "I Love BoldCoder!";
        
        // Convert the string to a character array
        char[] strArray = str.toCharArray();
        
        // Initialize a counter variable
        int length = 0;
        
        // Traverse the character array and increase the value of length by one
        int i = 0;
        while (i < strArray.length) {
            length++;
            i++;
        }
        
        // Print the length of the string
        System.out.println("The length of the string is: " + length);
    }
}

OUTPUT:

The length of the string is: 17

No comments:

Post a Comment

Share your thoughts or ask questions below!...👇

Featured Post

Java Interview Questions for 2 to 5 Years Experience

In this post, we are going to cover the most frequently asked Java interview questions for a 2 to 5 years experienced Java developer. It con...