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

Introduction To Java String Handling - Class - 10

String is the most commonly used class in Java and represents sequences of characters. A String object is immutable, meaning its value cannot be changed after it is created. Strings can be created using string literals, by concatenating other strings, or by constructing a new String object. The String class provides many useful methods for working with and comparing string values.

Uploaded by

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

Introduction To Java String Handling - Class - 10

String is the most commonly used class in Java and represents sequences of characters. A String object is immutable, meaning its value cannot be changed after it is created. Strings can be created using string literals, by concatenating other strings, or by constructing a new String object. The String class provides many useful methods for working with and comparing string values.

Uploaded by

bahbah27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to Java String Handling

String is probably the most commonly used class in java library. String class is encapsulated under java.lang
package. In java, every string that you create is actually an object of type String. One important thing to notice
about string object is that string objects are immutable that means once a string object is created it cannot be
altered. In Java, java.lang.String class is implementes using Serializable, Comparable and CharSequence
interface.

In Java, CharSequence Interface is used for representing a sequence of characters. CharSequence interface is
implemented by String, StringBuffer and StringBuilder classes. This three classes can be used for creating
strings in java.

What is an Immutable object?


An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer,
Byte, Short, Float, Double and all other wrapper classes objects are immutable.
Creating an Immutable class
public final class MyString
{
final String str;
MyString(String s)
{
this.str = s;
}

public String get()


{
return str;
}
}
In this example MyString is an immutable class. MyString's state cannot be changed once it is created.
Creating a String object
String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.
String str1 = "Hello";
2) Using another String object
String str2 = new String(str1);
3) Using new Keyword
String str3 = new String("Java");
4) Using + operator (Concatenation)
String str4 = str1 + str2;
or,
String str5 = "hello"+"Java";
Each time you create a String literal, the JVM checks the string pool first. If the string literal already exists in
the pool, a reference to the pool instance is returned. If string does not exist in the pool, a new string object is
created, and is placed in the pool. String objects are stored in a special memory area known as string constant
pool inside the heap memory.
Concatenating String
There are 2 methods to concatenate two or more string.
1. Using concat() method
2. Using + operator
1) Using concat() method
string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java"); //works with string literals too.
2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";
String Comparison
String comparison can be done in 3 ways.
1. Using equals() method
2. Using == operator
3. By CompareTo() method
Using equals() method
equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false
Using == operator
== operator compares two object references to check whether they refer to same instance. This also, will return
true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(s1 == s2) //true
test(s1 == s3) //false
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less than, equal to
or greater than the other string. It compares the String based on natural ordering i.e alphabetically. Its general
syntax is,
int compareTo(String str)
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1
Java String class functions
The methods specified below are some of the most commonly used methods of the String class in Java. We will
learn about each method with help of small code examples for better understanding.
charAt() method
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String str.
equalsIgnoreCase() method
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case doesn't
matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output: true
indexOf() method
indexOf() function returns the index of first occurrence of a substring or a character. indexOf() method has four
forms:
 int indexOf(String str): It returns the index within this string of the first occurrence of the specified
substring.
 int indexOf(int ch, int fromIndex): It returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
 int indexOf(int ch): It returns the index within this string of the first occurrence of the specified
character.
 int indexOf(String str, int fromIndex): It returns the index within this string of the first occurrence of
the specified substring, starting at the specified index.
Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
System.out.println(str.indexOf('u')); //3rd form
System.out.println(str.indexOf('t', 3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //1st form
System.out.println(str.indexOf(subString,7)); //4th form
}
}
Java String class functions
The methods specified below are some of the most commonly used methods of the String class in Java. We will
learn about each method with help of small code examples for better understanding.
charAt() method
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output: u
equalsIgnoreCase() method
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case doesn't
matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output: true
indexOf() method
indexOf() function returns the index of first occurrence of a substring or a character. indexOf() method has four
forms:

 int indexOf(String str): It returns the index within this string of the first occurrence of the specified
substring.
 int indexOf(int ch, int fromIndex): It returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
 int indexOf(int ch): It returns the index within this string of the first occurrence of the specified
character.
 int indexOf(String str, int fromIndex): It returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.

Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
System.out.println(str.indexOf('u')); //3rd form
System.out.println(str.indexOf('t', 3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //1st form
System.out.println(str.indexOf(subString,7)); //4th form
}
}
length() method
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
8
replace() method
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output: Change Me
substring() method
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
public String substring(int begin, int end);
/*
character of begin index is inclusive and character of end index is exclusive.
*/
The first argument represents the starting point of the subtring. If the substring() method is called with only one
argument, the subtring returned, will contain characters from specified starting point to the end of original
string.But, if the call to substring() method has two arguments, the second argument specify the end point of
substring.
String str = "0123456789";
System.out.println(str.substring(4));
456789
System.out.println(str.substring(4,7));
Output:456
toLowerCase() method
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output:abcdef
toUpperCase() method
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output:ABCDEF
trim() method
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());
Output:hello
NOTE: If the whitespaces are between the string, for example: String s1 = "study tonight"; then
System.out.println(s1.trim()); will output "study tonight".
trim() method removes only the leading and trailing whitespaces.
Extra note:
format() Method
format() is a string method. It is used to the format of the given string.
Following are the format specifier and their datatype:
Format Specifier Datatype
%a floating point
%b Any type
%c character
%d integer
%e floating point
%f floating point
%g floating point
%h any type
%n none
%o integer
%s any type
%t Date/Time
%x integer

public class FormatDemo1


{
public static void main(String[] args)
{
String a1 = String.format("%d", 125);
String a2 = String.format("%s", "studytonight");
String a3 = String.format("%f", 125.00);
String a4 = String.format("%x", 125);
String a5 = String.format("%c", 'a');
System.out.println("Integer Value: "+a1);
System.out.println("String Value: "+a2);
System.out.println("Float Value: "+a3);
System.out.println("Hexadecimal Value: "+a4);
System.out.println("Char Value: "+a5); }}

You might also like