Unit 10 String Handling
Unit 10 String Handling
String Handling
Java String
In java, string is basically an object that represents
sequence of char values.
An array of characters works same as java string. For
example:
char[]ch={a,p,e,x,c,o,l,l,e',g,e};
Strings=newString(ch);
is same as:
Strings=apexcollege";
The java String is immutable i.e. it cannot be changed
but a new instance is created. For mutable class, you
can use StringBuffer and StringBuilder class.
What is String in java
Generally, string is a sequence of characters. But
in java, string is an object that represents a
sequence of characters. String class is used to
create string object.
How to create String object?
There are two ways to create String object:
By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
Strings="welcome";
Each time you create a string literal, the JVM checks
the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance
is returned.
If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For
example:
Strings1="Welcome";
Strings2="Welcome";//willnotcreatenewinstance
Note:
String
objects
are
stored
in a
special
memor
y area
known
as
string
consta
nt
pool.
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
String compare by compareTo() method
The String compareTo() method compares values
lexicographically and returns an integer value
that describes if first string is less than, equal to
or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2:0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Apex";
String s2="Apex";
String s3="Ace";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because
s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 <
s1 )
}
}
String Concatenation in Java
1) String Concatenation by + (string concatenation)
operator
classTestStringConcatenation1{
publicstaticvoidmain(Stringargs[]){
Strings="Sachin"+"Tendulkar";
System.out.println(s);//SachinTendulkar
}
}
2) String Concatenation by concat() method
classTestStringConcatenation3{
publicstaticvoidmain(Stringargs[]){
Strings1="Sachin";
Strings2="Tendulkar";
Strings3=s1.concat(s2);
System.out.println(s3);//SachinTendulkar
}
}
Substring in Java
A part of string is calledsubstring. In other words,
substring is a subset of another string. In case of
substring startIndex is inclusive and endIndex is
exclusive.
You can get substring from the given string object
by one of the two methods:
public String substring(int startIndex):This
method returns new String object containing the
substring of the given string from specified
startIndex (inclusive).
public String substring(int startIndex, int
endIndex):This method returns new String object
containing the substring of the given string from
specified startIndex to endIndex.
Strings="hello";
publicclassTestSubstring{
publicstaticvoidmain(Stringargs[]){
Strings="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Output:
Tendulkar
Sachin
Java String toUpperCase() and
toLowerCase() method
Strings="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(nochangeinoriginal)
//passingsubstringwithfromindex
intindex3=s1.indexOf("is",4);//returnstheindexofissubstrin
gafter4thindex
System.out.println(index3);//5i.e.theindexofanotheris
//passingcharvalue
intindex4=s1.indexOf('s');//returnstheindexofscharvalue
System.out.println(index4);//3
}}
Java String lastIndexOf
Thejava string lastIndexOf()method returns
last index of the given character value or
substring. If it is not found, it returns -1. The index
counter starts from zero.
publicclassLastIndexOfExample{
publicstaticvoidmain(Stringargs[]){
Strings1="thisisindexofexample";//thereare2
's'charactersinthissentence
intindex1=s1.lastIndexOf('s');//returnslastindex
of's'charvalue
System.out.println(index1);//6
}}
Java StringBuffer class
Java StringBuffer class is used to created mutable
(modifiable) string. The StringBuffer class in java
is same as String class except it is mutable i.e. it
can be changed.
Important Constructor
StringBuffer():creates an empty string buffer
with the initial capacity of 16.
StringBuffer(String str):creates a string buffer
with the specified string.
StringBuffer(int capacity):creates an empty
string buffer with the specified capacity as length.
classA{
publicstaticvoidmain(Stringargs[]){
StringBuffersb=newStringBuffer("Hello");
sb.append("Java");//noworiginalstringischanged
System.out.println(sb);//printsHelloJava
}
}
Java StringBuilder class
Java StringBuilder class is used to create mutable
(modifiable) string. The Java StringBuilder class is
same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.
Important Constructors of StringBuilder class
StringBuilder():creates an empty string Builder
with the initial capacity of 16.
StringBuilder(String str):creates a string
Builder with the specified string.
StringBuilder(int length):creates an empty
string Builder with the specified capacity as
length.
classA{
publicstaticvoidmain(Stringargs[]){
StringBuildersb=newStringBuilder("Hello");
sb.append("Java");//noworiginalstringischanged
System.out.println(sb);//printsHelloJava
}
}
Date class
Thejava.util.Dateclass represents a specific
instant in time, with millisecond precision.
Constructor
Date()
Date(lone millisecond)
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now);
//SimpleDateFormat can be used to control the date/time
display format:
// E (day of week):
// M (month): M (in number), MM (in number with
leading zero)
// 3M: (in text xxx), >3M: (in full text full)
// h (hour): h, hh (with leading zero)
// m (minute)
// s (second)
// a (AM/PM)
// H (hour in 0 to 23)
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d
'at' h:m:s a z");
System.out.println("Format 1: " + dateFormatter.format(now));