String in Java

In Java, a string is a sequence of characters enclosed in double quotes and is used to represent text. These characters can be letters, numbers, symbols, or even whitespace. Unlike some other programming languages where strings are primitive data types, in Java, strings are objects of the String class.

Declaring and Initializing a String

In Java, you can declare a string using a literal or by instantiating an object of the String class.

Here's how to declare and initialize a string using a literal in Java:

String message = "Hello, How are you?";

In the above example, "Hello, How are you?" is a string literal assigned to the variable message.

Here's how to declare and initialize a string by creating an object of the String class:

String message = new String("Hello, How are you?");

Important Characteristics of Strings

  • Immutable: String is immutable, meaning that once a string object is created, it cannot be modified. Any operation that attempts to modify a string creates a new string object.
  • Length: The number of characters in a string can be determined using the length() method.
  • Concatenation: Combining two strings is known as concatenation, and it can be done using the + operator or the concat() method.

Length of a String

To find the length of a string in Java, you can use the length() method.

Example:

package com.example.app;

public class Example {

  public static void main(String[] args) {
    String message = "Hello, How are you?";
    int length = message.length();
    System.out.println("Length of the string is: " + length);

  }

}

Output:

Length of the string is: 19

Concatenating Strings

To Concatenate two or more strings, you can use the + operator or the concat() method.

Example:

package com.example.app;

public class Example {

  public static void main(String[] args) {
    String firstName = "Danny";
    String lastName = "Master";
    String fullName = firstName + " " + lastName;
    System.out.println("Full Name: " + fullName);
  }

}

Output:

Full Name: Danny Master

Accessing Characters in a String

To access a character in a string, you can use the charAt() method.

Example:

package com.example.app;

public class Example {

  public static void main(String[] args) {
    String word = "Hello";
    char firstChar = word.charAt(0);
    System.out.println("First character: " + firstChar);
  }

}

Output:

First character: H

String Class Methods

The String class provides a wide range of methods for manipulating and working with strings. The following are some of the commonly used String methods in Java:

String MethodDescription
int length()Returns the length of the string.
char charAt(int index)Returns the character at the specified index.
String concat(String str)
Concatenates the specified string to the end of the current string.
String toUpperCase()
Converts the string to uppercase.
String toLowerCase()Converts the string to lowercase.
String substring(int beginIndex)
Returns a new string that is a substring of the original string, starting from the specified index.
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of the original string, starting from the specified begin index and ending at the specified end index.
int indexOf(String str)
Returns the index of the first occurrence of the specified substring within the string.
int lastIndexOf(String str)
Returns the index of the last occurrence of the specified substring within the string.
boolean startsWith(String prefix)
Checks if the string starts with the specified prefix.
boolean endsWith(String suffix)
Checks if the string ends with the specified suffix.
String replace(char oldChar, char newChar)
Replaces all occurrences of the specified old character with the new character.
String replaceAll(String regex, String replacement)
Replaces all occurrences of the specified regular expression with the replacement string.
String trim()
Removes leading and trailing whitespace from the string.
String [] split(String regex)
Splits the string into an array of substrings based on the specified regular expression.

Example:

Here's an example code to demonstrate how the String class methods are used in Java:

import java.util.Arrays;

public class Sample {

   public static void main(String[] args) {

	String myText = "Hello Universe";
		
        int textLength = myText.length();
        System.out.println(textLength);
        
        char charAt = myText.charAt(0);
        System.out.println(charAt);
        
        String myText2 = myText.concat(". It's a beautiful day.");
        System.out.println(myText2);
        
        String upperCaseText = myText.toUpperCase();
        System.out.println(upperCaseText);
        
        String lowerCaseText = myText.toLowerCase();
        System.out.println(lowerCaseText);
        
        String subText = myText.substring(0, 5);
        System.out.println(subText);
 
        int indexOfCh = myText.indexOf("U");
        System.out.println(indexOfCh);
        
        int lastIndexOfCh = myText.lastIndexOf("l");
        System.out.println(lastIndexOfCh);
        
        boolean isTextStartingWith = myText.startsWith("He");
        System.out.println(isTextStartingWith);
        
        boolean isTextEndingWith = myText.startsWith("rso");
        System.out.println(isTextEndingWith);
        
        String replacedText = myText.replace("Universe", "World");
        System.out.println(replacedText);
        
        String replacedAllText = myText.replaceAll("e", "E");
        System.out.println(replacedAllText);
        
        String trimmedText = myText.trim();
        System.out.println(trimmedText);
        
                
        String [] splittedTextArray = myText.split("\\s");
        System.out.println(Arrays.toString(splittedTextArray));
   }

}

Output:

14
H
Hello Universe. It's a beautiful day.
HELLO UNIVERSE
hello universe
Hello
6
3
true
false
Hello World
HEllo UnivErsE
Hello Universe
[Hello, Universe]