String handling
String is an object that represents a sequence of characters. string objects are
immutable. Immutable simply means unmodifiable or unchangeable.Once string object
is created its data or state can't be changed .
String constant :it is created by using double quotes. For Example: “basic”, “a”, “880”
String Variable : variable which store the value of string constant.
String Var_name;
String str=”Basic”;
StringBuffer -:Java StringBuffer class is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
length() Method :- length() method is used to find out the length of a String. This
method counts the number of characters in a String including the white .
syntax : int length()
This method returns an integer number which represents the number of characters
(length) in a given string including white spaces.
String str1= "Test String";
System.out.println("Length of str1:"+str1.length());
Output: Length of str1:11
charAt() Method : - charAt() method returns the character at the specified index
in a string. The index should be between 0 and (length of string-1). For example:
s.charAt(0) would return the first character of the string s.
Syntax : char charAt(int index)
String str = "Welcome";
char ch1 = str.charAt(0);
//This will return the first char W of the string
char ch2 = str.charAt(5);
//This will return the 6th char m of the string
charAt() example to print all characters of string in new line
To print all the characters of a string, we are running a for loop from 0 to length of
string – 1 and displaying the character at each iteration of the loop using the charAt()
method.
public class JavaExample {
public static void main(String args[]) {
String str = "Program";
int len=str.length();
for(int i=0; i<=len-1; i++)
{
Char ch=str.chatAt(i);
System.out.println(ch);
}
}
}
charAt() example to count the number of blank spaces in the string
public class JavaExample {
public static void main(String[] args) {
String str = "god is only one";
//initialized the counter to 0
int counter = 0;
int len=str.length();
for (int i=0; i<=str.len-1; i++) {
char ch=str.charAt(i);
if(ch== ' ') {
//increasing the counter value at each occurrence of ' '
counter++;
}
}
System.out.println("Char space occurred "+counter+" times");
}
}
Output is : Char space occurred 3 times
equals() and equalsIgnoreCase() Methods :-
equals() and equalsIgnoreCase() methods are used for comparing equality of two
strings and return boolean value true or false.
Syntax:
boolean equals(String str): Case sensitive comparison(case and content both)
boolean equalsIgnoreCase(String str): Case in-sensitive comparison(only content)
For e.g. The equals() method would return false if we compare the strings “TEXT” and
“text” however equalsIgnoreCase() would return true.
String str1= "Hello";
String str2= "Hi";
String str3= "Hello";
System.out.println("str1 equals to str2:"+str1.equals(str2));
System.out.println("str1 equals to str3:"+str1.equals(str3));
System.out.println("str1 equals to HELLO:"+str1.equalsIgnoreCase("HELLO"));
System.out.println("str1 equals to str2:"+str1.equalsIgnoreCase(str2));
Output: str1 equals to str2:false
str1 equals to str3:true
str1 equals to HELLO:true
str1 equals to str2:false
Program to check a string is palindrome string or not
public class JavaExample{
public static void main(String args[]){
String str = "madam",t = ““;
int len=str.length(); //find length of the string
for (int i=len-1; i>=0; i--)
{
char ch=str.charAt(i); // reverse the string
t=t+ch;
}
if(str.equalsIgnoreCase(t)==true)
System.out.println("Palindrome String”);
else
System.out.println("Not a Palindrome String”);
}
}
toLowerCase() method :- The String toLowerCase() method returns the string in
lowercase letter. it converts all characters of the string into lower case letter.
String str = “BaSIc”;
String t = str.toLowerCase();
System.out.println(t); //output is : basic
toUpperCase() method :- The java String toUpperCase() method returns the string
in uppercase letter. it converts all characters of the string into upper case letter.
String str = “BaSIc”;
String t = str.toUpperCase();
System.out.println(t); //output is : BASIC
trim() method :- The java String trim() method eliminates leading and trailing
spaces and returns the string.
String str=” My Program “;
String t = str.trim();
System.out.println(t); //output is : My Program
concat() method :- The java String concat(String s) method combines specified
string at the end of this string. It returns combined string.
String str1 = “Basic”;
String str2 = “java”
String t = str1.concat(str2);
System.out.println(t); //output is : Basicjava
compareTo() Method :- This method is used for comparing two strings
lexicographically(alphabetically) and return a integer value . Each character of both the
strings is converted into a Unicode value for comparison. It return 0 if both the strings
are equal .it return positive value if the first string is lexicographically greater than the
second string else it return negative value.
If there is no index position at which they differ, then the shorter string
lexicographically precedes the longer string. In this case, it returns the difference of the
lengths of the strings. For example, System.out.println("AB".compareTo("ABCD")); will
display –2
Syntax : int compareTo(String s)
String str1 = "Cable";
String str2 = "Cadet";
String str3 = "Cable";
int var1 = str1.compareTo( str2 );
System.out.println("str1 & str2 comparison: "+var1);
int var2 = str1.compareTo( str3 );
System.out.println("str1 & str3 comparison: "+var2);
Output:
str1 & str2 comparison: -2
str1 & str3 comparison: 0
compareTo() method is case sensitive. However we do have a case insensitive
compare method in string class, which is compareToIgnoreCase(), this method
ignores the case while comparing two strings.
startsWith() Method :- The startsWith(String prefix) method is used for checking
prefix of a String. It returns a boolean value true or false based on whether the given
string begins with the specified letter or word.
String str = "Hello world";
boolan b=str.startsWith("He");
//This will return true because string str starts with "He"
endsWith() Method :- endsWith(String suffix) method checks whether
the String ends with a specified suffix. This method returns a boolean value true or
false. If the specified suffix is found at the end of the string then it returns true else it
returns false.
String str = "Hello java world";
boolan b=str.endWith("rld");
//return true because string str end with "rld"
indexOf() / lastIndexOf() Method :-
int indexOf(char ch) : It returns the index of the first occurrence of character ch in a
given String. It return -1 if char is not present in the string.
int indexOf(chart ch, int fromIndex) : It returns the index of first occurrence of
character ch in the given string after the specified index “fromIndex”. For example,
str.indexOf(‘A’, 20) then it would start looking for the character ‘A’ in string str after the
index 20.
int lastIndexOf(char ch) method : is used to find the last index of a specified
character ch in a given String. It return -1 if char is not present in the string.
int lastIndexOf(int ch, int fromIndex): It returns the last occurrence of ch, it
starts looking backwards from the specified index “fromIndex”.
String str1 = "programs";
int a= str.indexOf(‘g’); //return 3
int a= str.indexOf(‘r’); //return 1
int a= str.indexOf(‘t’); //return -1
int b = str1.indexOf('r',2); // return 4 index of r after 3 char
int a= str.lastIndexOf(‘g’); //return 3
int a= str.lastIndexOf(‘r’); //return 4
int a= str.lastIndexOf(‘t’); //return -1
substring() Method :- substring() returns a new string that is a substring of given
string. There are two variants of this method.
1-When we pass only the starting index:
String substring(int beginIndex)
Returns the substring starting from the specified index i.e beginIndex to the end of the
string. For example – "Programs".substring(2) would return "ograms". The beginIndex
is inclusive.
2-When we pass both the indexes, starting index and end index:
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the
specified beginIndex and extends to the character at index endIndex – 1. In other
words you can say that beginIndex is inclusive and endIndex is exclusive while getting
the substring.
For example – "Programs".substring(2,6) would return "ogra".
substring() example :
. String str= “god is one ";
String t= str.substring(4,6);
System.out.println(t); // output is : is
String p= str.substring(7);
System.out.println(p)); // output is : one
replace() method :- String replace(char oldChar, char newChar): It replaces all
the occurrences of a oldChar character with newChar character. For e.g. "pog
pance".replace('p', 'd') would return dog dance.
String str = “programs";
System.out.print("String after replacing all 'r' with 'x' :" );
String t= str.replace('r', 'p');
System.out.println(t); // Output : pxogxams
valueOf() method :- String valueOf() method returns the String representation of
the boolean, char, char array, int, long, float and double arguments. We have different
versions of this method for each type of arguments .
Syntax :
public static String valueOf(data_type var): data type to String
String valueOf() Example :
Lets take an example, where we are using all the variants of valueOf() method. In this
example we are using valueOf() method to convert the integer, float, long, double, char
and char array to the String.
int i = 10; //int value
float f = 10.10f; //float value
long l = 111L; //long value
double d = 2222.22; //double value
char ch = 'A'; //char value
char array[] = {'a', 'b', 'c'}; //char array
//converting int to String
String str1 = String.valueOf(i);
//converting float to String
String str2 = String.valueOf(f);
//converting long to String
String str3 = String.valueOf(l);
//converting double to String
String str4 = String.valueOf(d);
//converting char to String
String str5 = String.valueOf(ch);
//converting char array to String
String str6 = String.valueOf(array);
Convert String to primitive datatype :-
Two ways to convert String to primitive data type.
1. Java – Convert String to primitive data(int, float ,double) using
parseDatatype(String) method
1- A Integer.parseInt(String) convert String to int type.
1- B Float.parseFloat(String) convert String to float type.
1- C Double.parseDouble(String) convert String to double type.
String str = "1234",str1 = “14.48”;
int inum = Integer.parseInt(str);
double d=Double.parseDouble(str1);
String to int example using Integer.parseInt(String)
public class JavaExample{
public static void main(String args[]){
String str="123";
int inum = 100;
/* converting the string to an int value
* ,the value of inum2 would be 123 after
* conversion
*/
int inum2 = Integer.parseInt(str);
int sum = inum+inum2;
System.out.println("Result is: "+sum);
}
}
2. Java – Convert String to primitive using valueOf(String) method
2- A Integer.ValueOf(String) convert String to int type.
2- B Float.valueOft(String) convert String to float type.
2- C Double.valueOf(String) convert String to double type .
String str = "1234",str1 = “14.48”;
int inum = Integer.valueOf(str);
double d=Double.valueOf(str1);
Convert String to int example using Integer.valueOf(String)
public class JavaExample{
public static void main(String args[]){
String str="234";
//An int variable
int inum = 110;
/* Convert String to int in Java using valueOf() method
* the value of variable inum2 would be integer after conversion
*/
int inum2 = Integer.valueOf(str);
//Adding up inum and inum2
int sum = inum+inum2;
//displaying sum
System.out.println("Result is: "+sum);
}
}
Methods of class Character
static boolean isDigit(char ch)
Returns the boolean value true if the specified character ch is a digit, otherwise, returns
the boolean value false.
boolean b = Character.isDigit('A'); // return false
boolean b = Character.isDigit('0'); // return true
static boolean isLetter(char ch)
Returns the boolean value true if the specified character ch is a letter, otherwise,
returns the boolean value false.
boolean b = Character.isLetter('A'); // return true
boolean b = Character.isLetter('0'); // return false
static boolean isLetterOrDigit(char ch)
Returns the boolean value true if the specified character ch is a letter or a digit,
otherwise, returns the boolean value false.
boolean b = Character.isLetterOrDigit('A'); // return true
boolean b = Character.isLetterOrDigit('6'); // return true
boolean b = Character.isLetterOrDigit('*'); // return false
static boolean isLowerCase(char ch)
Returns the boolean value true if the specified character ch is a lowercase character,
otherwise, returns the boolean value false.
boolean b = Character.isLowerCase('A')); // return false
boolean b = Character.isLowerCase('a')); // return true
static boolean isUpperCase(char ch)
Returns the boolean value true if the specified character ch is a uppercase character,
otherwise, returns the boolean value false.
boolean b = Character.isUpperCase('A')); // return true
boolean b = Character.isUpperCase('a')); // return false
static boolean isWhitespace(char ch)
Returns the boolean value true if the specified character ch is a white space, otherwise,
returns the boolean value false. A whitespace includes space, tab, or new line.
boolean b = Character.isWhitespace('A')); // return false
boolean b = Character.isWhitespace(' ')); // return true
boolean b = Character.isWhitespace('\n')); // return true
boolean b = Character.isWhitespace('\t')); // return true
static char toLowerCase(char ch)
Converts the specified character ch to lowercase and returns it .
Char d = Character.toLowerCase('B'); // return ‘b’
static char toUpperCase(char ch)
Converts the specified character ch to uppercase and returns it.
Char d = Character.toUpperCase('a'); // return ‘A’