0% found this document useful (0 votes)
44 views

Unit-I - 4 String

A string is a sequence of characters that exists as an object of the class java.lang.String. Strings can be constructed using string literals or via the new keyword. Strings are immutable, and common methods allow accessing characters, concatenating, and comparing strings.

Uploaded by

Mochi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Unit-I - 4 String

A string is a sequence of characters that exists as an object of the class java.lang.String. Strings can be constructed using string literals or via the new keyword. Strings are immutable, and common methods allow accessing characters, concatenating, and comparing strings.

Uploaded by

Mochi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

String In Java

What is String?
• A string is sequence of characters.
• string is a sequence of characters that exists as an object of the
class java.lang.
• A string class is a user-defined template for creating and
manipulating string objects, which are sequences of characters
• Java strings are created and manipulated through the string
class.
• A String can be constructed by either:
• a string literal
• via the "new" keyword
String str1 = "Java is easiest language";
String str2 = new String("I'm cool");
•In the first statement, str1 is declared as a String reference and initialized with a
string literal "Java is easiest programming language". In the second
statement, str2 is declared as a String reference and initialized via
the new operator and constructor to contain "I'm cool".

•String literals are stored in a common pool. This facilitates sharing of storage for
strings with the same contents to conserve storage. String objects allocated
via new operator are stored in the heap, and there is no sharing of storage for the
same contents.
String Literal vs. String Object
• there are two ways to construct a string: implicit construction by
assigning a string literal or explicitly creating a String object via the
new operator and constructor.

String s1 = "Hello"; // String literal


String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
Java has provided a special mechanism for keeping the String literals - in a so-
called string common pool.
If two string literals have the same contents, they will share the same storage
inside the common pool. This approach is adopted to conserve storage for
frequently-used strings.
On the other hand, String objects created via the new operator and
constructor are kept in the heap. Each String object in the heap has its own
storage just like any other object. There is no sharing of storage in heap even if
two String objects have the same contents.
You can use the method equals() of the String class to compare the contents
of two Strings. You can use the relational equality operator '==' to compare
the references (or pointers) of two objects. Study the following codes:
s1 == s1; // true, same pointer
s1 == s2; // true, s1 and s1 share storage in common pool
s1 == s3; // true, s3 is assigned same pointer as s1
s1.equals(s3); // true, same contents
s1 == s4; // false, different pointers
s1.equals(s4); // true, same contents
s4 == s5; // false, different pointers in heap
s4.equals(s5); // true, same contents
String is Immutable

• The meaning of immutable is unchangeable or unmodifiable. That is, once


we create a string object with value, we are not allowed to perform any
changes in that object.

• Java implements this immutability concept to minimize the duplication of


string values that tend to exist many times in any application program.

• Java enhances the reliability of code and simplifies memory management.


public class ImmutabilityTest
{
public static void main(String[] args)
{ // Creating a sting literal object with
content.
String s = "hello";
// Calling concat() method to add string at
the end.
s.concat("world");
System.out.println(s); // It will print "hello"
because string is an immutable object.
}
}
When JVM will execute statement String s = “hello”;, it will create a string object in the string constant pool
and store “hello” in it.

When the next statement s.concat(“world”); will be executed by JVM, it will create two new objects
because we are trying to modify the original content.

1. First, for every string literal “world”, JVM will create one copy of string object in the string constant pool.

2. The second object will be created in the heap with modified content “hello world”. Since string
concatenation is executed at the runtime. Therefore, if a new object is required to create, this new object is
always created in the heap area only, not in the string constant pool.

Since this new object is not assigning with any reference variable, therefore, it is called unreferenced object
and the garbage collector will automatically remove it from the memory.

Thus, the value of string s is not modified and still, ‘s’ is pointing to “hello” only. Therefore, the result is
“hello”. This is the reason, string objects are called immutable in Java.
String Methods
int length() method
• The length() method returns the length of the String that is, the
number of characters in a String.

public class LengthOfString


• Syntax:
{
public static void main(String args[])
stringName.length( ) ; {
String str = "This is a Tutorial on Strings";
int len = str.length();
System.out.println( "Length of sentence is : " +
len );
}
}
char charAt(int index) method
• return a character value at a specified position (index) of a String.

public class string_charAt


• Syntax: {
stringName.charAt( index ) ; public static void main(String args[])
{
String str = "This is a Tutorial on Strings";
char result = str.charAt(11);
System.out.println("At position 8, the character is: "
+result);
System.out.println("At position 1, the character is: "
+str.charAt(1));
}
}
String concat(String string1) method
• concatenating or adding two strings into a single string.
• This method appends its String argument to the indicated string
argument and returns a new instance of the String class.
public class StringConcatenation
{
string1.concat(string2); public static void main(String args[])
{
String string1 = “Tutorial on";
String string2 = "Java String";
string1 = string1.concat(string2);
System.out.println("Concatenated String is: " +string1);
}
String substring(int beginIndex) method
• The substring method with a single argument is used to create new
objects or instances of String class from existing instances of String.
• The method returns the substring from the index which is passed as
an argument to the method.
public class SubStrings
• Syntax: {
string.substring(beginIndex) ; public static void main(String args[])
{
String sentence = "Welcome to Tutorial on
Strings";
String subString = sentence.substring(11);
System.out.println( "The Substring is: "
+subString) ;
}
}
String substring(int beginIndex, int endIndex)
method
• The substring with two arguments method is used to create new
objects or instances of String class from existing instances of String.
• The method returns the new String by using the required index range
(including the start index and excluding the end index).
• Syntax:
sentence.substring(beginIndex, endIndex) ;
public class SubStrings
{
public static void main(String args[])
{
String sentence = "Welcome to Tutorial on Strings";
String subString1 = sentence.substring(11, 21);
String subString2 = sentence.substring(22, 30);
System.out.println("The Substring within the range is: " + subString1);
System.out.println("The Substring within the range is: " + subString2);
}
}
int compareTo(String string1, String string2)
method
• the method returns an integer which indicates the lexicographic
(alphabetical) comparison of the two strings.
• The result is negative if the relative alphabetic value of the particular letter of
the first string is smaller than that of the second string’s letter on the same
location.
• And it is positive if the first string is lexicographically larger than the second
string.
• If both strings are identical, then a value zero(0) is returned.
Syntax:
string1.compareTo(string2) ;
public class CompareStrings
String sentence1 = "This is a ";
{
String sentence2 = "Java Tutorial ";
public static void main(String args[]) /*result = sentence1.compareTo(sentence2);
{ System.out.println(result);*/
String string1 = "Hello World"; if (sentence1.compareTo(sentence2)!=0) {
String string2 = "Hello World"; System.out.println(sentence1 + " " +
int result = string1.compareTo(string2); sentence2
System.out.println(result); + " : Not Equal");
}
else {
String sentence = "Welcome ";
System.out.println(sentence1 + " " +
result = sentence.compareTo("to
sentence2
TechVidvan Tutorial "); + " : Equal");
System.out.println(result); }
}
}
Why not use == for the comparison of Strings?
• In general, both equals() and “==” operators in Java are used to
compare objects to check equality but here are some of the
differences between the two:
• The main difference between the .equals() method and == operator is
that one is the method and the other is the operator.
• One can use == operators for reference comparison (address
comparison) and the .equals() method for content comparison.
• Both s1 and s2 refer to different objects.
• When one uses == operator for the s1 and s2 comparison then the
result is false as both have different addresses in memory.
• Using equals, the result is true because it’s only comparing the values
given in s1 and s2.
String toUpperCase() method
• converts all the characters of a given string to uppercase.
• Syntax:
sentence.toUpperCase() ; public class CaseConversion
{
public static void main(String args[])
{
String string1 = "Hello World";
String string2 = "welcome to Java Tutorial ";
System.out.println(string1.toUpperCase());
System.out.println(string2.toUpperCase());
}
}
String toLowerCase() method
• converts all the characters of a given string to lowercase.
• Syntax: public class CaseConversion
sentence.toLowerCase() ; {
public static void main(String args[])
{
String string1 = "HELLO WORLD";
String string2 = "WELCOME TO JAVA
TUTORIAL";
System.out.println(string1.toLowerCase());
System.out.println(string2.toLowerCase());
}
}
String trim() method
• This method returns the new String after removing whitespaces at
both ends. It does not affect whitespaces in the middle of the String.
• Syntax:
public class TrimString
sentence.trim() ;
{
public static void main(String args[])
{
String string1 = " This is a Tutorial on Strings ";
System.out.println("The original string is:" +string1);
System.out.println("The trimmed string is:"
+string1.trim());
}
}
String replace(char oldChar, char
newChar)
• This method replaces each occurrence of the first argument of the
string with the second argument and returns the resulting string.
• Syntax: public class ReplaceString
{
sentence.replace(char1, char2) ; public static void main(String args[])
{
//Replacing all the 'a' with 'e'
String string1="TechVidvan is a good tutorial";
String replaceString=string1.replace('a','e');
//replaces all occurrences of 'a' to 'e'
System.out.println("String after replacing characters is:
+replaceString);

}
}

You might also like