Java Basics-String

 

Java String

In this tutorial, we will learn about Java Strings, how to create them, and various methods of String with the help of examples.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.

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

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


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 firstsecond, 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.


Java String Operations

Java String provides various methods to perform different operations on strings. We will look into some of the commonly used string operations.

1. 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. 


2. Join two 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, we the concat() method joins first and second and assigns it to the joinedString variable.

We can also join two strings using the + operator in Java.


3. 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 firstsecond, 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. 

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


Methods of Java String

Besides those mentioned above, there are various string methods present in Java. Here are some of those methods:

MethodsDescription
substring()returns the substring of the string
replace()replaces the specified old character with the specified new character
charAt()returns the character present in the specified location
getBytes()converts the string to an array of bytes
indexOf()returns the position of the specified character in the string
compareTo()compares two strings in the dictionary order
trim()removes any leading and trailing whitespaces
format()returns a formatted string
split()breaks the string into an array of strings
toLowerCase()converts the string to lowercase
toUpperCase()converts the string to uppercase
valueOf()returns the string representation of the specified argument
toCharArray()converts the string to a char array

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 tring 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,

  1. JVM takes the first string "Hello! "
  2. creates a new string by adding "World" to the first string
  3. assign the new string "Hello! World" to the example variable
  4. 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. 

Note: The String class provides various other constructors to create strings. To learn more, visit Java String (official Java documentation).


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.

While creating strings using string literals, the value of the string is directly provided. 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 points to the existing string.
  • If the string doesn't exist, the new string is created.

However, while creating strings using the new keyword, the value of the string is not directly provided. Hence the new string is created all the time.


                                                 Java String Methods
















Java String split()

The Java String split() method divides the string at the specified regex and returns an array of substrings.

The syntax of the string split() method is:

string.split(String regex, int limit)

Here, string is an object of the String class.

split() Parameters

The string split() method can take two parameters:

  • regex - the string is divided at this regex (can be strings)
  • limit (optional) - controls the number of resulting substrings

If the limit parameter is not passed, split() returns all possible substrings.

split() Return Value

  • returns an array of substrings

Note: If the regular expression passed to split() is invalid, the split() method raises PatternSyntaxExpression exception.

Example 1: split() Without limit Parameter

// importing Arrays to convert array to string
// used for printing arrays
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    String vowels = "a::b::c::d:e";

    // splitting the string at "::"
    // storing the result in an array of strings
    String[] result = vowels.split("::");

    // converting array to string and printing it
    System.out.println("result = " + Arrays.toString(result));
  }
}

Output

result = [a, b, c, d:e]

Here, we split the string at ::. Since the limit parameter is not passed, the returned array contains all the substrings.

split() With limit Parameter

  • If the limit parameter is 0 or negative, split() returns an array containing all substrings.
  • If the limit parameter is positive (let's say n), split() returns the maximum of n substrings.

Example 2: split() With limit Parameter

// importing Arrays to convert array to string
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    String vowels = "a:bc:de:fg:h";

    // splitting array at ":"

    // limit is -2; array contins all substrings
    String[] result = vowels.split(":", -2);
    System.out.println("result when limit is -2 = " + Arrays.toString(result));

    // limit is 0; array contains all substrings
    result = vowels.split(":", 0);
    System.out.println("result when limit is 0 = " + Arrays.toString(result));

    // limit is 2; array contains a maximum of 2 substrings
    result = vowels.split(":", 2);
    System.out.println("result when limit is 2 = " + Arrays.toString(result));

    // limit is 4; array contains a maximum of 4 substrings
    result = vowels.split(":", 4);
    System.out.println("result when limit is 4 = " + Arrays.toString(result));

    // limit is 10; array contains a maximum of 10 substrings
    result = vowels.split(":", 10);
    System.out.println("result when limit is 10 = " + Arrays.toString(result));
  }
}

Output

result when limit is -2 = [a, bc, de, fg, h]
result when limit is 0 = [a, bc, de, fg, h]
result when limit is 2 = [a, bc:de:fg:h]
result when limit is 4 = [a, bc, de, fg:h]
result when limit is 10 = [a, bc, de, fg, h]

Note: The split() method takes regex as the first argument. If you need to use special characters such as: \|^*+ etc, you need to escape these characters. For example, we need to use \\+ to split at +.

Example 3: split() at the + character

// importing Arrays to convert array to string
// used for printing arrays
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    String vowels = "a+e+f";

    // splitting the string at "+"
    String[] result = vowels.split("\\+");

    // converting array to string and printing it
    System.out.println("result = " + Arrays.toString(result));
  }
}

Output

result = [a, e, f]

Here, to split a string at +, we have used \\+. It's because + is a special character (has a special meaning in regular expressions).

______________________________________________________________

Java String compareTo()

The Java String compareTo() method compares two strings lexicographically (in the dictionary order). The comparison is based on the Unicode value of each character in the strings.

The syntax of the compareTo() method is:

string.compareTo(String str)

Here, string is an object of the String class.

compareTo() Parameters

The compareTo() method takes a single parameter.

  • str - the string to be compared

compareTo() Return Value

  • returns 0 if the strings are equal
  • returns a negative integer if the string comes before the str argument in the dictionary order
  • returns a positive integer if the string comes after the str argument in the dictionary order

Example: Java String compareTo()

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "Learn Java";
        String str3 = "Learn Kolin";
        int result;

        // comparing str1 with str2
        result = str1.compareTo(str2);
        System.out.println(result); // 0

        // comparing str1 with str3
        result = str1.compareTo(str3);
        System.out.println(result); // -1

        // comparing str3 with str1
        result = str3.compareTo(str1);
        System.out.println(result); // 1
    }
}

Here,

  • str1 and str2 are equal. Hence, str1.compareTo(str2) returns 0.
  • str1 comes before str3 in the dictionary order. Hence, str1.compareTo(str3) returns negative, and str3.compareTo(str1) returns positive.

Example 2: Check if Two Strings are Equal

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Python";
        String str2 = "Learn Java";
        
        // if str1 and str2 are equal, the result is 0
        if (str1.compareTo(str2) == 0) {
            System.out.println("str1 and str2 are equal");
        }
        else {
            System.out.println("str1 and str2 are not equal");
        }
    }
}

Output

str1 and str2 are not equal

The compareTo() method takes the letter case (uppercase and lowercase) into consideration.

Example 3: compareTo() With Case

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn Java";
        int result;

        // comparing str1 with str2
        result = str1.compareTo(str2);
        System.out.println(result); // -32
    }
}

When "Learn Java" is compared to "learn Java", we do not get 0. It is because compareTo() takes the letter case into consideration.

Notes:

  • If you need to compare two strings ignoring case differences, use the Java String compareToIgnoreCase() method.
  • If you pass null to the compareTo() method, you will get an error.

Java String compareToIgnoreCase()

The Java String compareTo() method compares two strings lexicographically (in the dictionary order), ignoring case differences.

The syntax of the string compareToIgnoreCase() method is:

string.compareToIgnoreCase(String str)

Here, string is an object of the String class.

compareToIgnoreCase() Parameters

The string compareToIgnoreCase() method takes a single parameter.

  • str - the string to be compared

compareToIgnoreCase() Return Value

  • returns 0 if the strings are equal, ignoring case considerations
  • returns a negative integer if the string comes before the str argument in the dictionary order
  • returns a positive integer if the string comes before the str argument in the dictionary order

Example: Java String compareToIgnoreCase()

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn java";
        String str3 = "Learn Kolin";
        int result;

        // comparing str1 with str2
        result = str1.compareToIgnoreCase(str2);
        System.out.println(result); // 0

        // comparing str1 with str3
        result = str1.compareToIgnoreCase(str3);
        System.out.println(result); // -1

        // comparing str3 with str1
        result = str3.compareToIgnoreCase(str1);
        System.out.println(result); // 1
    }
}

Here,

  • str1 and str2 are equal if you do not consider the case differences. Hence, str1.compareToIgnoreCase(str2) returns 0.
  • str1 comes before str3 in the dictionary order. Hence, str1.compareToIgnoreCase(str3) returns negative, and str3.compareToIgnoreCase(str1) returns positive.

Example 2: Check if Two Strings are Equal

class Main {
    public static void main(String[] args) {
        String str1 = "LEARN JAVA";
        String str2 = "Learn Java";
        
        // if str1 and str2 are equal (ignoring case differences),
        // the result is 0
        if (str1.compareToIgnoreCase(str2) == 0) {
            System.out.println("str1 and str2 are equal");
        }
        else {
            System.out.println("str1 and str2 are not equal");
        }
    }
}

Output

str1 and str2 are equal

If you need to compare two strings with case differences taken into consideration, use either

  • Java String CompareTo()
  • Java String equals()

Java String length()

The Java String length() method returns the length of the string

The syntax of the length() method is:

string.length()

Here, string is an object of the String class.

length() Parameters

  • The length() method doesn't take any parameters.

length() Return Value

  • The length() method returns the length of the given string.

The length is equal to the number of char values (code units) in the string.

Example: Java String length()

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

        System.out.println(str1.length());  // 4
        System.out.println(str2.length());  // 0
        System.out.println("Java".length());  // 4
        System.out.println("Java\n".length()); // 5
        System.out.println("Learn Java".length()); // 10
    }
}

In the above program, the length of "Java\n" string is 5 instead of 6. It is because \n is a single character (newline) in Java.


Reference:https://www.programiz.com/java-programming/library/string/replace

Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Java OOPS:Constructors in Java – A complete study!!

Java Basics:Data Types