12 String - Handling
12 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.
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.
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]);