in , ,

Java String

Java String
Java String

Java String

In this tutorial, we will find out about Java String, how to make it, and its different methods with the help of examples.

In Java, a string is a sequence of characters. For instance, “hello” is a string containing a grouping of characters ‘h’, ‘e’, ‘l’, ‘l’, and ‘o’.

In contrast to other programming languages, strings in Java are not primitive sorts (like int, char, and so forth) Rather, all strings are objects of a predefined class named String. For instance,

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

Here, we have created a string named type. Here, we have initialized the string with “java programming”. In Java, we use double quotes to represent a string.

The string is an instance of the String class.

Note: All string variables are instances of the String class.


Java String Methods

Java String gives different strategies that allow us to perform distinctive string tasks. Here is a portion of the usually used string methods.

MethodsDescription
concat()joins the two strings together
equals()compares the value of two strings
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
length()returns the size of the specified string
replace()replaces the specified old character with the specified new character
substring()returns the substring of the 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 data

Let’s take a few examples.


Example 1: Java find string’s length

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

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

    //checks the string length
    System.out.println("The length of the string: " + greet.length());
  }
}

Output

The string is: Hello! World
The length of the string: 12

In the above example, we have created a string named greet. Here we have used the length() method to get the size of the string.


Example 2: Java join two strings using Concat()

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

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

    String name = "World";
    System.out.println("Second String: " + name);

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

Output

First String: Hello!
Second String: World
Joined String: Hello! World

In the above example, we have created 2 strings named greet and name.

Here, we have used the concat() method to join the strings. Hence, we get a new string named joinedString.


In Java, we can also join two strings using the + operator.

Example 3: Java join strings using + operator

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

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

    String name = "World";
    System.out.println("Second String: " + name);

    // join two strings
    String joinedString = greet + name;
    System.out.println("Joined String: " + joinedString);
  }
}

Output

First String: Hello!
Second String: World
Joined String: Hello! World

Here, we have used the + operator to join the two strings.


Example 4: Java compare two strings

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

    // create 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 used the equals() method to look at the value of two strings.

The method returns true if the two strings are a similar else it returns false.

Note: We can likewise use the == operator and compareTo() method to make a correlation between 2 strings.


Example 5: Java get characters from a string

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

    // create string using the string literal
    String greet = "Hello! World";
    System.out.println("The string is: " + greet);

    // returns the character at 3
    System.out.println("The character at 3: " + greet.charAt(3));

    // returns the character at 7
    System.out.println("The character at 7: " + greet.charAt(7));
  }
}

Output

The string is: Hello! World
The character at 3: l
The character at 7: W

In the above example, we have used the charAt() method to access the character from the specified position.


Example 6: Java Strings other methods

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

    // create string using the new keyword
    String example = new String("Hello! World");

    // returns the substring World
    System.out.println("Using the subString(): " + example.substring(7));

    // converts the string to lowercase
    System.out.println("Using the toLowerCase(): " + example.toLowerCase());

    // converts the string to uppercase
    System.out.println("Using the toUpperCase(): " + example.toUpperCase());

    // replaces the character '!' with 'o'
    System.out.println("Using the replace(): " + example.replace('!', 'o'));
  }
}

Output

Using the subString(): World
Using the toLowerCase(): hello! world
Using the toUpperCase(): HELLO! WORLD
Using the replace(): Helloo World

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

Here,

  • the substring() method returns the string World
  • the toLowerCase() method converts the string to the lower case
  • the toUpperCase() method converts the string to the upper case
  • the replace() method replaces the character ‘!’ with ‘o’.

Escape characters in strings

Strings in Java are represented by double-quotes. For example,

// create a string
String example = "This is a string";

Now if we want to include double-quotes in our string. For example,

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

This will cause a mistake. It is on the grounds that double-quotes are used to represent the string. Consequently, the compiler will treat “This is the ” as a string.

To solve this issue, the escape character \ is used in Java. Presently we can include double-quotes for the string as:

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

The escape character tells the compiler to escape the double quote and read the whole text.


Java Strings are Immutable

In Java, making a string implies making an object of the String class. At the point when we make a string, we can’t change that string in Java. This is the reason strings are called immutable in Java.

To understand it more deeply, let’s consider an example:

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

Here, we have created a string object “Hello!”. Once it is created, we cannot change it.

Now suppose we want to change the string.

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

Here, we have attempted to add another string to the past string.

Since strings are immutable, it should cause an error. Yet, this works fine.

Presently it would seem that we can change the string. In any case, this isn’t true. We should perceive what has actually occurred here.

We have a string “Hello!”, referred to by the variable named example. Presently while executing the above code,

  • the JVM takes the string “Hello!”
  • appends the string ” World” to it
  • this creates a new string “Hello! World”
  • the variable example now refers to the new string
  • the previous string “Hello!” remains unchanged

Note: Every time a new string is created and it is referenced by a variable.


Making strings using the new catchphrase

So far we have made strings like primitive sorts in Java. In any case, since strings in Java are objects, we can make using the new catchphrase too. For instance,


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

In the above example, we have used the new keyword along with the constructor String() to create a string.

The String class provides various other constructors to create strings. To learn about all those constructors, visit Java String (official Java documentation).

Now, let’s see how this process of creating strings differs from the previous one.


Difference between Using String literals and new keyword

Since we realize how strings are made using string literals and the new watchword, how about we see what is the significant contrast between them.

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

While making strings using string literals, the estimation of the string is legitimately given. Thus, the compiler first checks the string pool to check whether the string as of now exists.

If the string already exists, the new string isn’t made. Instead, the new reference points to the existing string.

If the string doesn’t exist, the new string is made.

However, while making strings using the new catchphrase, the value of the string isn’t legitimately given. Henceforth the new string is made constantly.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

Java Constructors

Java Constructors

Java Access Modifiers

Java Access Modifiers