0% found this document useful (0 votes)
26 views29 pages

Java String

1) In Java, a string is an object that represents a sequence of characters. Strings can be created using string literals or the new keyword. 2) Common string methods include compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. These methods allow operations like comparing, concatenating, and manipulating strings. 3) Strings are immutable in Java, meaning that once created a string cannot be modified, only new strings can be created from existing ones. This immutability allows strings to be used safely in multi-threaded applications and memory.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
26 views29 pages

Java String

1) In Java, a string is an object that represents a sequence of characters. Strings can be created using string literals or the new keyword. 2) Common string methods include compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. These methods allow operations like comparing, concatenating, and manipulating strings. 3) Strings are immutable in Java, meaning that once created a string cannot be modified, only new strings can be created from existing ones. This immutability allows strings to be used safely in multi-threaded applications and memory.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 29

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:
String s="javatpoint";
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.
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:
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:
3. String s1="Welcome";
4. String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as
the "string constant pool".
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

 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).
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
Java String class methods
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.
1.class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//
will print Sachin because strings are immutable objects
6. }
7.}
1. But if we explicitly assign it to the reference variable, it
will refer to "Sachin
Tendulkaclass 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
 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

 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:
• 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.
1.class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11.}
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.}
2) By Using == operator
The == operator compares references not values.

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 refers to instance created in nonpool)
8. }
9. }
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:

s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
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
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:
 String s=(new StringBuilder()).append("Sachin").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:
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:
 public String concat(String another)
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. }
 There are some other possible ways to concatenate Strings in Java,
 . 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.
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. }
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. }
3. String concatenation using String.join() method
 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.
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 store the result
9. System.out.println(s.toString()); //Displays result
10. }
Substring in Java
 You can get substring from the given String object by one of the two
methods:
1. public String substring(int startIndex):
This method returns new String object containing the substring of the given
string from specified startIndex (inclusive). The method throws an
IndexOutOfBoundException when the startIndex is larger than the length
of String or less than zero.
2. public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given
string from specified startIndex to endIndex. The method throws an
IndexOutOfBoundException when the startIndex is less than zero or
startIndex is greater than endIndex or endIndex is greater than length of
1. public class TestSubstring{
2. public static void main(String args[]){
3. String s="SachinTendulkar";
4. System.out.println("Original String: " + s);
5. System.out.println("Substring starting from index 6: " +s.substring(
6));//Tendulkar
6. System.out.println("Substring starting from index 0 to 6: "+s.substr
ing(0,6)); //Sachin
7. }
8. }
 The above Java programs, demonstrates variants of the substring() method of String class.
The startindex is inclusive and endindex is exclusive.
Using String.split() method:
 The split() method of String class can be used to extract a substring from a sentence. It accepts
arguments in the form of a regular expression.
1. import java.util.*;
2.
3. public class TestSubstring2
4. {
5. /* Driver Code */
6. public static void main(String args[])
7. {
8. String text= new String("Hello, My name is Sachin");
9. /* Splits the sentence by the delimeter passed as an argument */
10. String[] sentences = text.split("\\.");
11. System.out.println(Arrays.toString(sentences));
12. }
 In the above program, we have used the split() method. It accepts an argument \\. that
checks a in the sentence and splits the string into another string. It is stored in an array of
String objects sentences.

You might also like