Sie sind auf Seite 1von 36

Chapter 10

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.

In the above example only one object will be created.


Firstly JVM will not find any string object with the
value "Welcome" in string constant pool, so it will
create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create
2) By new keyword
Strings=newString("Welcome");//createstwoobj
ectsandonereferencevariable
In such case, JVM will create a new string object
in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant
pool. The variable s will refer to the object in
heap(non pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string
literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array
to string
String s3=new String("example");//creating java
string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
Immutable String in Java
In java,string objects are immutable. Immutable
simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be
changed but a new string object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Apex";
s.concat(" College");//concat() method appends the
string at the end
System.out.println(s);//will print Apex because
strings are immutable objects
}
}
Output:Apex
class Testimmutablestring1{
public static void main(String args[]){
String s="Apex";
s=s.concat("College");
System.out.println(s);
}
}
Output: Apexcollege
Java String compare
String compare by equals() method
The String equals() method compares the original
content of the string. It compares values of string
for equality. String class provides two methods:
public boolean equals(Object
another)compares this string to the specified
object.
public boolean equalsIgnoreCase(String
another)compares this String to another string,
ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
class Teststringcomparison2{
public static void main(String args[]){
String s1="apex";
String s2="APEX";

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)

Java String trim() method


Strings="Sachin";
System.out.println(s);//Sachin
System.out.println(s.trim());//Sachin
Java String startsWith() and endsWith() method
Strings="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
Java String charAt() method
Strings="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Java String length() method
Strings="Sachin";
System.out.println(s.length());//6
Java String replace() method
Strings1="Javaisaprogramminglanguage.Javaisapl
atform.JavaisanIsland.";
StringreplaceString=s1.replace("Java","Kava");//replace
salloccurrencesof"Java"to"Kava"
System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava
is an Island.
Java String indexOf
Thejava string indexOf()method returns index of
given character value or substring. If it is not found, it
returns -1. The index counter starts from zero.
publicclassIndexOfExample{
publicstaticvoidmain(Stringargs[]){
Strings1="thisisindexofexample";
//passingsubstring
intindex1=s1.indexOf("is");//returnstheindexofissubstring
intindex2=s1.indexOf("index");//returnstheindexofindexsu
bstring
System.out.println(index1+""+index2);//28

//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));

dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at'


hh:mm:ss a zzz");
System.out.println("Format 2: " + dateFormatter.format(now));

dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");


System.out.println("Format 3: " + dateFormatter.format(now));
}
}
Output:
Thu Jan 07 10:34:11 NPT 2016
Format 1: Thu, 2016-1-7 at 10:34:11 AM NPT
Format 2: Thu 2016.01.07 at 10:34:11 AM NPT
Format 3: Thursday, January 7, 2016
java.util.Calendar &
java.util.GregorianCalendar
TheCalendarclass provides support for:
maintaining a set of calendar fields such
asYEAR,MONTH,DAY_OF_MONTH,HOUR,MINUTE,SE
COND,MILLISECOND; and manipulating these
calendar fields, such as getting the date of the
previous week, roll forward by 3 days.
Calendaris a abstract class, and you cannot use the
constructor to create an instance. Instead, you use the
static methodCalendar.getInstance()to instantiate an
implementation sub-class.
Calendar.getInstance(): return aCalendarinstance
based on the current time in the default time zone
with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
The most important method inCalendarisget(int
calendarField), which produces anint.
ThecalendarFieldare defined asstaticconstant and
includes:
get(Calendar.DAY_OF_WEEK): returns 1
(Calendar.SUNDAY) to 7 (Calendar.SATURDAY).
get(Calendar.YEAR):year
get(Calendar.MONTH): returns 0 (Calendar.JANUARY) to
11 (Calendar.DECEMBER).
get(Calendar.DAY_OF_MONTH),get(Calendar.DATE): 1
to 31
get(Calendar.HOUR_OF_DAY): 0 to 23
get(Calendar.MINUTE): 0 to 59
get(Calendar.SECOND): 0 to 59
get(Calendar.MILLISECOND): 0 to 999
get(Calendar.HOUR): 0 to 11, to be used together
withCalendar.AM_PM.
get(Calendar.AM_PM): returns 0 (Calendar.AM) or 1
import java.util.Calendar;

public class CalenderDemo {


public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// You cannot use Date class to extract individual Date fields
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.println("Now is: "+year+"/"+(month+1)
+"/"+""+day+" "+hour+":"+minute+":"+second);
}
}
Output:
Now is: 2016/1/7 10:46:23
Random Class
An instance of this class is used to generate a stream of
pseudorandom numbers.
next(int)Generates the next pseudorandom number.
nextBytes(byte[])Generates a user specified number of
random bytes.
nextDouble()Returns the next pseudorandom, uniformly
distributeddoublevalue between0.0and1.0from this random
number generator's sequence.
nextFloat()Returns the next pseudorandom, uniformly
distributedfloatvalue between0.0and1.0from this random
number generator's sequence.
nextInt()Returns the next pseudorandom, uniformly
distributedintvalue from this random number generator's
sequence.
nextLong()Returns the next pseudorandom, uniformly
distributedlongvalue from this random number generator's
sequence.
import java.util.Random;
public class RandomClassDemo {
public static void main( String args[] ){
// create random object
Random randomno = new Random();

// check next int value


for(int i=0;i<10;i++)
System.out.println("Next int value: " +
randomno.nextInt(10000));
}
}

Das könnte Ihnen auch gefallen