javac Test java
E\SCIP>java Test
Outer class main method
E,\SCJP>java Test$Nested
Nested class main method
‘+ From the normal inner class we can access both static and non static members of outer
class but from static nested class we can access only static members of outer class.
Example:
class Test
{
static class Nested
{
public void methodOne()
{
System.out.printin(x);//C.E:non-static variable x cannot be referenced
from a static context
System.out.printin(y);
425,
DURGA SOFTCore java
NAGOOR BABU
Compression between normal or regular class and static nested class?
Normal /regular inner class Static nested class
1) Without existing outer class object| 1) Without existing outer class object
there is no chance of existing inner there may be a chance of existing static
class object. That is inner class object is ~ fasted “ela¥s “Gbjeet? “That is static
always associated with outer class nested class object is not associated
object. with outer class object.
2) Inside normal or regular inner class we | 2) Inside static nested class we can
can’t declare static members. declare static members.
3) “Inside normal inner class we can’t] 3) Inside static nested class we can
declare main() method and hence we declare main() method and hence we
can’t invoke regular inner class directly can invoke static nested class directly
from the command prompt. from the command prompt.
4) From the normal or regular inner class| 4) ‘From static nested class we can access
we can access both static and non only static members of outer class
static members of outer class directly. directly.
426
DURGA SOFT
426Core java NAGOOR BABU
Internationalization
* The process of designing a web application such that it supports various countries,
various languages without performing any changes in the application is called
Internationalization.
‘© We can implement Internationalization by using the following classes. They are:
1) Locale
2) NumberFormat
3) DateFormat
‘A.Locale: A Locale object can be used to represent a geographic (country) location (or)
language.
‘© Locale class present in java.util package.
© Itis a final class and direct child class of Object implements Cloneable and Serializable
Interfaces.
How to create a Locale object:
‘© We can create a Locale object by using the following constructors of Locale class.
1) Locale I=new Locale(String language);
2) Locale I=new Locale(String language,String country);
* Locale class already defines some predefined Locale constants. We can use these
constants directly.
Example:
Locale. UK
Locale. US
Locale. ITALY
Locale. CHINA
Important methods of Locale class:
1) public static Locale getDefault()
2) public static void setDefault{Locale |)
3) public String getLanguage()
4), public String getDisplayLanguage(Locale !)
5) public String getCountry()
6) public String getDisplayCountry(Locale I)
7) public static String[] getlSOLanguages()
8) public static String[] gettSOCountries()
9) public static Locale[] getAvailableLocales()
Example for Locale:
import java.util.*;
class LocaleDemo{
public static void main(String args{]){
Locale I1=Locale.getDefault();
/{System.out.printin(I1.getCountry()+"
427
DURGA SOFTCore java NAGOOR BABU
7/System.out.printin(I1.getDisplayCountry()+"...." #1. getDisplayLanguage());
Locale I2=new Locale("“pa”,"IN");
Locale.setDefault(I2);
‘String{] s3=Locale.getiSOLanguages();
for(String s4:s3) .
if
JiSystem.out.print("ISO language is
USystem.out.printin(s4);
}
Stringl] s4=Locale.getlSOCountries();
System.out.print("ISO Country is:");
‘System.out.printin(s5);
}
Localef] s=Locale.getAvailableLocales();
for(Locale s1:5)
{
USystem.out.print( "Available locales is:");
Hsystern.out.printin(s1.getDisplayCountry(}+"
mn
NumberFormat:
‘* Various countries follow various styles to represent number.
'+51.getDisplayLanguage());
123.456, 789.
* Byusing NumberFormat class we can format a number according to a particular Locale.
© NumberFormat class present in java.Text package and it is an abstract class.
* Hence we can’t create an object by using constructor.
NumberFormat nf=new NumberFormat();
Getting NumberFormat object for the default Locale:
‘* NumberFormat class defines the following methods for this.
invalid
1)public static NumberFormat getinstance();
2}public static NumberFormat getCurreneylnstance();
3)public static NumberFormat getPercentinstance();
4)public static NumberFormat getNumberinstance();
Getting NumberFormat object for the specific Locale;
© The methods are exactly same but we have to pass the corresponding Locale object as
argument.
428
DURGA SOFTCore java NAGOOR BABU
Example: public static NumberFormat getNumberinstance(Locale I);
* Once we got NumberFormat object we can call the following methods to format and
parse numbers.
1) public String format{long |};
2). public String format(double d);
* Toconvert a number from java form to Locale specific form.
1) public Number parse(String source)throws ParseException
* To convert from Locale specific String form to java specific form.
Example:
import java.util:*;
import java.text.*;
class NumberFormatDemo
{
Public static void main(String args{]){
double d=123456.789;
NumberFormat nf=NumberFormat getinstance(Locale.ITALY);
‘System. out.printin( “ITALY form is :"+nf.format(d));
}
}
‘Output:
ITALY form is :123.456,789
Requirement: Write a program to print a java number in INDIA, UK, US and ITALY currency
formats.
Program:
import java.util.";
import java.text.*;
class NumberFormatDemo
{
public static void main(String args{]}{
double d=123456.789;
Locale INDIA=new Locale("pa","IN");
NumberFormat nf=NumberFormat.getCurrencyinstance(INDIA);
System.out.printin("INDIA notation is :"+nf.format(d));
NumberFormat nfl=NumberFormat.getCurrencyinstance(Locale.UK);
‘System. out.printin("UK notation is :"+nf1.format(d)};
NumberFormat nf2=NumberFormat.getCurrencyinstance(Locale.US);
System.out.printin("US notation is :"+nf2.format(d));
NumberFormat nf3=NumberFormat.getCurrencyinstance(Locale.ITALY);
System. out.printIn("“ITALY notation is :"+nf3.format(d));
R
Ovtput:
INDIA notation is: INR 123,456.79
UK notation is: 123,456.79
US notation is: $123,456.79
a
DURGA SOFT
429Core java NAGOOR BABU
ITALY notat 123.456,79
ni Fra
NumberFormat class defines the following methads for this purpose.
1) public void setMaximumFractionDigits(int n
2). public void setMinimumFractionDigits(int n)
3) public void setMaximumintegerDigits(int n);
4) public void setMinimumintegerDigits(int n);
nm
Example:
import java.text.*;
public class NumberFormatExample
{
public static void main(String[] args){
NumberFormat nf=NumberFormat.getinstance();
nf-setMaximumFractionDigits(3);
System.out.printin(nf.format(123.4));
System.out printin(nf.format(123.4567));
nf.setMinimumFractionDigits(3);
System.out.printin(nf.format(123.4));
‘System.out.printin(nf.format(123.4567));
nf-setMaximurnintegerDigits(3);
System.out.printin(nf.format(1.234)};
System. out printin(nf.format(123456.789));
nf setMinimumintegerDigits(3);
System. out printIn(nf.format(1.234));
System.out.println(nf.format(123456.789));
B
Output:
123.4
123.457
123.400
123.457
1.234
456.789
001.234
456.789
DateFormat: Various countries follow various styles to represent Date. We can format the date
according to a particular locale by using DateFormat class.
* DateFormat class present in java.text package and it is an abstract class,
DateFon fe 4
‘© DateFormat class defines the following methods for this purpose.
430
DURGA SOFT
430Core java NAGOOR BABU
L)public static DateFormat getinstance();
2)public static DateFormat getDateinstance();
3)public static DateFormat getDatelnstance(int style);
DateFormat.FULL-
DateFormat.LONG——-—
DateFormat. MEDIMUM-—
DateFormat.SHORT:
1) public static DateFormat getDateinstance(int style, Locale |);
‘© Once we got DateFormat object we can format and parse Date by using the following
methods.
1) public String format(Date date);
‘© Toconvert the date from java form to locale specific string form.
1) public Date parse(String source)throws ParseException
‘* Toconvert the date from locale specific form to java form.
Requirement: Write a program to represent current system date in all possible styles of us
format.
Program:
import java.text.*;
import java.util.*;
public class DateFormatDemo
{
public static void main(String args[]{
System. out.printin("full form is :"+DateFormat.getDatelnstance(0).format(new Date()));
‘System.out.printin("long form is :"+DateFormat.getDatelnstance(1) format(new Date()));
System. out printin("medium form is :"+DateFormat.getDateinstance(2) format(new Date()));
‘System. out printin("short form is :"+DateFormat.getDateinstance(3).format(new Date()));
}
I
Output
Full form is: Wednesday, July 20, 2011
Long form is: July 20, 2011
Medium form is: Jul 20, 2011
Short form is: 7/20/11
‘Note: The default style is medium style.
Requirement; Write a program to represent current system date in UK, US and ITALY styles.
Program:
import java.text.*;
import java.util.*;
public class DateFormatDemo
{
431
DURGA SOFT
431Core java NAGOOR BABU
Public static void main(String argsiI
DateFormat UK=Dateformat.getDatelnstance(0,Locale.UK);
DateFormat US=DateFormat.getDateinstance(0,Locale.US);
DateFormat ITALY=DateFormat.getDatelnstance(0,Locale.ITALY);
System-out:printin("UK'style is :"+UK.format(new Date())); -
System.out.printin("US style is :"+US.format(new Date()));
‘System.out.printin("ITALY styl ITALY.format(new Date()));
}
Output:
UK style is: Wednesday, 20 July 2011
US style is: Wednesday, July 20, 2011
ITALY style is: mercoled> 20 luglio 2011
rma h date and time:
‘© DateFormat class defines the following methods for
1)public static DateFormat getDateTimeinstance();
2)public static DateFormat getDateTimeinstance(int dateStyie, int timeStyle);
3)public static DateFormat getDateTimeinstance(int dateStyle, int ‘ee Locale 1);
0to3
0to3
Exam
import java.text.*;
import java.util";
public class DateFormatDemo
{
public static void m:
}
}
Output:
ITALY style is: mercoledes 20 luglio 2011 23.21.30 1ST
432,
DURGA SOFT
432Core java NAGOOR BABU
Development
Javac: we can use Javac to compile a single or group of " java files”.
‘Syntax:
javacfoptions} . Testjava (valid)
Testjava Demo.java (valid)
-solitce java (valid)
version
-d
Java: we can use java command to run a single “.class file”.
‘Syntax:
java [options] classfileargi0] _ara{1).
version
-ea/-esa/-da/-dsa
D
-¢p/-classpath
Glasspath: Class path describes the location where the required “.class files” are available. We
can set the class path in the following 3 ways.
1)
2
3)
Permanently by using environment variable “classpath”. This class path will be
preserved after system restart also.
Temporary for a particular command prompt level by using “set” command.
Example:
set classpath=%classpath%;D:'\durga_classes;,;
Once if you close the command prompt automatically this class path will be lost.
We can set the class path for a particular command level by using "-cp” (or) “-class
path”. This class path is applicable only for that command execution, After executing
‘the command this classpath will be lost.
Among the 3 ways of setting the class path the most common way is setting class path
at command level by using “-cp”.
Example 1:
class Rain
{
public static void main(String args{}){
433,
DURGA SOFT
433Core java NAGOOR BABU
‘System.out.printin("Raining of jobs these days");
)
Analysis:
D:\lava>javac Rain, java (valid)
ining of jobs these days.
:\>java Rain (invatid)
Exception in thread "main" java.lang.NoClassDeffoundError: Rain
D:\>java -cp D:\java Rain (valid)
Raining of jobs these days.
D:\>java Rain (invalid)
\pjava -cp d:\java Rain (valid)
Raining of jobs these days
Example 2;
& B:
[public class Fresher lass ItCompany
Kt
lpublic void methodOne(}{
{System.out.printin("i want jot
limmediatel
i
"
bic static void main(String args{I}{
ser fonew Fresher();
methodOne();
sm.out.printin(“don't worry you will
et soon.
Analysis:
‘C:\pjavac Fresher. java (valid)
D:\>javac ItCompany java (invalid)
‘compile time error: Company java:4: cannot find symbol
symbol : dass Fresher
location: class itCompany
Fresher f=new Freaher();
D:\pjavac -¢p c:ItCompany.java{valid)
D:\>java ItCompany
Runtime error:NoClassDefFoundError: Fresher
D:\>java -cp c: ItCompany
Runtime error:NoClassDeffoundError: ItCompany
D:\>java -ep .¢: Company (valid)
i want job immediately
don't worry you will get soo
E:\>java -cp DssC: Company (valid)
434
DURGA SOFT
434Core java NAGOOR BABU
Example 3:
package packi.pack2; Package packs. pack4 fimport pack3. pack Saif,
oublic class Kareena import packt.pack2 Kareena; ktass Bhaskar{
publi void methodOne(}{ public class Saif{ [public static void mainiString|
|system.out.prntin("hellosoif.can | public void methodTwo(X larastIM
1u please set hellotune"}; Kareena k=new Kareena(); saits=new Saif);
kmethodOne(); j.methodtwo
System.out.pritin(*#ot possible asi am in} [system.out.printin(*kareena
kcani helo vou": Ht
Analysis:
:\>javac 4 . Kareena java (valid)
Di\pjavac-d. Saif java (invalid) ——> compile time error
Saif javass:
symbol : lass Kareena
location: cass pack3.packs Saif
Kareena knew Kareena();
Di\pjavac-ep c+ Saif.java (valid)
E\pjavac Bhaskar java (invalid) ——> compile ime error
Bhaskar java:4: cannot find symbol
symbol: class Saif
location: lass Bhaskar
Saif sonew Safi);
piavac -cp d: Bhaskar.java (valid)
E:\pjava Bhaskar (invalid) > Runtime error
iNoclassDefFoundError: pack3/pack8/Salf
E.\pjava ep d: Bhaskar (invalid) > Runtime error
\NoClassDefFoundError: Bhaskar
\pjava pd: Bhaskar (invalid) —SRuntime error
NoClassDefFoundérror:packi/pack2/Kareena
E\pjava jar -cvf bhaskar jar Beer.class Test.class X.class
D:\Enum>jar -cvf bhaskar-jar *.class
a jar file:
D:\Enum>jar -xvf bhaskar.jar
D:\Enum>jar -tvf bhaskar jar
436
DURGA SOFT
436Core java NAGOOR BABU
Example 5:
public class BhaskarColorFulCale{
public static int addlint x int y){
return x*y;
}
public static int multipiylint xint yl{
return 2%x*y;
i
Analysis:
\pjavac BhaskarColorFulCalc.java
jar -cvf bhaskar jar BhaskarColorFulCale.class
Example 6:
lass Client{
public static void main(String args{IM
System.out.printin(BhaskarColorFulCalc.add(10,20));
System.out.printin(BhaskarColorFulCalc.multiply(10,20));
»
Analysis:
D:\Enum>javac Client.java (invalid)
D:\Enum>javac -cp c: Client.java (invalid)
D:\Enum>javac -ep c:\bhaskar jar Client,java (valid)
D:\Enum>java -cp :e:\bhaskar.jar Client (valid)
‘Note: Whenever we are placing jar file in the classpath compulsory we have to specify the
name of the jar file also and just location is not enough.
System properties:
* For every system some persistence information is available in the form of system
properties. These may include name of the os, java version, vendor of jvm etc.
‘* We can get system properties by using getProperties() method of system class. The
following program displays all the system properties.
Example 7:
import java.util";
class Test{
public static void main(String argsfIM
//Proper
J here getPropertes() method returns the Properties object.
Properties p=System.getPropertiest};
pulist(System.out);
u
a class in util package.
437
DURGA SOFT
437Core java NAGOOR BABU
}
How to set system property from the command promot;
© We can set system property from the command prompt by using -D option.
Command;
D:\Enum>java -Dbhaskar=sejp Test
propertyname propertyvalue
‘What is the difference between path and classpath?
Path: We can use “path variable” to specify the location where required binary executables are
available.
* If we are not setting path then “java” and “Javac” commands won't work.
Glasspath: We can use “classpath variable” to describe location where required ciass files are
available.
© If we are not setting classpath then our program won't compile and run.
‘What is the difference between JDK, JRE and JVM?
DK (iava development kit): To develop and run java applications the required environment is
JDK.
JRE (java runtime environment): To run java appiication the required environment is JRE.
JVM (java virtual machine): To execute java application the required virtual machine is VM.
Diagram:
1K
> IDK=JRE*Development Tools.
> JRE=JVMeLibraries.
> JRE is the part of JOK.
> Jvmis the part of JRE.
t client side JRE is required and at developers side JDK is required.
rtcut way to place a jar fil
‘* If we are placing jar file in the following location then it is not required to set classpath
explicitly.
Not
438
DURGA SOFT
438Core java NAGOOR BABU
Diagram:
439)
DURGA SOFT
439Core java NAGOOR BABU
ENUM
© We can use enum to define a group of named constants.
Example 1:
enum Month
{
JAN, FEB/MAR,DEC;
}
Example 2:
enum Beer
{
KF,KO,RC,FO;
}
‘© Enum concept introduced in 1.5 versions.
‘When compared with old languages enum java’s enum is more powerful.
© By using enum we can define our own data types which are also come enumerated data
‘+ Internally enum’s are implemented by using class concept. Every enum constant is
reference variable to that enum type object.
‘* Every enum constant is implicitly public static final always.
enum Beer final class Beer extends java.lang.Enum{
{ public static final Beer KF=new Beer();
KF,KO; public static final Beer KO=new Beer();
} i
Diagram:
Decl :
Example 4:
enum Beer
{
KF,KO,RC,FO;//here semicolon is optional.
iY
class Test
{
public static void main(String args{]}{
440
DURGA SOFT
440Core java NAGOOR BABU
Beer bi=Beer.KF;
System.out.printin(b4);
}
}
Output:
D:\Enum>java Test
KF
Note: Every enum constant internally static hence we can access by using “enum name”.
Enum vs switch statement:
‘© Until 1.4 versions the allowed types for the switch statement are byte, short, char int.
But from 1.5 version onwards in addition to this the corresponding wrapper classes and
enum type also allowed. That is from 1.5 version onwards we can use enum type as
argument to switch statement.
byte Bye
une) short short
) int Integer 1
char > character
Tav +
um
Example:
enum Beer
it
KF,KO,RC,FO;
}
class Test{
public static void main(String argstI){
Beer bi=Beer.RC;
switch(b1{
case KF:
System.out printin( "itis childrens brand");
break;
case KO:
System.out.println("it is too lite");
break;
case RC:
aa
DURGA SOFT
aaCore java NAGOOR BABU
‘System.out.printin("it is too hot");
break;
case FO:
System.out.printIn("buy one get one");
break;
default:
System.out printin(“other brands are not good");
}
D:\Enum>java Test
Itis too hot
* If we are passing enum type as argument to switch statement then every case label
should be a valid enum constant otherwise we will get compile time error.
Example:
enum Beer
{
KF,KO,RCFO;
,
class Test{
public static void main(String args{]){
Beer b1=Beer.RC;
switch(b1){
case KF:
case RC:
case KALYANI:
mn
‘Output:
Compile time error.
D:\Enum>javac Test.java
‘Test.java:11: unqualified enumeration constant name required
case KALYANI:
© We can declare enum either outside the class or within the class but not inside a
method. If we declare enum outside the class the allowed modifiers are:
1) public
2) default
3) strietfp.
‘© Ifwe declare enum inside a class then the allowed motifiers are:
aaa,
DURGA SOFT
442Core java
NAGOOR BABU
1) public private
2) default + protected
3) strictfp static
Exami : a
| lass x
enum x | cassx | {
0 t public void methodOne({
classy | enumy | enumx
0 0 Q_ putpute
: } > eompile time error.
(watid) | Yyatiay |) fosNtnumojavac X.java
}Xjavar4: enum types must not be local
lerum x
Enum vs inheritance:
‘* Every enum in java is the direct child class of java.lang.Enum class hence it is not
possible to extends any other enum.
‘© Every enum is implicitly final hence we can’t create child enum.
‘© Because of above reasons we can conclude inheritance concept is not applicable for
enum’s explicitly.
© But enum can implement any no. Of interfaces simultaneously.
Exam
oe ‘enum X extends Enum | S35*%
0 ° 0
‘enum Y extends X ‘enum Y extends X
0
(irwal {inwalid)
Example:
enum X
0
class ¥ extends X
0
‘output interface x
‘compile time error. 0
DAAEnum>javac Y.iava ‘enum Y implements X
Y¥java:3:cannot inherit from finalX | (}
class ¥ extends X ey
‘.java:3: enum types are not extensible
class ¥ extends X
(invalid)
Java.lang.Enum: Every enum in java is the direct child class of java.lang.Enum. The power of
enum is inheriting from this class only.
a3
DURGA SOFT
443Core java NAGOOR BABU
‘© itis abstract class and it is direct child class of “Object class” it implements Serializable
and Comparable,
values() method: Every enum implicitly contains a static values() method to list all constants of
enum.
Example: Beer{] b=Beer.values();
‘ordinal{) method; Within enum the order of constants is important we can specify by its ordinal
value.
¢ We can find ordinal value(index value) of enum constant by using ordinal() method.
Example: public int ordinal();
Example:
enum Beer
{
KE,KO,RC,FO;
}
class Test{
public static void main(String args{]){
Beer{] b=Beer.values();
for(Beer b1:b)//this is forEach loop.
{
System.out.printin(b1+".
"+b Lordinal());
Specialty of java enur
powerful because in addit
When compared with old languages enum java’s enum is more
n to constants we can take normal variables, constructors, methods
etc which may not possible in old languages.
Inside enum we can declare main method and even we can invoke enum directly from
the command prompt.
Example:
‘enum Fish{
GOLD, APOLO,STAR;
public static voi
(String args{]){
System.out.printin("enum main() method called");
b
DURGA SOFT
444Core java NAGOOR BABU
‘Output:
D:\Enum>java Fish
enum main() method called
‘+ Inaddition to constants if we are taking any extra members like methods then the list of
constants should be in the 1* tine and should ends with semicolon.
‘If we are taking any extra member then enum should contain at least one constant. Any
way an empty enumis always valid.
Example;
enum X{
enum X{ . “ ‘public void methodOne(}{
A,8,C;//here semicolon mandatory. } y
abt roan ac
} (wali) {invalid)
enum enum Jenum x
C" c |
publicveld methosDrell) | public vod methodone(
+ twain (vata) [Panay
Enum vs constructor: Enum can contain constructor. Every enum constant represents an object
of that enum class which is static hence all enum constants will be created at the time of class
loading automatically and hence constructor will be executed at the time of enum class loading
for every enum constants,
Example:
enum Beer{
KF,KO,RC,FO;
Beer(){
‘System.out.printin("Constructor called.");
}
}
class Test{
public static void main(String args{]}
Beer b=Beer.KF;
‘System,out.printin("hello.'
y
Output:
D:\Enum>java Test
Constructor called.
Constructor called.
Constructor called.
445,
DURGA SOFT
445Core java NAGOOR BABU
Constructor called.
Hello.
‘* We can’t create enum object explicitly and hence we can’t invoke constructor directly.
Example:
enum Beer{
KF,KO,RC,FO;
Beer(){
System.out.printin("constructor called");
}
}
class Test{
public static void main(String args{]){
Beer b=new Beer();
‘System.out.printin(b);
y
Output:
Compile time error.
D:\Enum>javac Test java
enum types may not be instantiated
new Beer();
Example:
kF==>public static final Beer KF=new Beer();
IKF(100)==>public static final Beer KF=new Beer(100};
enum Beer
{
KF(100), KO(70),RC(65),Fo(90), KALYANI;
int price;
price){
this.price=price;
}
Beer()
c
this.p!
}
public int getPrice()
{
retum price;
}
125;
a6
DURGA SOFT
448Core java NAGOOR BABU
}
class Test(
public static void main(String argsf)}{
Beer[] b=Beer.values();
for(Beer b1:b)
{
System.out.printin(b1+"
mw
'+b1.getPrice());
‘© Inside enum we can take beth instance and static methods but it is not possible to take
abstract methods.
Gsel:
* Every enum constant represents an object hence whatever the methods we can apply
on the normal objects we can apply the same methods on enum constants also.
Which of the following expressions are valid?
1) Beer.KF==Beer.RC-
2) Beer.KF.equals(Beer.RC)
3) Beer.KF false
—>false
invalid
—>valid
3) import static pack1.Fish.’
DURGA SOFT
447Core java NAGOOR BABU
4) import static pack1 Fi
Baample 3:
package pack3;
/Tirmport pack.
import pack1.*;
/fmnport static pack1.Fish.GUPPY;
import static pack1.Fish.*;
class B
{
public static void main(String args{]}{
Fish f=Fish.STAR;
‘System.out.printin(GUPPY);
}
}
Case 3:
enum Color
System.out.printin("Dangerous color");
}
1.GREEN;
Public void info()
{
System.out.printin( "Universal color");
t
class Test{
Public static void main(String args{I){
Color{] c=Color.values();
for(Color c1:
{
cLinfo();
m
‘Output:
Universal color
Dangerous color
Universal color
a8,
DURGA SOFT
448Core java NAGOOR BABU
Regular expression
© A Regular Expression is a expression which represents a group of St
particular pattern.
Example:
* We can write a Regular Expression to represent all valid mail ids.
* We can write a Regular Expression to represent all valid mobile numbers.
applic
is according to a
re: lar 6
‘* Toimplement validation logic.
* To develop Pattern matching applications.
‘* To develop translators like compilers, interpreters etc.
* To develop digital circuits.
* To develop communication protocols like TCP/IP, UDP etc.
Example:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[} args)
{
int count=0;
Pattern p=Pattern.compile("ab");
Matcher m=p.matcher("abbbabbaba”);
while(m.find())
{
count++;
System.out.printin(m.start()+"
“+mend(}+"
}
‘System.out.printin("The no of occurences :"+count);
‘The no of occurrences: 3
Pattern class:
‘* APattern object represents “compiled version of Regular Expression”
© We can create a Pattern object by using compile() method of Pattern class.
449
DURGA SOFT
449Core java
public static Pattern compile(String regex);
Example:
Pattern p=Pattern.compile("ab");
‘Note: if we refer API we will get more information about pattern class.
Matcher:
NAGOOR BABU
* A Matcher object can be used to match character sequences against a Regular
Expression. We can create a Matcher object by using matcher() method of Pattern
class.
public Matcher matcher(String target);
Matcher m=p.matcher("abbbabbaba");
Important methods of Matcher class:
1) boolean find();
‘© Itattempts to find next match and returns true if it is available otherwise returns false.
2) int start();
* Returns the start index of the match.
3) int end();
© Returns the offset(equalize) after the last character matched.(or)
* Returns the end index of the matched.
4) String group();
© Returns the matched Pattern.
Note: Pattern and Matcher classes are available in java.util.regex package.
Either ‘a’ or ‘b’ or ‘c’
Except ‘a’ and ‘b’ and ‘c’
ny lower case alphabet symbol
‘ny upper case alphabet symbol
wny alphabet symbol
—Any digit from 0 to9
Any alphanumeric character
Bample:
import java.util
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("alb7@z#"};
while(m.find())
450,
DURGA SOFTCore java NAGOOR BABU
System.out.printin(m.start()+"
—@
Bad
bt
Predefined character classes:
space character
-Any digit from o to 9[o-9]
‘Any word character[a-zA-Z0-9]
-Any character including special characters.
Example:
import java.util.regex.";
class RegularExpressionDerno
{
public static void main(String] args)
{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("alb7@z#");
while(m.find())
{
System.out.printin(m.start(}+"--—"+m.group());
}
}
451
DURGA SOFT
451Core java NAGOOR BABU
Quantifiers:
+ Quantifiers can be used to specify no of characters to match.
—Exactly one ‘a!
At least one ‘a’
‘Any no of a's including zero number
—At most one ‘a’
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(Stringf] ares)
{
Pattern p=Pattern.compile("x");
Matcher m=p.matcher("abaabaaab");
while(m.find())
{
‘System. out. printin(m start()+"--—"+m.group());
}
}
}
Output:
xea__ | xeat xza?
“o—a |o—a Oa
2——a | 2—aa
Pattern class split() metho:
* Pattern class contains split() method to split the given string against a regular
expression.
Example 1:
import java.util.regex.*;
class RegularExpressionDemo
{
452
DURGA SOFTCore java NAGOOR BABU
public static void main(String[] args)
{
Pattern p=Pattern.compile("\\s");
String[] s=p.split("bhaskar software solutions");
for(String s1:s)
{
‘System.out.printIn(s1);//bhaskar
Hsoftware
//solutions
}
}
}
Example 2:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("\\."}; (or)L-]
String{] s=p.split(" www.dugrajobs.com");
for(String s
{
System.out.printin(s1);//www
//dugrajobs
//com
}
String class split() metho
* String class also contains split() method to split the given string against a regular
expression.
Example:
import java.util.regex.*;
class RegularExpressionDemo
{
public static void main(String{] args)
{
String s="www.durgajobs.com";
453,
DURGA SOFTCore java NAGOOR BABU
‘String|] s1=s.split("\.’
for(String s2:s1)
{
System.out.printin(s2);//mww
/[durgajobs
Icom
‘+ String class split() method can take regular expression as argument where as pattern
class split() method can take target string as the argument.
StringTokenizer:
© This class present in java.util package.
© Itisa specially designed class to perform string tokenization.
Example 1:
import java.util;
class RegularExpressionDemo
{
public static void main(Stringf] args)
{
StringTokenizer st=new StringTokenizer("durga software solutions");
while(st.hasMoreTokens())
{
‘System.out.printin(st.nextToken());//durga,
I/software
//solutions
}
}
J
© The default regular expression for the StringTokenizer is space.
Example 2:
import java.uti
class RegularExpressionDemo
{
public static void main(String[) args)
{
454
DURGA SOFTCore java NAGOOR BABU
‘StringTokenizer st=new StringTokenizer("2,99,988",","),
Target Rogular Expression
{{StringTokenizer st=new StringTokenizer("1,99,988",",");
while(st.hasMoreTokens())
{
System.out.printin(st.nextToken());//1
1/99
1/988
}
Requirement: Write a regular expression to represent all valid identifiers in yava language.
Rules:
The allowed characters are:
1) atoz,AtoZ,0t09,-
2) The 1" character should be alphabet symbol only.
3) The length of the identifier should be at least 2.
Program:
import java.util.regex.";
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("[a-zA-Z][a-2A-Z0-9-#]+"); (or)
Pattern p=Pattern.compile("[a-zA-Z][a-2A-Z0-9-H][a-2A-Z0-9-H]*
Matcher m=p.matcher(args[0});
if{m.find()&&mn.group().equals(args{0}))
{
System.out.printin( "valid identifier");
}
else
{
System.out.printin("invalid identifier");
}
}
}
455
DURGA SOFTCore java NAGOOR BABU
Outputs
scip>javac RegularExpressionDemo,java
€:\scjp>java RegularExpressionDemo bhaskar
Valid identifier
:\scjp>java RegularExpressionDemo ?bhaskar
Invalid identifier
Requirement: Write a regular expression to represent all mobile numbers.
Rules:
2) Should contain exactly 10 digits.
2) The 1* digit should be 7 to 9.
Program:
import java.utilregex.*;
class RegularExpressionDemo
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("{7-9}{0-9]{0-9]{0-9]10-9]{0-9][0-9][0-9][0-9][0-9
[pattern p=Pattern.compile("[7-9]{0-9](9}");
Matcher m=p.matcher(args{0});
‘f(m find()&&m.group().equals(args[0]))
{
System.out printin( "valid number");
System.out.printin("invalid number");
10 digits mobile:
{7-9][0-9][0-9][0-9}[0-9}{0-9}[0-9}[0-9][0-9][0-9] (or)
{7-9][0-9{9}
‘Output:
E:\scjp>javac RegularExpressionDemo java
£:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 6989308279
456
DURGA SOFTCore java NAGOOR BABU
Invalid number
10 digits (or) 11 digits:
(0?[7-9}[0-9}{9})
‘Output:
E:\s¢jp>javac RegularExpressionDemo.java
cjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 09989308279
Valid number
E:\scjp>java RegularExpressionDemo 919989308279
number
(Or) 11. (or) 12 digits:
(0191)2{7-9]{0-91{9} (or)
(91)2(02(7-9][0-91{9))
£:\scjp>javac RegularExpressionDemo,java
E:\scjp>java RegularExpressionDemo 9989308279
Valid number
E:\scjp>java RegularExpressionDemo 09989308279
Valid number
E:\scjp>java RegularExpressionDemo 919989308279
Valid number
E:\scjp>java RegularExpressionDemo 69989308279
Invalid number
Requirement: Write a regular expression to represent all Mail Ids.
Program:
import java.util.regex.*;
class RegularExpressionDemo
(
public static void main(String[] args)
{
Pattern p=Pattern.compile("[a-zA-Z}{a-zA-Z0-9-.]* @[a-zA-Z0-9] +([.][a-zA-Z]+)+");
Matcher m=p.matcher(args[0]);
if{m find()&&m.group().equals(args{0}))
{
System.out.printin("*valid mail i
else
457
DURGA SOFTCore java NAGOOR BABU
}
‘Output:
System.out.printin("invalid mail id
E:\scjp>iavac RegularExpressionDemo,java
E:\scjp>java RegularExpressionDemo [email protected]
Valid mail id
E:\scjp>java RegularExpressionDemo [email protected]
Invalid mail fd
:\scip>java RegularExpressionDemo [email protected]
Invalid mail id
Requirement: Write a program to extract all valid mobile numbers from a file.
Diagram:
(9988308279
9052142606
9700720065
6998930827
aan
566666666
3333333333,
(9989308279)
| > |s052142606
12700720065,
‘output.oxt
inputot
Program:
import java.util.regex.*;
import java.io.*;
class RegularExpressionDemo
iz
public static void main(String[] args)throws :O€xception
{
Printwriter out=new PrintWriter("output.txt");
BufferedReader br=new BufferedReader(new FileReader("input.txt"));
Pattern p=Pattern.compile("[7-9][0-91{9}");
String line=br.readtine();
while(linet=null)
{
Matcher m=p.matcher(line);
while(m.find())
{
out printin(m.group());
}
458
DURGA SOFTCore java NAGOOR BABU
line=br.readLinel);
}
out-flush();
}
Requirement: Write a program to extract all Mail IDS from the File.
Note: In the above program replace mobile number regular expre:
expression.
Requirement: Write a program to display all txt file names present in E:\sc)p folder.
Program:
import java.util.regex.*;
with MAIL ID regular
import java.io.*;
class RegularExpressionDemo:
{
public static void main(String[] args)throws IOException
{
int count=0;
Pattern p=Pattern.compile("[a-2A-20-9-$.}+| txt");
File f=new File("E:\\scjp");
String[] s=f.list();
for(String s1:s)
{
Matcher m=p.matcher(s1);
if(m.find()&&m.group().equals(s1))
{
count++;
System.out.printin(s1);
}
}
System.out printin(count);
input.txt
output.txt
outut.txt
3
459)
DURGA SOFT