Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with String Constructors in Java

In this lesson, you will learn

  • String Constructors
  • String Concatenation
  • toString( ) Method
  • Methods of String Class

 

String Constructors

In Java, strings are objects that represent sequences of characters. The String class provides several constructors for creating strings.

Here are the primary constructors used to create strings in Java, along with examples.

 

1. Creating String from Default Constructor

Creates an empty string. This constructor is not often used since strings are immutable, and you can’t change an empty string afterward.

String str = new String();
// Creates an empty string

 

2. Creating String from an Array of Characters

To create a String initialized by an array of characters, use the following constructor

Constructor: public String(char chars[ ])

Example

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);
/* Creates a string "Hello" from an 
array of characters */

You can specify a subrange of a character array as an initializer using the following constructor:

 

Constructor: public String(char chars[ ], int startIndex, int numChars)

 

Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.

Example

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
//This initializes s with the characters cde.

 

3. Creating String from String Objects

You can construct a String object that contains the same character sequence as another String object using this constructor.

Constructor: public String(String strObj)

Here, strObj is a String object.

Example

package ch11.l2;

public class CreateString {
	public static void main(String[] args) {
		char c[] = {'J', 'a', 'v', 'a'}; 
		String s1 = new String(c);
		String s2 = new String(s1);
		System.out.println(s1);
		System.out.println(s2);
		System.out.println("s1==s2: "+(s1==s2));
		//check equality of objects
	}
}

Output

Java
Java
s1==s2: false

 

4. Creating String from Byte Array

Constructs a new String by decoding an array of bytes using the platform’s default charset.

Constructors:

public String(byte chrs[ ])
public String(byte chrs[ ], int startIndex, int numChars)

Here, chrs specifies the array of bytes. The second form allows you to specify a subrange.

Example

package ch11.l2;

public class MakeStringFromByteArray {

	public static void main(String[] args) {
		byte ascii[] = {65, 66, 67, 68, 69, 70 };
		String s1 = new String(ascii);
		System.out.println(s1);
		String s2 = new String(ascii, 2, 3);
		System.out.println(s2);
	}
}

Output

ABCDEF
CDE

 

5. Creating String from a Substring

  • Constructs a new String that contains characters from a substring(int beginIndex) and substring(int beginIndex, int endIndex) of an existing String.
  • The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

Example

String original = "Hello, World!";
String str = new String(original.substring(0, 5));
/* Creates a string "Hello" from a 
substring of "Hello, World!" */

 

6. StringBuilder or StringBuffer

  • Constructs a new String that represents the same sequence of characters as the content of the StringBuilder or StringBuffer.
  • You can construct a String by using the constructor shown here

Constructors

public String(StringBuffer strBufObj)

public String(StringBuilder strBuildObj)

 

Example

StringBuilder sb = new StringBuilder("Hello");
String str = new String(sb);
// Creates a string "Hello" from a StringBuilder

 

String Concatenation

  • The ‘+’ operator, which concatenates two strings, produces a String object as the result

Example

String myage = "21";
String s1 = "He is " + myage + " years old.";
System.out.println(s1); //"He is 21 years old."

 

String Concatenation with Other Data Types

int myage = 21;
String s1 = "He is " + myage + " years old.";
System.out.println(s1); //"He is 21 years old."

 

String s = "four: " + 2 + 2;
System.out.println(s); //four: 22
String s = "four: " + (2 + 2); //four: 4

 

toString( ) Method

  • In Java, the toString() method is a public method provided by the Object class, which is the superclass of all classes in Java.
  • Its primary purpose is to return a string representation of an object.
  • When you create a class in Java, it inherits the toString() method from the Object class.
  • This method can be overridden in any custom class to provide a meaningful string representation of an object, which can be particularly helpful for debugging or logging purposes.

 

Example 1: Without Using ‘toString()’ Method

package ch11.l2;

class Person{
	public String name;
	public int age;
	public String gender;
	
	public Person(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}	
}

public class ToStringExample {

	public static void main(String[] args) {
		Person p1=new Person("Amit", 27, "Male");
		Person p2=new Person("Riya", 23, "Female");
		System.out.println(p1);//compiler writes here p1.toString()
		System.out.println(p2);//compiler writes here p1.toString()
	}
}

Output

ch11.l2.Person@7cc355be
ch11.l2.Person@6e8cf4c6

 

Example 2: Adding ‘toString()’ Method in a Class

package ch11.l2;

class Person{
	public String name;
	public int age;
	public String gender;
	
	public Person(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", "
				+ "gender=" + gender + "]";
	}	
	
}

public class ToStringExample {

	public static void main(String[] args) {
		Person p1=new Person("Amit", 27, "Male");
		Person p2=new Person("Riya", 23, "Female");
		System.out.println(p1);//compiler writes here p1.toString()
		System.out.println(p2);//compiler writes here p1.toString()
	}
}

Output

Person [name=Amit, age=27, gender=Male]
Person [name=Riya, age=23, gender=Female]

 

Methods of String Class

Below is a summarized table of some commonly used String methods, categorized by their purpose with examples.

Method Description Example
charAt(int index) Returns the character at the specified index. String s = "example"; char c = s.charAt(2); // 'a'
compareTo(String anotherString) Compares two strings lexicographically. String s1 = "hello"; String s2 = "world"; int result = s1.compareTo(s2); // Negative value
concat(String str) Concatenates the specified string to the end of this string. String s1 = "hello "; String s2 = s1.concat("world"); // "hello world"
contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values. String s = "example"; boolean contains = s.contains("amp"); // true
endsWith(String suffix) Tests if this string ends with the specified suffix. String s = "example"; boolean endsWith = s.endsWith("ple"); // true
equals(Object anObject) Compares this string to the specified object. String s1 = "hello"; String s2 = "hello"; boolean equals = s1.equals(s2); // true
equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. String s1 = "Hello"; String s2 = "hello"; boolean equalsIgnoreCase = s1.equalsIgnoreCase(s2); // true
indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. String s = "example"; int index = s.indexOf('a'); // 2
isEmpty() Returns true if, and only if, length() is 0. String s = ""; boolean isEmpty = s.isEmpty(); // true
length() Returns the length of this string. String s = "example"; int length = s.length(); // 7
replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. String s = "example"; String replaced = s.replace('e', 'a'); // "axampla"
split(String regex) Splits this string around matches of the given regular expression. String s = "one,two,three"; String[] parts = s.split(","); // ["one", "two", "three"]
startsWith(String prefix) Tests if this string starts with the specified prefix. String s = "example"; boolean startsWith = s.startsWith("ex"); // true
substring(int beginIndex) Returns a new string that is a substring of this string. String s = "example"; String sub = s.substring(3); // "mple"
toCharArray() Converts this string to a new character array. String s = "example"; char[] chars = s.toCharArray(); // ['e', 'x', 'a', 'm', 'p', 'l', 'e']
toLowerCase() Converts all of the characters in this String to lower case. String s = "Example"; String lower = s.toLowerCase(); // "example"
toUpperCase() Converts all of the characters in this String to upper case. String s = "example"; String upper = s.toUpperCase(); // "EXAMPLE"
trim() Returns a string whose value is this string, with any leading and trailing whitespace removed. String s = " example "; String trimmed = s.trim(); // "example"

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

05/04/2025

Very well made pdf, easy to understand, got the concept in one reading

 

 

Submit a Review