Java String (Methods & Constructor) with Syntax and Example

Free Java courses with 37 real-time projects - Learn Java

Earlier in this course we read about characters which are tokens of unit length. Now strings are a slightly different concept. Many characters join together to form a string. For example, the letter A individually is a character or a string. But “ABCD” together is a string only because it has more than one character in it.

Java strings

Java Strings

The strings in java are a collection of characters bound by double quotes(“”). They are immutable, i.e once they are declared, their values cannot be changed.String can also be listed as an array of characters starting at the index 0 and ending with a null character (\0).
This means that the first letter of the string is at index 0 to the last character of the string which is indexed at (length of the string-1).
This is an individual datatype in Java.

Methods of Declaring String in Java

There are two ways of declaring strings in Java

1. By using the new keyword
String course = new String(“Java”);

2. By using the String literal.
String course=”java”;

However there is a problem while declaring strings using the literal. In this method the String object is not created explicitly by the programmer(We do not use the new keyword). So the compiler creates one object for us when the line is executed. But, if we have the same string initialization in a different line, then the initialization would not be completed and no new object would be created.
for example,

  • String s1=”DataFlair”;
  • String s2=”DataFlair”;

For the first string the java object is created, which references s1. However when the second line is executed the s2 instance points to the same old “DataFlair” object which was declared before. No new objects are created.
But when you use the new keyword, JVM is forced to create a new object.

Java program to illustrate the use of new keyword and string literal

package com.dataflair.stringclass;
public class DeclareString {
  public static void main(String[] args) {
    String course = "Java";
    String course1 = new String("Python");
    System.out.println(course);
    System.out.println(course1);

  }
}

Output:

Java
Python

Java String Constant Pool

Do you know the differences between using a string literal and using the new keyword while declaring strings. Let us clear it once and for all. Remember we talked about java being a memory efficient programming language? This is how it manages to save a lot of memory:

When you are declaring a string literal(i.e without using the new keyword), the JVM stores this string in a pool of strings called the String Constant Pool. Simple,right? Now we declared two strings of the same value “DataFlair” in the case above. So what JVM does is, it creates a reference s1 and points it to the object “DataFlair”. Whenever the compiler executes the second line which is String s2=”DataFlair”; it realizes that DataFlair object is already in the String Constant Pool ! So, it points the new instance s2 to the same old “DataFlair” object created in the first line. No new objects create.

This results in saving up space as the JVM did not need to create a different object for the same String.
That is why the String Constant Pool is an integral part of Java.

String immutability advantages:
1. String constant pool

The string constant pool saves memory hence the string class being immutable helps a lot.

2. Security

The fact that strings cannot be changed also aids to security.

3. Thread Safe

Since the objects cannot be modified,multiple threads can share these objects amongst themselves.No synchronization is required.

4. Caching KEY

As strings are immutable, the hashcode of the same creates at the time of the string declaration. Then it can be used as candidate keys for hashmaps.

Memory Allocation

As soon as a string object gets created, it is created in two places, one in the heap memory and the other in the string constant pool. However when the second reference also has the same value as the one in the string constant pool the reference points to the pool memory instead of the heap memory.

All the following objects, the same as the one before are referenced in the String Constant Pool memory.

String constructors in Java

String Constructors in Java

While declaring a string object there are many types of constructors that can be called. Some of them are:

String(byte[] array)

This string is generated by the compiler by decoding the byte array provided. It happens by using the default character set of the platform.

The byte values are actually the ASCII values provided. The string is by converting them to their respective character values and then encoding the string.

Syntax:
String <variable> = new String(byte[]array)

String(byte[]array,charset)

It is similar to the previous constructor. The difference lies in the fact that it uses the given character set to decode the string.

Syntax:
String <variable> = new String(byte[]array, Charset)

String(byte[]array,String character_set_name)

This constructor decodes the byte array depending on the character set mentioned in the string.

Syntax:
String <variable> = new String(byte[]array,Character_setname);

String(byte[]array,int start_index,int length,String Character_setname)

This constructor decodes the byte array based on the starting index, the given length and the character set mentioned.

Syntax:
String<variable> = new String(byte[]array,int start_index,int length,String Character_setname);

String (char[] array)

This constructor forms the string by allocating a new string from the character array.

Syntax:
String <variable> = new String(char[]array);

String(char[]array, int start_index, int count)

This returns the string from the given character array by allocating strings from the start position.

Syntax:
String<variable>=new String(char[]array,int start_index,int count);
String(int unicode[]array,int offset,int count)

This returns a string from the unicode array from a given starting index.

Syntax:
String<variable> = new String(unicode[]array,int offset, int count);

Java String Buffer

This constructor is a mutable class which means that the strings passed through this can be changed as per requirement. It has thread protection, which means multiple threads cannot access the object passed.

Syntax:
StringBuffer<variable>=new StringBuffer(<String>);

Java String Builder

String builder is similar to a string buffer. It is a class which has mutable property. However string builder is free from thread protection, i.e., multiple threads can access the string at the same time. It is more efficient than a String buffer.

StringBuilder<variable> = new StringBuilder(<String>);

Java program to illustrate the usage of different constructor for string initialization:

package com.dataflair.stringclass;
import java.nio.charset.Charset;
public class DeclareString {
  public static void main(String[] args) {
    byte[] b_arr = {
      68,
      97,
      116,
      97,
      70,
      108,
      97,
      105,
      114
    };
    String s_byte = new String(b_arr);
    System.out.println("Direct conversion of byte array " + s_byte);

    Charset cs = Charset.defaultCharset();
    String charset = new String(b_arr, cs);
    System.out.println("Conversion of byte array by specified character set " + charset);

    String schar = new String(b_arr, 1, 3, cs);
    System.out.println("Using character set and offset indexes " + schar);

    char carr[] = {
      'D',
      'a',
      't',
      'a',
      'F',
      'l',
      'a',
      'i',
      'r'
    };
    String s_carr = new String(carr);
    System.out.println("Using character array " + s_carr);

    String s_carr2 = new String(carr, 1, 3);
    System.out.println("Using character array and start index " + s_carr2);

    int uni_code[] = {
      68,
      97,
      116,
      97,
      70,
      108,
      97,
      105,
      114
    };
    String s_unicode = new String(uni_code, 1, 4);
    System.out.println("Unicode conversion " + s_unicode);

    //using string buffer
    StringBuffer sbuf = new StringBuffer("DataFlair");
    System.out.println("The string builder initialization " + sbuf);

    //using string builder

    StringBuilder sbuild = new StringBuilder("Java");
    System.out.println("Using Stringbuilder initialization " + sbuild);
  }
}

Output:

Direct conversion of byte array DataFlair
Conversion of byte array by specified character set DataFlair
Using character set and offset indexes ata
Using character array DataFlair
Using character array and start index ata
Unicode conversion ataF
The string builder initialization DataFlair
Using Stringbuilder initialization Java

Java String Methods

String Methods in Java

1. length- This method is particularly useful for finding out the length of the string. It returns an integer which is the length of the string. The basic syntax of this method is <string variable>.length();

2. charAt- This returns the character at the particular index passed as an argument to this method. The syntax is <string variable>.charAt(<index>);

3. substring(int i)- This method returns a string which is a substring of the original string starting at the index passed as the argument to the method. This has a simple syntax of <String variable>.substring(<index>);

4. substring(int i,int j)- This method returns the substring which starts at the index i, given as the first argument to the method and ends at j, given as the second argument in the method. It has a simple syntax of <String variable>.substring(<index1>,<index2>);

5. concat- As the name suggests, this method is useful for concatenating two strings. Concatenating means adding together two entities. It has the syntax of <String-variable1>.concat(<String_variable2>); In place of the variables you can also use string literals directly.
You can also concat strings by simple add operator
Example- “Hello”+” DataFlair”; yields Hello DataFlair.

6. indexOf- This method returns the index of the first occurence of the character passed as an argument in the string.The syntax of the method is <string_variable1>.indexOf(<String_variable2>);

7. equals- This method returns true if both the strings are equal and false if they are not equal. It has a syntax of <String_variable1>.equals(<String_variable2>);

8. compareTo- This method compares the two strings in a lexicographical order. If both of the strings are equal it returns zero.The result is positive if the first argument string is greater than the second string, lexicographically. If not, the result is negative. It has a syntax of <variable1>.compareTo(<variable2>);

9. toLowerCase- Converts the string to lowercase. It has a syntax of <variable>.toLowerCase();

10. toUpperCase- Converts the string to uppercase. It has a syntax of <variable>.toUpperCase();

11. trim- Trims the string, i.e, removes all unnecessary spaces before and after the string. Note that it does not remove the spaces inside the string. It has a syntax like <variable>.trim();

12. replace- Returns the string by replacing all occurrences of the first character with the second character. It has a syntax <String_variable>.replace(<character1>,<character2>);

Java program to illustrate the string methods in Java:

package com.dataflair.stringclass;
public class StringMethods {
  public static void main(String[] args) {
    String s = "    I am learning Java at DataFlair!     ";

    System.out.println("The output of s.length() is " + s.length());
    System.out.println("The output of s.charAt(10) is " + s.charAt(10));
    System.out.println("The output of s.substring(4) is " + s.substring(4));
    System.out.println("The output of s.substring(5,10) is " + s.substring(10, 18));
    String s1 = "Data",
    s2 = "Flair";
    System.out.println("The output of s1.concat(s2) is " + s1.concat(s2));
    System.out.println("The output of s.indexOf('D') is " + s.indexOf("D"));
    System.out.println("The output of s.length() is " + s.length());
    System.out.println("The output of s1.equals(s2) is " + s1.equals(s2));
    System.out.println("The output of s1.compareTo(s2) is " + s1.compareTo(s2));
    System.out.println("The output of s.toLowerCase() is " + s.toLowerCase());
    System.out.println("The output of s.toUpperCase() is " + s.toUpperCase());
    System.out.println("The output of s.trim() is " + s.trim());
  }
}

Output:

The output of s.length() is 41
The output of s.charAt(10) is e
The output of s.substring(4) is I am learning Java at DataFlair!
The output of s.substring(5,10) is earning
The output of s1.concat(s2) is DataFlair
The output of s.indexOf(‘D’) is 26
The output of s.length() is 41
The output of s1.equals(s2) is false
The output of s1.compareTo(s2) is -2
The output of s.toLowerCase() is i am learning java at dataflair!
The output of s.toUpperCase() is I AM LEARNING JAVA AT DATAFLAIR!
The output of s.trim() is I am learning Java at DataFlair!

Quiz on Java String

Summary

Java Strings are extremely common as data entries in applications and managing them is an important task. So, a good knowledge of the string class and its methods is essential for manipulating and working with strings in programming.

Do share your feedback in the comment section if you like the article!!!

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

4 Responses

  1. Lyndon says:

    Am I missing something? I am a newbie but isn’t the answer 9?

    • Koen Hendriks says:

      Most programming languages (including Java) start counting from 0.

      So, 0, 1, 2, 3, 4, 5, 6, 7, 8 String characters.

  2. Rehima says:

    Great work 👏👏👏

  3. Lenin says:

    1. Question
    class Sample {
    public static void main ( String args [ ] )

    {

    String text = “DataFlair”;

    system.out.println(text.length());

    }

    }
    Incorrect answer

Leave a Reply

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