Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

String Programs in Java

Last Updated on July 1, 2023 by Prepbytes

In Java, strings are an essential part of programming as they represent a sequence of characters. Manipulating strings is a common task in Java programming, and understanding how to work with strings effectively is crucial. This article serves as an introduction to writing programs on string in Java covering the basics of string manipulation, concatenation, comparison, and other common operations.

In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters ‘h’, ‘e’, ‘l’, ‘l’, and ‘o’.

We use double quotes to represent a string in Java. For example,

// create a string
String type = "Java programming";

Here, we have created a string variable named type. The variable is initialized with the string Java Programming.

Example: Create a String in Java

class Main {
  public static void main(String[] args) {
    
    // create strings
    String first = "Java";
    String second = "Python";
    String third = "JavaScript";

    // print strings
    System.out.println(first);   // print Java
    System.out.println(second);  // print Python
    System.out.println(third);   // print JavaScript
  }
}

In the above example, we have created three strings named first, second, and third. Here, we are directly creating strings like primitive types.

However, there is another way of creating Java strings (using the new keyword). We will learn about that later in this tutorial.

Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects of a predefined class named String.

And, all string variables are instances of the String class.

Java String Operations Programs

Java’s String class offers a wide range of methods that facilitate diverse operations on strings.

Get length of a String

To find the length of a string, we use the length() method of the String. For example,

class Main {
  public static void main(String[] args) {

    // create a string
    String greet = "Hello! World";
    System.out.println("String: " + greet);

    // get the length of greet
    int length = greet.length();
    System.out.println("Length: " + length);
  }
}

Output

String: Hello! World
Length: 12

In the above example, the length() method calculates the total number of characters in the string and returns it. To learn more, visit Java String length().

Join Two Java Strings

We can join two strings in Java using the concat() method. For example,

class Main {
  public static void main(String[] args) {

    // create first string
    String first = "Java ";
    System.out.println("First String: " + first);

    // create second
    String second = "Programming";
    System.out.println("Second String: " + second);

    // join two strings
    String joinedString = first.concat(second);
    System.out.println("Joined String: " + joinedString);
  }
}

Output

First String: Java 
Second String: Programming     
Joined String: Java Programming

In the above example, we have created two strings named first and second. Notice the statement,
String joinedString = first.concat(second);
Here, the concat() method joins the second string to the first string and assigns it to the joinedString variable.

We can also join two strings using the + operator in Java. To learn more, visit Java String concat().

Compare two Strings

In Java, we can make comparisons between two strings using the equals() method. For example,

class Main {
  public static void main(String[] args) {

    // create 3 strings
    String first = "java programming";
    String second = "java programming";
    String third = "python programming";

    // compare first and second strings
    boolean result1 = first.equals(second);
    System.out.println("Strings first and second are equal: " + result1);

    // compare first and third strings
    boolean result2 = first.equals(third);
    System.out.println("Strings first and third are equal: " + result2);
  }
}

Output

Strings first and second are equal: true
Strings first and third are equal: false

In the above example, we have created 3 strings named first, second, and third. Here, we are using the equal() method to check if one string is equal to another.

The equals() method checks the content of strings while comparing them. To learn more, visit Java String equals().

Note: We can also compare two strings using the == operator in Java. However, this approach is different than the equals() method. To learn more, visit Java String == vs equals().

Escape character in Java Strings

The escape character is used to escape some of the characters present inside a string.

Suppose we need to include double quotes inside a string.

// include double quote 
String example = "This is the "String" class";

Since strings are represented by double quotes, the compiler will treat "This is the " as the string. Hence, the above code will cause an error.

To solve this issue, we use the escape character \ in Java. For example,

// use the escape character
String example = "This is the \"String\" class.";

Now escape characters tell the compiler to escape double quotes and read the whole text.

Java Strings are Immutable

In Java, strings are immutable. This means, once we create a string, we cannot change that string.

To understand it more deeply, consider an example:

// create a string
String example = "Hello! ";

Here, we have created a string variable named example. The variable holds the string "Hello! ".

Now suppose we want to change the string.

// add another string "World"
// to the previous string example
example = example.concat(" World");

Here, we are using the concat() method to add another string World to the previous string.

It looks like we are able to change the value of the previous string. However, this is not true.

Let’s see what has happened here,

  • JVM takes the first string "Hello! "
  • creates a new string by adding "World" to the first string
  • assign the new string "Hello! World" to the example variable
  • the first string "Hello! " remains unchanged
  • Creating strings using the new keyword
  • So far we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using the new keyword as well. For example,

// create a string using the new keyword
String name = new String("Java String");

In the above example, we have created a string name using the new keyword.

Here, when we create a string object, the String() constructor is invoked. To learn more about constructor, visit Java Constructor.

Example: Create Java Strings using the new keyword

class Main {
  public static void main(String[] args) {

    // create a string using new
    String name = new String("Java String");

    System.out.println(name);  // print Java String
  }
}

Create String using literals vs new keyword

Now that we know how strings are created using string literals and the new keyword, let’s see what is the major difference between them.

In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.

  1. While creating strings using string literals,
    String example = "Java";
    Here, we are directly providing the value of the string (Java). Hence, the compiler first checks the string pool to see if the string already exists.
    If the string already exists, the new string is not created. Instead, the new reference example points to the already existing string (Java).
    If the string doesn’t exist, the new string (Java is created).

  2. While creating strings using the new keyword,
    String example = new String("Java");
    Here, the value of the string is not directly provided. Hence, a new "Java" string is created even though "Java" is already present inside the memory pool.

Conclusion:
In conclusion, understanding string manipulation in Java is crucial for developing robust applications. Throughout this article, we have covered the basics of creating and initializing strings, concatenating them, performing common operations, comparing strings, formatting them, and utilizing mutable string classes like StringBuilder and StringBuffer. By mastering these concepts and techniques, you will be equipped to handle various string-related tasks and solve real-world programming challenges effectively in Java.

FAQs related to String Programs in Java:

Frequently asked questions related to string program in Java are discussed below:

Q1: Are strings mutable or immutable in Java?
In Java, strings are immutable, meaning their values cannot be changed after they are created. However, string manipulation operations create new string objects rather than modifying the existing ones.

Q2: How can I check if two strings are equal in Java?
To check if two strings have the same content, you can use the equals() method provided by the String class. For example, str1.equals(str2) will return true if str1 and str2 have identical content.

Q3: How do I concatenate strings efficiently in Java?
While concatenating strings with the + operator or using the concat() method works, it can be inefficient when concatenating multiple strings. To concatenate strings efficiently, you can use the StringBuilder class, which provides a mutable string buffer.

Q4: Can I convert a string to uppercase or lowercase in Java?
Yes, you can convert a string to uppercase using the toUpperCase() method or to lowercase using the toLowerCase() method provided by the String class. For example, str.toUpperCase() will return the uppercase version of str.

Q5: How can I extract a substring from a string in Java?
You can extract a substring from a string by using the substring() method, which allows you to specify the starting and ending indices of the desired substring. For example, str.substring(startIndex, endIndex) will return the substring starting from startIndex and ending at endIndex-1.

Q6: How can I split a string into an array in Java?
You can split a string into an array of substrings using the split() method, which accepts a delimiter as an argument. It separates the string at each occurrence of the delimiter and returns an array of the resulting substrings.

Q7: Is it possible to format strings dynamically in Java?
Yes, Java provides the printf() method, which allows you to format strings dynamically using placeholders and format specifiers. This method is similar to the C language’s printf() function.

Q8: Can I modify a string in Java without creating a new object?
No, since strings are immutable in Java, you cannot modify them directly. However, you can use mutable string classes like StringBuilder or StringBuffer to perform efficient string manipulations.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *