You are on page 1of 10

String Class

Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.

String class definition:

public final class String


extends Object implements Serializable, Comparable<String>, CharSequence

All string literals in Java programs, such as “abc”, are implemented as instances of String
class.
The String class is immutable; so that once it is created a String object cannot be changed.
Whenever we change any string, a new instance is created. For mutable string, you can use
String Buffer and StringBuilder classes. If there is a necessity to make a lot of modifications to
Strings of characters, then you should use StringBuffer & StringBuilder Classes.

Example:

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};

String str = new String(data);


Here are some more examples of how strings can be used:

System.out.println("abc");

String cde = "cde";

System.out.println("abc" + cde);

String c = "abc".substring(2,3);

String d = cde.substring(1, 2);

Constructors in String class


The String class has 11 constructors that allow you to provide the initial value of the string
using different sources, such as an array of characters.

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };


String helloString= new String(helloString);
System.out.println(helloString);//hello
String Class Methods

Method Description
Int length() returns the number of characters contained in the string
object.
String concat() returns a new string that is string1 with string2 added to it
at the end.
Char charAt(int index) Returns the character at the specified index.
Boolean equals(Object Compares this string to the specified object.
obj)
boolean Compares this String to another String, ignoring case
equalsIgnoreCase(Str considerations.
ing anotherString)
String replace(char Returns a new string resulting from replacing all
oldChar, char occurrences of oldChar in this string with newChar.
newChar)
String[] split(String Splits this string around matches of the given regular
regex) expression.
String toLowerCase() Converts all of the characters in this String to lower case
using the rules of the default locale.
String toUpperCase() Converts all of the characters in this String to upper case
using the rules of the default locale.
String toString() This object (which is already a string!) is itself returned.
String trim() Returns a copy of the string, with leading and trailing
whitespace omitted.
static String Returns the string representation of the passed data type
valueOf(primitive argument.
data type x)
How to create String object?

There are two ways to create String


object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will return
the reference to the same instance.
Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).

Why string objects are immutable in java?

Because java uses the concept of string literals. Suppose there are 5 reference variable, all
refers to one object “opulent”. If one reference variable changes the value of the object, it will
be affected to all the reference variables. That is why string objects are immutable in java.

Java String Comparison

We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting(by compareTo() method),


reference matching (by == operator) etc.

There are three ways to compare string in java:

1.By equals() method

2.By = = operator

3.By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.

public boolean equalsIgnoreCase(String another) compares this String to another


string, ignoring case.

Example:

Class StringEqualCompare {
public static void main(String args[]){
String s1="Opulent";
String s2="Opulent ";
String s3=new String("Opulent ");
String s4="Tech";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

2) String compare by == operator

The = = operator compares references not values.

class StringAssinCompare{
public static void main(String args[]){
String s1=" Opulent ";
String s2=" Opulent ";
String s3=new String("Opulent ");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:

s1 == s2:0

s1 > s2 :positive value

s1 < s2 :negative value

Example:

class StringComtoCompare{
public static void main(String args[]){
String s1="Opulent";
String s2="Opulent ";
String s3="Tech";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//3(because s1>s3)
System.out.println(s3.compareTo(s1));//-3(becauses3 < s1)
}
}
String Concatenation in Java

In java, string concatenation forms a new string that is the combination of multiple strings.
There are two ways to concat string in java:

1.By + (string concatenation) operator

2.By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:

class StringConcatPlus{
public static void main(String args[]){
String s="Opulent "+"Tech";
System.out.println(s);//Opulent Tech
}
}

The Java compiler transforms above code to this:

1. String s=(new StringBuilder()).append("Opulent").append("Tech”).toString();

In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and its append method. String concatenation operator produces a new string by appending
the second operand onto the end of the first operand. The string concatenation operator can
concat not only string but primitive values also. For Example:

class StringConcatPlus2{

public static void main(String args[]){


String s=50+30+"Opulent"+40+40;
System.out.println(s);//80Opulent4040
}
}

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string.
Syntax:

public String concat(String another)


Let's see the example of String concat() method.

Class TestStringConcatenation{
public static void main(String args[]){
String s1="Opulent ";
String s2="Tech";
String s3=s1.concat(s2);
System.out.println(s3);//Opulent Tech
}
}

You might also like