Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views27 pages

Lesson 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 27

Java String

In Java, string is basically an object that


represents sequence of char values. An array of
characters works same as Java string. For
example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
2. Java String class provides a lot of methods
to perform operations on strings such as
compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
3. The java.lang.String class
implements Serializable, Comparable and CharS
equence interfaces.
CharSequence Interface
The CharSequence interface is used to represent
the sequence of characters.
String, StringBuffer and StringBuilder classes
implement it. It means, we can create strings in
Java by using these three classes.

The Java String is immutable which means it


cannot be changed. Whenever we change any
string, a new instance is created. For mutable
strings, you can use StringBuffer and StringBuilder
classes.

What is String in Java?


Generally, String is a sequence of characters.
But in Java, string is an object that represents a
sequence of characters. The java.lang.String
class is used to create a string object.
How to create a 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 the 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";//It doesn't create a new inst
ance
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
that is why it will create a new object. After that it
will find the string with the value "Welcome" in the
pool, it will not create a new object but will return
the reference to the same instance.
Why Java uses the concept of String
literal?
To make Java more memory efficient (because
no new objects are created if it exists already in
the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two
objects and one reference variable
In such case, JVM will create a new string object
in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the
object in a heap (non-pool).

Java String Example


1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java stri
ng literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char a
rray to string
6. String s3=new String("example");//creating J
ava string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
The above code, converts a char array into
a String object. And displays the String
objects s1, s2, and s3 on console
using println() method.
Java String class methods
The java.lang.String class provides many useful
methods to perform operations on sequence of
char values.

No Method Description
.

1 char charAt(int It returns char value for the


index) particular index

2 int length() It returns string length

3 static String It returns a formatted string.


format(String format,
Object... args)

4 static String It returns formatted string with


format(Locale l, given locale.
String format,
Object... args)

5 String substring(int It returns substring for given


beginIndex) begin index.

6 String substring(int It returns substring for given


beginIndex, int begin index and end index.
endIndex)

7 boolean It returns true or false afte


contains(CharSeque matching the sequence of cha
nce s) value.

8 static String It returns a joined string.


join(CharSequence
delimiter,
CharSequence...
elements)

9 static String It returns a joined string.


join(CharSequence
delimiter, Iterable<?
extends
CharSequence>
elements)

10 boolean It checks the equality of string


equals(Object with the given object.
another)

11 boolean isEmpty() It checks if string is empty.

12 String concat(String It concatenates the specified


str) string.
13 String replace(char It replaces all occurrences o
old, char new) the specified char value.

14 String It replaces all occurrences o


replace(CharSequen the specified CharSequence.
ce old,
CharSequence new)

15 static String It compares another string. I


equalsIgnoreCase(St doesn't check case.
ring another)

16 String[] split(String It returns a split string


regex) matching regex.

17 String[] split(String It returns a split string


regex, int limit) matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified cha


value index.

20 int indexOf(int ch, int It returns the specified cha


fromIndex) value index starting with given
index.

21 int indexOf(String It returns the specified


substring) substring index.

22 int indexOf(String It returns the specified


substring, int substring index starting with
fromIndex) given index.

23 String toLowerCase() It returns a string in lowercase.

24 String It returns a string in lowercase


toLowerCase(Locale using specified locale.
l)

25 String toUpperCase() It returns a string in uppercase.

26 String It returns a string in uppercase


toUpperCase(Locale using specified locale.
l)

27 String trim() It removes beginning and


ending spaces of this string.

28 static String It converts given type into


valueOf(int value) string. It is an overloaded
method.
Immutable String in Java
A String is an unavoidable type of variable while
writing any application program. String
references are used to store various attributes
like username, password, etc. In Java, String
objects are immutable. Immutable simply
means unmodifiable or unchangeable.
Once String object is created its data or state
can't be changed but a new String object is
created.
Let's try to understand the concept of
immutability by the example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method a
ppends the string at the end
5. System.out.println(s);//will print Sachin bec
ause strings are immutable objects
6. }
7. }
Now it can be understood by the diagram given
below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is
why String is known as immutable.
As you can see in the above figure that two
objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference
variable, it will refer to "Sachin Tendulkar"
object.
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
In such a case, s points to the "Sachin Tendulkar".
Please notice that still Sachin object is not
modified.
Why String objects are immutable in
Java?
As Java uses the concept of String literal.
Suppose there are 5 reference variables, all
refer to one object "Sachin". If one reference
variable changes the value of the object, it will
be affected by all the reference variables. That
is why String objects are immutable in Java.
Following are some features of String which
makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an
argument. Consider, if the String object is
modifiable, the value might be changed and the
class that is supposed to be loaded might be
different.
To avoid this kind of misinterpretation, String is
immutable.
2. Thread Safe:
As the String object is immutable we don't have
to take care of the synchronization that is
required while sharing an object across multiple
threads.
3. Security:
As we have seen in class loading, immutable
String objects avoid further errors by loading the
correct class. This leads to making the
application program more secure. Consider an
example of banking software. The username and
password cannot be modified by any intruder
because String objects are immutable. This can
make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the
usage in the heap memory. When we try to
declare a new String object, the JVM checks
whether the value already exists in the String
pool or not. If it exists, the same value is
assigned to the new object. This feature allows
Java to use the heap space efficiently.

Why String class is Final in Java?


The reason behind the String class being final is
because no one can override the methods of the
String class. So that it can provide the same
features to the new String objects as well as to
the old ones.
Java String compare

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 Using equals() Method
2.By Using == Operator
3.By compareTo() Method

1) By Using equals() Method


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

o class Teststringcomparison1{
o public static void main(String args[]){
o String s1="Sachin";
o String s2="Sachin";
o String s3=new String("Sachin");
o String s4="Saurav";
o System.out.println(s1.equals(s2));//true
o System.out.println(s1.equals(s3));//true
o System.out.println(s1.equals(s4));//false
o }
o }
In the above code, two strings are compared
using equals() method of String class. And the
result is printed as boolean
values, true or false.
Teststringcomparison2.java
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2
));//true
8. }
9. }
In the above program, the methods of String class
are used. The equals() method returns true if
String objects are matching and both strings are of
same case. equalsIgnoreCase() returns true
regardless of cases of strings.
2) By Using == operator
The == operator compares references not
values.
Teststringcomparison3.java
1.class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both
refer to same instance)
7. System.out.println(s1==s3);//false(because s3 re
fers to instance created in nonpool)
8. }
9.}

3) String compare by compareTo()


method
The above code, demonstrates the use
of == operator used for comparing
two String objects.
3) By Using compareTo() method
The String class 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 objects. If:
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative
value.
Teststringcomparison4.java
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//
1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-
1(because s3 < s1 )
9. }
10. }
String Concatenation in Java
In Java, String concatenation forms a new String
that is the combination of multiple strings. There
are two ways to concatenate strings 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:
TestStringConcatenation1.java
1.class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6.}
The Java compiler transforms above code to
this:
1. String s=(new StringBuilder()).append("Sac
hin").append(" Tendulkar).toString();
In Java, String concatenation is implemented
through the StringBuilder (or StringBuffer) class
and it's 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
concatenate not only String but primitive values
also. For Example:
TestStringConcatenation2.java
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }

2) String Concatenation by concat()


method
The String concat() method concatenates the
specified string to the end of current string.
Syntax:
1.public String concat(String another)
Let's see the example of String concat() method.
TestStringConcatenation3.java
1.class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8.}

The above Java program, concatenates two


String objects s1 and s2 using concat() method
and stores the result into s3 object.
There are some other possible ways to
concatenate Strings in Java,

1. String concatenation using


StringBuilder class
StringBuilder is class provides append() method
to perform concatenation operation. The
append() method accepts arguments of different
types like Objects, StringBuilder, int, char,
CharSequence, boolean, float, double.
StringBuilder is the most popular and fastet way
to concatenate strings in Java. It is mutable class
which means values stored in StringBuilder
objects can be updated or changed.
StrBuilder.java
1.public class StrBuilder
2.{
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. StringBuilder s1 = new StringBuilder("Hello");
//String 1
7. StringBuilder s2 = new StringBuilder(" World"
); //String 2
8. StringBuilder s = s1.append(s2); //String 3 to
store the result
9. System.out.println(s.toString()); //Displays
result
10. }
11. }

In the above code snippet, s1, s2 and s are


declared as objects
of StringBuilder class. s stores the result of
concatenation of s1 and s2 using append()
method.
2. String concatenation using format()
method
String.format() method allows to concatenate
multiple strings using format specifier like %s
followed by the string values or objects.
1. public class StrFormat
2. {
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //
String 1
7. String s2 = new String(" World"); //
String 2
8. String s = String.format("%s%s",s1,s2);
//String 3 to store the result
9. System.out.println(s.toString()); //
Displays result
10. }
11. }
Here, the String objects s is assigned the
concatenated result of
Strings s1 and s2 using String.format() metho
d. format() accepts parameters as format
specifier followed by String objects or values.

3. String concatenation using String.join()


method (Java Version 8+)
The String.join() method is available in Java
version 8 and all the above versions.
String.join() method accepts arguments first a
separator and an array of String objects.
StrJoin.java:
1.public class StrJoin
2.{
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.join("",s1,s2); //String 3 to s
tore the result
9. System.out.println(s.toString()); //Displays
result
10. }
11. }

You might also like