Java String (Methods & Constructor) with Syntax and Example

Hope, you are enjoying the journey of learning Java. Till now, you are familiar with the fundamentals of Java. Today, we will discuss the Java string with its constructor and methods. Each one will be described with an example so we didn’t leave any room for queries.

Let’s start with an introduction to Java String.

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

1. What is the Java String?

Java String is a data type, which is used to represent text. In other words, strings are a sequence of characters, which are used to print any string and they are immutable, i.e. they cannot be changed once created. The string always ends with ‘\0’ or null character.

There are two ways to create a Java string.

  • Using a string literal in Java

String name = “DataFlair”;

  • Using a new keyword

String name = new String (“DataFlair”);

  • Graphical representation of the string

Introduction to Java Strings

Do you know how to create & initialize Arrays in Java?

Example of Java String-

// Java code to illustrate String 
package com.DataFlair.String;

public class JavaStringDemo {
  public static void main(String[] args) 
      { 
          // Declare String without using new operator 
          String name = "DataFlair Web Services"; 
    
          // Prints the String. 
          System.out.println("String name = " + name); 
    
          // Declare String using new operator 
          String name1 = new String("TechVidvan"); 
    
          // Prints the String. 
          System.out.println("String name1 = " + name1); 
      } 
  } 

Output-

JavaStringDemo

Before we discuss Java string constructors, you should be familiar with Constructors in Java

2. Java String Constructors

There are various types of String constructors in Java. Let us see them one by one:

String Constructor in Java

2.1 String(byte[] byte_arr)

It constructs a new string by the decoding of the byte array using the default character set of the platform for decoding.

Example

byte[] b_arr = {81, 101, 101, 107, 115};
String s_byte =new String(b_arr);
2.2 String(byte[] byte_arr, Charset char_set)

It constructs a new string by decoding of the byte array, it uses the char_set for decoding.

Example

byte[] b_arr = {81, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs);
2.3 String(byte[] byte_arr, String char_set_name)

It constructs a new string by decoding of the byte array using the char_set_name of the platform for decoding.

Example

byte[] b_arr = {68, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII");
2.4 String(byte[] byte_arr, int start_index, int length)

It constructs a new string by decoding of the byte array depending on the start_index(Starting location) and length(number of characters from starting location), it used char_set for decoding.

Are you aware of the difference between Array and ArrayList?

Example

byte[] b_arr = {68, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs);
2.5 String(byte[] byte_arr, int start_index, int length, String char_set_name)

It constructs a new string by decoding of the byte array depending on the start_index(Starting location) and length(number of characters from starting location), it uses char_set_name for decoding.

Example

byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII");
2.6 String(char[] char_arr)

This method allocates a new string from the character array.

Example 

char char_arr[] = {'d', 'o', 'g', 'k', 's'};
String s = new String(char_arr);

It’s time to reveal the truth of StringBuffer in Java

2.7 String(char[] char_array, int start_index, int count)

This method allocates a string to the given character array, the only difference is that it chooses count characters from the start index.

Example 

char char_arr[] = {'w', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3);
2.8 String(int[] uni_code_points, int offset, int count)

This method allocates a string from a uni_code_array but chooses the character from start_index.

Example

int[] uni_code = {61, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3);
3.9 String(StringBuffer s_buffer)

This method allocates a new method to the java string in s_buffer.

Example

String s_buffer = "dogs";
String s = new String(s_buffer);
2.10 String(StringBuilder s_builder)

This method allocates a new method to the string in s_builder.

Example

String s_builder = "dogs";
String s = new String(s_builder);

Don’t confuse between String, StringBuffer, and StringBuilder

3. Java String Methods

These are important Java String Methods-

String Methods in Java

3.1 length()

This method returns the number of character in the string.

Example

int len = sentence.length();
3.2 Char charAt(int i)

This java method returns the character at ith index.

Example

char ch=sentence.charAt(5);

Do you know what is Constructor Overloading in Java

3.3 String substring (int i)

This method returns the ith index substring.

Example

sentence.substring(11)
3.4 String Substring (int i, int j)

This method in java returns the substring from i to j-1 index.

Example

sentence.substring(2, 5);
3.5 String concat( String str)

This method concatenates the specified string to the end of this string.

Example

String name="DataFlair ";
name=name.concat("Web Services");
System.out.println("After concatenating the string is : "+name)
3.6 int indexOf (String s)

This method in java returns the index within the string of the first occurrence of the specified string.

Example

int index=sentence.indexOf("DataFlair's");
System.out.println("Index of DataFlair's is : "+index);
3.7 boolean equals( Object otherObj)

This method compares this string to the specified object.

Example 

boolvar1.equals(boolvar2)
3.8 int compareTo( String anotherString)

This method compares two string lexicographically.

Example

Integer num1 = new Integer(10);  
Integer num2 = new Integer(20);   
System.out.println(num1.compareTo(num2));
3.9. String toLowerCase()

This method converts all the characters in the String to lower case.

Example

String name1="HELLO DATAFLAIR";  
   String name1lower=name1.toLowerCase();
3.10 String toUpperCase()

This method converts all the characters in the String to upper case.

Example-

String name1upper=name1.toUpperCase();  
   System.out.println(name1upper);

Recommended Reading – Constructor Chaining in Java

3.11 String trim()

This method returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.

Example

String sentence2 = "   DataFlair has 4 Courses   ";   
   System.out.println(sentence2.trim());
3.12 String replace (char oldChar, char newChar)

This method returns new string by replacing all occurrences of oldChar with newChar.

Example

 String s1="DataFlair is a very good website";  
   String replaceString=s1.replace('a','e');  
   System.out.println(replaceString);

So, this was all about Java String Tutorial. Hope you like our explanation on String Methods and Constructor in java.

Java Quiz

4. Implementation of String Method

Let us see how we can use these methods on string with the help of a simple program

package com.DataFlair.String;

public class JavaStringMethods {
   public static void main(String args[]) {
   
  // using sting.length method 
   String sentence = "Welcome to DataFlair's tutorial for Java";
   int len = sentence.length();
   System.out.println( "String Length is : " + len );
   
   // using charAt(i) method
   char ch=sentence.charAt(5);
   System.out.println("Character at 5th position is : "+ch);
   
   //using substring method
   System.out.println("Using Substring");
   System.out.println(sentence.substring(11));
   
   //using concat method
   String name="DataFlair ";
   name=name.concat("Web Services");
   System.out.println("After concatenating the string is : "+name);
   
   // indexOf method
   int index=sentence.indexOf("DataFlair's");
   System.out.println("Index of DataFlair's is : "+index);
   
   // boolean equals method
   // boolean object
   Boolean boolvar1 = new Boolean(name); 
   // Boolean object 
   Boolean boolvar2 = new Boolean(sentence); 
   // compare method 
   System.out.println(boolvar1 + " comparing with " + boolvar2 + " = " + boolvar1.equals(boolvar2)); 
   
   //compareTo method
   System.out.println("Comparing Numbers");
   Integer num1 = new Integer(10);  
   Integer num2 = new Integer(20);   
   // as num1<num2, Output will be a value less than zero  
   System.out.println(num1.compareTo(num2));          
   
   // String to lowercsae method
   System.out.println("String in lower case");
   String name1="HELLO DATAFLAIR";  
   String name1lower=name1.toLowerCase();  
   System.out.println(name1lower);  
   
   //String to uppercase method
   System.out.println("String in lower case");
   String name1upper=name1.toUpperCase();  
   System.out.println(name1upper);
   
   //trim method
   String sentence2 = "   DataFlair has 4 Courses   ";  
   // trims the trailing and leading spaces  
   System.out.println(sentence2.trim());  
   
   //using replace method
   System.out.println("Replacing all the 'a' with 'e'");
   String s1="DataFlair is a very good website";  
   String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'  
   System.out.println(replaceString);
   
   }
   
   
   } 

Output-

Javastringmethod

5. Summary

In this article, we learned everything about Java String with its constructors and methods. Now, you can implement String methods in your code. If you face any query or doubt, feel free to share with us!

Next Article – Explore StringTokenizer In Java with Examples

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.