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

12 String - Handling

String is an immutable object in Java. When concatenating strings or modifying a string value, new String objects are created in memory rather than modifying the original object. The String class provides many useful methods for working with and manipulating string values, such as charAt(), concat(), equals(), length(), replace(), substring(), toLowerCase(), and split(). String objects are stored in the String constant pool to improve memory efficiency when multiple references refer to the same literal value.

Uploaded by

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

12 String - Handling

String is an immutable object in Java. When concatenating strings or modifying a string value, new String objects are created in memory rather than modifying the original object. The String class provides many useful methods for working with and manipulating string values, such as charAt(), concat(), equals(), length(), replace(), substring(), toLowerCase(), and split(). String objects are stored in the String constant pool to improve memory efficiency when multiple references refer to the same literal value.

Uploaded by

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

String Handling

String is a 16-bit Unicode character In Java, strings are objects. Just like other objects, you can create an
instance of a String with the new keyword, as follows:
String s = new String();

Note:- String object is immutable(unchangable), its reference variable is not. String is final class in java
so you can not extends its functionality.
class Test extends String{} // compiler error Reason:-String is final class not able to extends.
Once you have assigned a String a value, that value can never change— it's immutable.

String class has about a zillion constructors, so you can use a more efficient shortcut:
String s = new String(“hello");
And just using string literal:
String s = “hello";
There are some subtle differences between these options discuss later.

Assign reference variable s to s2.


String s2 = s; // refer s2 to the same String as s
String is immutable object so what happened with the following:-
String s=“Hello”;
s=s+” Java”;
System.out.println(s); // output:- Hello Java.
There are created three objects into the memory.
1. An object with value “Hello” that assigned to reference variable s.
2. An object with value “ Java” that not assigned to any reference variable.
3. An object with value “Hello Java” that assigned to reference variable s. Now s refer to “Hello Java” its
previous reference with object(“Hello”) has been lost.

Note:- However, that the original “Hello" String didn't change (it can't, remember, it's immutable); only
the reference variable s was changed, so that it would refer to a different String.

Strings and Memory:-


One of the key goals of any good programming language is to make efficient use of memory. As
applications grow, it's very common for String literals to occupy large amounts of a program's
memory, and there is often a lot of redundancy within the universe of String literals for a program.
To make Java more memory efficient, the JVM sets aside a special area of memory called the "String
constant pool." When the JVM encounters a String literal, it checks the pool to see if an identical
String already exists. If a match is found, the reference to the new literal is directed to the
existing String, and no new String literal object is created.
Why making String objects immutable:-
If several reference variables refer to the same String without even knowing it, it would be very bad if any
of them could change the String's value.
Example:-
String s1=“Hello”;
String s2=s1;
There is only one object created into string constant pool and both reference variables s1 and
s2 refer to same object “Hello”.
If s1 changes the object’s value as s1=“Hi” so it is very bad s2 also will get “Hi” instead “Hello”.
So that string object is immutable. Once a string object created it can not be change.

Creating New Strings:-


String s = "abc"; // creates one String object and one
// reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,
// and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
public class ImmutableStrings
{
public static void main(String[] args)
{
String one = “hello";
String two = “hello";
System.out.println(one.equals(two));
System.out.println(one == two);
}
}

Note:- The equals() method checks to see if the String objects contain the same data (“hello"), the ==
operator, when used on objects, checks for referential equality - that means that it will return true if
and only if the two reference variables refer to the exact same object.

Constructing Strings using the "new" keyword implies a different sort of behaviour. Let's look at an
example:
public class ImmutableStrings
{
public static void main(String[] args)
{
String one = “hello";
String two = new String(“hello“);
System.out.println(one.equals(two));
System.out.println(one == two);
}
}
In such a case,two references to the same String literal are still put into the constant table
(the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged
to create a new String object at run-time, rather than using the one from the constant
table.
Output :- true and false.
In such a case, although the two String references refer to String objects that contain the
same data, “hello", but they do not refer to the same object. That can be seen from the
output of the program. While the equals() method returns true, the == operator, which
checks for referential equality, returns false.
Note:- If you'd like to get both of these local variables to refer to the same object, you can
use the intern() method defined in String.
System.out.println(one == two.intern());
public class InternDemo{
public static void main(String[] args) {
String s1=new String(“hello");
String s2=“hello”;
//Without intern one object from pool and another from heap so s1 and s2 refers to
the different objects.
System.out.println( s1== s2);
//With intern using one object from pool so s1 and s2 refers to the same object.
System.out.println( s2== s1.intern()); }}
Methods in the String Class:-
There are many methods in string class here we are going to discuss only some of more
commonly used methods in the String class.
■ charAt(int index) Returns the character located at the specified index.
Ex:- System.out.println("hello".charAt(0)); // output h.
What happened with: System.out.println("hello".charAt(8));
//Runtime Error:- java.lang.StringIndexOutOfBoundsException: String index out of range: 8

■ concat() Appends one String to the end of another ( "+" also works)
Ex:- String s="Billo"; System.out.println(s.concat(" Rani")); //output Billo Rani
Same with “+” operator System.out.println(s+" Rani")); //output Billo Rani

Think output:-
String s="Billo"; s.concat(“Barbar”); System.out.println(s);
■ public boolean equalsIgnoreCase(String anotherString) Determines the equality of two Strings,
ignoring case
■public int length() Returns the number of characters in a String
■public String replace(char oldChar, char newChar).
String s="Billo"; System.out.println(s.replace('B', 'D'));
 public int indexOf(int ch): Returns the index within this string of the first occurrence of the
specified character or -1 if the character does not occur.
 public int indexOf(int ch, int fromIndex): Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index or -1 if the character
does not occur.
 int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring. If it does not occur as a substring, -1 is returned.
 int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence
of the specified substring, starting at the specified index. If it does not occur, -1 is returned.
String s="Billo";
System.out.println(s.indexOf('l'));
System.out.println(s.indexOf('l',3));
System.out.println(s.indexOf('l',4));
System.out.println(s.indexOf("llt"));

 int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified
character or -1 if the character does not occur.
 public int lastIndexOf(int ch, int fromIndex): Returns the index of the last occurrence of the
character in the character sequence represented by this object that is less than or equal to fromIndex,
or -1 if the character does not occur before that point.
 public int lastIndexOf(String str): If the string argument occurs one or more times as a substring
within this object, then it returns the index of the first character of the last such substring is
returned. If it does not occur as a substring, -1 is returned.
 public int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the specified index.
■ public String substring(int beginIndex) or
public String substring(int beginIndex, int endIndex)
String Str = new String("Welcome to Sahidirection.com");
System.out.println(Str.substring(10) ); //output:- Sahidirection.com
System.out.println(Str.substring(10, 24) ); //output:- Sahidirection
■ toLowerCase() Returns a String with uppercase characters converted.
■ toUpperCase() Returns a String with lowercase characters converted.
■ toString() Returns the value of a String.
■ trim() Removes whitespace from the ends of a String.
■ char[] toCharArray() Converts string to a new character array.
 String Str = new String("Welcome to Sahidirection.com");
 char[] ch=Str.toCharArray();
 System.out.println(ch[0]);
■ public boolean startsWith(String prefix, int indexToStart) or public boolean startsWith(String
prefix)
String Str = new String(" Welcome to Sahidirection.com");
System.out.println(Str.startsWith("Welcome") ); // true
System.out.println(Str.startsWith("Tutorials") ); // false
■ public boolean endsWith(String suffix).
 String Str = new String("Welcome to Sahidirection.com");
 System.out.println(Str.endsWith(".com"));// true
public String[] split(String regex, int limit) or public String[] split(String regex)
 String Str = new String("Welcome-to-Sahidirection.com");
 String[] arr=Str.split("-", 2);
 System.out.println(arr[0]);
 System.out.println(arr[1]);

The StringBuffer and StringBuilder Classes


The java.lang.StringBuffer and java.lang.StringBuilder classes should be used when you have to make a
lot of modifications to strings of characters.
String x = "abc"; x = x.concat("def"); System.out.println("x = " + x); // output is "x = abcdef"
We got a nice new String out of the deal, but the downside is that the old String
"abc" has been lost in the String pool, thus wasting memory. If we were using a
StringBuffer instead of a String, the code would look like this:
StringBuffer sb = new StringBuffer("abc");
sb.append("def");
System.out.println("sb = " + sb); // output is "sb = abcdef“
 StringBuffer vs. StringBuilder
The StringBuilder class was added in Java 5. It has exactly the same API as the
StringBuffer class, except StringBuilder is not thread safe. In other words, its
methods are not synchronized. You should use StringBuilder instead of StringBuffer whenever possible
because StringBuilder will run faster.
Thanks

You might also like