Java Notes
Java Notes
1) Simple
Java is easy to learn and its syntax is quite simple,
clean and easy to understand.The confusing and
ambiguous concepts of C++ are either left out in
Java or they have been re-implemented in a cleaner
way.
Eg : Pointers and Operator Overloading are not
there in java but were an important part of C++.
2) Object Oriented
In java everything is Object which has some data
and behaviour. Java can be easily extended as it is
based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes
by emphasizing mainly on compile time error
checking and runtime checking. But the main areas
which Java improved were Memory Management
and mishandled Exceptions by introducing
automatic Garbage Collector and Exception
Handling.
4) Platform Independent
Unlike other programming languages such as C, C+
+ etc which are compiled into platform specific
machines. Java is guaranteed to be write-once, run-
anywhere language.
On compilation Java program is compiled into
bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode
format also provide security. Any machine with Java
Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first
choice. With java secure features it enable us to
develop virus free, temper free system. Java
program always runs in Java runtime environment
with almost null interaction with system OS, hence it
is more secure.
6) Multi Threading
Java multithreading feature makes it possible to
write program that can do many tasks
simultaneously. Benefit of multithreading is that it
utilizes same memory and other resources to
execute multiple threads at the same time, like While
typing, grammatical errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing
to do with a particular computer architecture, hence
a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No
implementation dependent features. Everything
related to storage is predefined, example: size of
primitive data types
9) High Performance
Java is an interpreted language, so it will never be
as fast as a compiled language like C or C++. But,
Java enables high performance with the use of just-
in-time compiler.
System is a Class
out is a Variable
println() is a method
Integer
This group includes byte, short, int, long
byte : It is 1 byte(8-bits) integer data type. Value
range from -128 to 127. Default value zero.
example: byte b=10;
short : It is 2 bytes(16-bits) integer data type. Value
range from -32768 to 32767. Default value zero.
example: short s=11;
int : It is 4 bytes(32-bits) integer data type. Value
range from -2147483648 to 2147483647. Default
value zero. example: int i=10;
long : It is 8 bytes(64-bits) integer data type. Value
range from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. Default value zero.
example: long l=100012;
Floating-Point Number
This group includes float, double
float : It is 4 bytes(32-bits) float data type. Default
value 0.0f. example: float ff=10.3f;
double : It is 8 bytes(64-bits) float data type. Default
value 0.0d. example: double db=11.123;
Characters
This group represent char, which represent symbols
in a character set, like letters and numbers.
char : It is 2 bytes(16-bits) unsigned unicode
character. Range 0 to 65,535. example: char c='a';
Boolean
This group represent boolean, which is a special
type for representing true/false values. They are
defined constant of the language. example: boolean
b=true;
Identifiers in Java
All Java components require names. Name used for
classes, methods, interfaces and variables are
called Identifier. Identifier must follow some rules.
Here are the rules:
All identifiers must start with either a letter( a to z
or A to Z ) or currency character($) or an
underscore.
After the first character, an identifier can have any
combination of characters.
A Java keyword cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo
are two different identifiers.
Type Casting
Assigning a value of one type to a variable of
another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit)
}
Output :
Int value 100
Long value 100
Float value 100.0
}
Output :
Double value 100.04
Long value 100
Int value 100
Variable
What is a variable?
When we want to store any information, we store it
in an address of the computer. Instead of
remembering the complex address where we have
stored our information, we name that address.The
naming of an address is known as variable. Variable
is the name of memory location.
Java Programming language defines mainly three
kind of variables.
1.Instance variables
2.Static Variables
3.Local Variables
1) Instance variables
Instance variables are variables that are declare
inside a class but outside any method,constructor or
block. Instance variable are also variable of object
commonly known as field or property. They are
referred as object variable. Each object has its own
copy of each variable and thus, it doesn't effect the
instance variable if one object changes the value of
the variable.
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student
class.
2) Static variables
Static are class variables declared with static
keyword. Static variables are initialized only once.
Static variables are also used in declaring constant
along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object
of Student class will share instituteCode property.
Additional points on static variable:
static variable are also known as class variable.
static means to remain constant.
In Java, it means that it will be constant for all the
instances created for that class.
static variable need not be called from object.
It is called by classname.static variable name
Note: A static variable can never be defined inside a
method i.e it can never be a local variable.
Example:
Suppose you make 2 objects of class Student and
you change the value of static variable from one
object. Now when you print it from other object, it will
display the changed value. This is because it was
declared static i.e it is constant for every object
created.
package profound;
class Student{
int a;
static int id = 35;
void change(){
System.out.println(id);
}
}
o1.change();
Student.id = 1;
o2.change();
}
}
Output:
35
1
3) Local variables
Local variables are declared in method, constructor
or block. Local variables are initialized when
method, constructor or block start and will be
destroyed once its end. Local variable reside in
stack. Access modifiers are not used for local
variable.
Array Declaration
Syntax :
datatype[ ] identifier;
or
datatype identifier[ ];
Both are valid syntax for array declaration. But the
former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.
Initialization of Array
new operator is used to initialize an array.
Example :
int[ ] arr = new int[10]; //this creates an empty
array named arr of integer type whose size is 10.
or
int[ ] arr = {10,20,30,40,50}; //this creates an
array named arr whose elements are given.
Multi-Dimensional Array
A multi-dimensional array is very much similar to a
single dimensional array. It can have multiple rows
and multiple columns unlike single dimensional
array, which can have only one full row or one full
column.
Array Declaration
Syntax:
datatype[ ][ ] identifier;
or
datatype identifier[ ][ ];
Initialization of Array
new operator is used to initialize an array.
Example:
int[ ][ ] arr = new int[10][10]; //10 by 10 is the
size of array.
or
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},
{11,12,13,14,15}};
// 3 by 5 is the size of the array.
Jagged Array
Jagged means to have an uneven edge or surface.
In java, a jagged array means to have a multi-
dimensional array with uneven size of rows in it.
Initialization of Jagged Array
new operator is used to initialize an array.
Example:
int[ ][ ] arr = new int[3][ ]; //there will be 10
arrays whose size is variable
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];
Java Operators
Java provides a rich set of operators enviroment.
Java operators can be devided into following
categories
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical
expression in the same way that are used in
algebra.
operator description
% remainder of division
Relation operators
The following table shows all relation operators
supported by Java.
operator description
Logical operators
Java supports following 3 logical operator. Suppose
a=1 and b=0;
operator description example
|| Logical OR (a || b) is true
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assignment Operators
Assignment operator supported by Java are as
follows
operator description example
Misc operator
There are few other operator supported by java
language.
Conditional operator
It is also known as ternary operator and used to
evaluate Boolean expression
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 :
Otherwise value expr3
instanceOf operator
This operator is used for object reference variables.
The operator checks whether the object is of
particular type (class type or interface type)
Class
In Java everything is encapsulated under classes.
Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the
behaviors /states of a particular entity. A class
defines new data type. Once defined this new type
can be used to create object of that type. Object is
an instance of class. You may also call it as physical
existence of a logical template class.
A class is declared using class keyword. A class
contain both data and code that operate on that
data. The data or variables defined within
a class are called instance variables and the code
that operates on this data is known as methods.
Thus, the instance variables and methods are
known as class members. class is also known as a
user defined datatype.
A class and an object can be related as
follows: Consider an ice tray(like of cube shape) as
a class. Then ice cubes can be considered as the
objects which is a blueprint of its class i.e of ice tray.
Methods in Java
Method describe behavior of an object. A method is
a collection of statements that are group together to
perform an operation.
Syntax :
return-type methodName(parameter-list)
{
//body of method
}
Example of a Method
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We
will discuss it in detail later.
Return Type : A method may return value. Data
type of value return by a method is declare in
method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines
what method does.
Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
Output :
50
Method overloading
If two or more method in a class have same name
but different parameters, it is known as method
overloading. Overloading always occur in the same
class(unlike method overriding).
Method overloading is one of the ways through
which java supports polymorphism. Method
overloading can be done by changing number of
arguments or by changing the data type of
arguments. If two or more method have same name
and same parameter list but differs in return type
are not said to be overloaded method
Note: Overloaded method can have different access
modifiers.
Constructors in Java
A constructor is a special method that is used to
initialize an object.Every class has a constructor,if
we don't explicitly declare a constructor for any java
class the compiler builds a default constructor for
that class. A constructor does not have any return
type.
A constructor has same name as the class in which
it resides. Constructor in Java can not be abstract,
static, final or synchronized. These modifiers are not
allowed for constructor.
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Constructor Overloading
Like methods, a constructor can also be overloaded.
Overloaded constructors are differentiated on the
basis of their type of parameters or number of
parameters. Constructor overloading is not much
different than method overloading. In case of
method overloading you have multiple methods with
same name but different signature, whereas in
Constructor overloading you have multiple
constructor with different signature but only
difference is that Constructor doesn't have return
type in Java.
Class test:
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("sachin", "India",
32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}
output:
this is sachin of india
this is sachin of india
this is virat of india
this keyword
this keyword is used to refer to current object.
this is always a reference to the object on which
method was invoked.
this can be used to invoke current class
constructor.
this can be passed as an argument to another
method.
Example :
class Box
{
Double width, height, depth;
Box (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
}
Here the this is used to initialize member of current
object. Such as, this.width refers to the variable
width of the current object that has invoked the
constructor. width only refers to the parameter
received in the constructor i.e the argument passed
while calling the constructor.
Garbage Collection
In Java destruction of object from memory is done
automatically by the JVM. When there is no
reference to an object, then that object is assumed
to be no longer needed and the memory occupied
by the object are released. This technique is
called Garbage Collection. This is accomplished by
the JVM.
Unlike C++ there is no explicit need to destroy
object.
finalize() method
Sometime an object will need to perform some
specific task before it is destroyed such as closing
an open connection or releasing any resources held.
To handle such situation finalize() method is
used. finalize() method is called by garbage
collection thread before collecting object. Its the last
chance for any object to perform cleanup utility.
Signature of finalize() method
protected void finalize()
{
//finalize-code
}
gc() Method
gc() method is used to call garbage collector
explicitly. However gc() method does not guarantee
that JVM will perform the garbage collection. It only
request the JVM for garbage collection. This method
is present in System and Runtime class.
Modifiers in Java
Modifiers are keywords that are added to change
meaning of a definition. In Java, modifiers are
catagorized into two types,
1.Access control modifier
2.Non Access Modifier
2) Non-access Modifier
Non-access modifiers do not change the
accessibility of variables and methods, but they do
provide them special properties. Non-access
modifiers are of 5 types,
1.Final
2.Static
3.Transient
4.Synchronized
5.Volatile
Final
Final modifier is used to declare a field as final i.e. it
prevents its content from being modified. Final field
must be initialized when it is declared. Final keyword
can be used with a variable, a method or a class.
1.Final Variable
When a variable is declared as final, then its value
cannot be changed. The variable acts like a
constant.
Syntax:
final int a = 5;
2.Final Method
When a method is declared as final, then that
method cannot be overridden.
Example:
class Profound{
final void learn(){System.out.println("learning
something
new");}
}
Static Modifier
Static Modifiers are used to create class variable
and class methods which can be accessed without
instance of a class. Lets study how it works with
variables and member functions.
Static with Variables
Static variables are defined as a class member
that can be accessed without any object of that
class. Static variable has only one single storage.
All the object of the class having static variable will
have the same instance of static variable. Static
variables are initialized only once.
Static variable are used to represent common
property of a class. It saves memory. Suppose
there are 100 employee in a company. All
employee have its unique name and employee id
but company name will be same all 100 employee.
Here company name is the common property. So
if you create a class to store employee detail,
company_name field will be mark as static.
Example
class Employee
{
int e_id;
String name;
static String company_name = "Profound";
}
}
Output :
104 Abhijit Profound
108 ankit Profound
Static variable vs Instance Variable
Static variable Instance Variable
Static Method
A method can also be declared as static. Static
methods do not need instance of its class for
being accessed. main() method is the most
common example of static method. main() method
is declared as static because it is called before
any object of the class is created.
Example :
class Test
{
Static block
Static block is used to initialize static data
member. Static block executes
before main() method.
Example
class ST_Employee
{
int eid;
String name;
static String company_name;
static {
company_name ="Profound"; //static block
invoked before main() method
}
}
Output :
104 Abhijit Profound
Transient modifier
When an instance variable is declared as
transient, then its value doesn't persist when an
object is serialized
Synchronized modifier
When a method is synchronized it can be
accessed by only one thread at a time. We will
discuss it in detail in Thread.
Volatile modifier
Volatile modifier tells the compiler that the volatile
variable can be changed unexpectedly by other
parts of your program. Volatile variables are used
in case of multithreading
program. volatile keyword cannot be used with a
method or a class. It can be only used with a
variable.
Inheritance (IS-A)
Inheritance is one of the key features of Object
Oriented Programming. Inheritance provided
mechanism that allowed a class to inherit property
of another class. When a Class extends another
class it inherits all non-private members including
fields and methods. Inheritance in Java can be best
understood in terms of Parent and Child relationship,
also known as Super class(Parent) and Sub
class(child) in Java language.
Inheritance defines is-a relationship between a
Super class and its Sub
class. extends and implementskeywords are used to
describe inheritance in Java.
Purpose of Inheritance
1.It promotes the code reusabilty i.e the same
methods and variables which are defined in a
parent/super/base class can be used in the
child/sub/derived class.
2.It promotes polymorphism by allowing method
overriding.
Disadvantages of Inheritance
Main disadvantage of using inheritance is that the
two classes (parent and child class) gets tightly
coupled.
This means that if we change code of parent class, it
will affect to all the child classes which is
inheriting/deriving the parent class, and hence, it
cannot be independent of each other.
String modelType;
public void showDetail()
{
vehicleType = "Car"; //accessing
Vehicle class member
modelType = "sports";
System.out.println(modelType+"
"+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car();
car.showDetail();
}
}
Output :
sports Car
Types of Inheritance
1.Single Inheritance
2.Multilevel Inheritance
3.Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to
parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Output :
Parent and Child
}
public class Child extends Parent {
String name;
Example
class Student
{
String name;
Address ad;
}
Here you can say that Student has-a Address.
Example of Aggregation
class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String place)
{
this.authorName=name;
this.age=age;
this.place=place;
}
public String getAuthorName()
{
return authorName;
}
public int getAge()
{
return age;
}
public String getPlace()
{
return place;
}
}
class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
this.name=n;
this.price=p;
this.auth=at;
}
public void showDetail()
{
System.out.println("Book is"+name);
System.out.println("price "+price);
System.out.println("Author is
"+auth.getAuthorName());
}
}
class Test
{
public static void main(String args[])
{
Author ath=new Author("Me",22,"India");
Book b=new Book("Java",550,ath);
b.showDetail();
}
}
Output :
Book is Java.
price is 550.
Author is me.
Method Overriding
When a method in a sub class has same name,
same number of arguments and same type
signature as a method in its super class, then the
method is known as overridden method. Method
overriding is also referred to as runtime
polymorphism. The key benefit of overriding is the
abitility to define method that's specific to a
particular subclass type.
Runtime Polymorphism or
Dynamic method dispatch
Dynamic method dispatch is a mechanism by which
a call to an overridden method is resolved at
runtime. This is how java implements runtime
polymorphism. When an overridden method is called
by a reference, java determines which version of
that method to execute based on the type of object it
refer to. In simple words the type of object which it
referred determines which version of overridden
method will be called.
Upcasting
When Parent class reference variable refers
to Child class object, it is known as Upcasting
Example
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
instanceof operator
In Java, instanceof operator is used to check the
type of an object at runtime. It is the means by which
your program can obtain run-time type information
about an object. instanceof operator is also
important in case of casting object at
runtime. instanceof operator return boolean value, if
an object reference is of specified type then it
return true otherwise false.
Example of instanceOf
public class Test
{
public static void main(String[] args)
{
Test t= new Test();
System.out.println(t instanceof Test);
}
}
Output :
true
Downcasting
Example of downcasting
with instanceof operator
class Parent{ }
Child.show(p);
}
}
Output :
Sucessfull Casting
class Test
{
public static void main(String[] args)
{
Parent p =new Parent();
Child1 c1 = new Child1();
Child2 c2 = new Child2();
p = c1;
System.out.println(p instanceof Child1);
//true
System.out.println(p instanceof Child2);
//false
p = c2;
System.out.println(p instanceof Child1);
//false
System.out.println(p instanceof Child2);
//true
}
Output :
true
true
false
false
true
false
false
true
A Wrapper class is a class whose object wraps or contains a primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store a primitive
data types. In other words, we can wrap a primitive value into a wrapper class object
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Integer myInt = 5;
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
Example
public class MyClass {
public static void main(String[] args) {
System.out.println(myString.length());
Java Package
Package are used in Java, in-order to avoid name
conflicts and to control access of class, interface and
enumeration etc. A package can be defined as a
group of similar types of classes, interface,
enumeration and sub-package. Using package it
becomes easier to locate the related classes.
import keyword
import keyword is used to import built-in and user-
defined packages into your java source file so that
your class can refer to a class that is in another
package by directly using its name.
There are 3 different ways to refer to class that is
present in different package
1.Using fully qualified name(But this is not a
good practice.)
If you use fully qualified name then only declared
class of this package will be accessible. Now there
is no need to import. But you need to use fully
qualified name every time when you are accessing
the class or interface.
It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
Example :
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully
qualified name
obj.msg();
}
}
Output:
Hello
Points to remember
When a package name is not specified , a class is
defined into the default package (the current
working directory) and the package itself is given
no name. Hence you were able to execute
assignments earlier.
While creating a package, care should be taken
that the statement for creating package must be
written before any other import statements.
// not allowed
import package p1.*;
package p3;
//correct syntax
package p3;
import package p1.*;
Abstract class
If a class contain any abstract method then the class
is declared as abstract class. An abstract class is
never instantiated. It is used to provide abstraction.
Although it does not provide 100% abstraction
because it can also have concrete method.
Syntax :
abstract class class_name { }
Abstract method
Method that are declared without any body within an
abstract class are called abstract method. The
method body will be defined by its subclass.
Abstract method can never be final and static. Any
class that extends an abstract class must implement
all the abstract methods declared by the super class.
Syntax :
abstract return_type function_name (); // No
definition
this is callme.
this is concrete method.
Points to Remember
1.Abstract classes are not Interfaces. They are
different, we will study this when we will study
Interfaces.
2.An abstract class may or may not have an abstract
method. But if any class has even a single
abstract method, then it must be declared
abstract.
3.Abstract classes can have Constructors, Member
variables and Normal methods.
4.Abstract classes are never instantiated.
5.When you extend Abstract class with abstract
method, you must define the abstract method in
the child class, or make the child class abstract.
Interface
Interface is a pure abstract class.They are
syntactically similar to classes, but you cannot
create instance of an Interface and their methods
are declared without any body. Interface is used to
achieve complete abstraction in Java. When you
create an interface it defines what a class can do
without saying anything about how the class will do
it.
Syntax :
interface interface_name { }
Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
NOTE : Compiler automatically converts methods of
Interface as public and abstract, and the data
members as public, static and final by default.
interface Rollable
{
boolean isRollable
}
boolean isMoveable()
{
return true;
}
boolean isRollable()
{
return true;
}
public static void main(String args[])
{
Tyre tr=new Tyre();
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
}
}
Output :
true
true
Nested Class
A class within another class is known as Nested
class. The scope of the nested is bounded by the
scope of its enclosing class.
Static Nested Class
A satic nested class is the one that
has static modifier applied. Because it is static it
cannot refer to non-static members of its enclosing
class directly. Because of this restriction static
nested class is seldom used.
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output :
Inside inner
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output :
Inside inner 0
Inside inner 1
Inside inner 2
Inside inner 3
Inside inner 4
class Inner
{
public void show()
{
System.out.println("Inside inner "+(++count));
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
Outer.Inner in= ot.new Inner();
in.show();
}
}
Output :
Inside inner 1
Annonymous class
A class without any name is called Annonymous
class.
interface Animal
{
void type();
}
public class ATest {
public static void main(String args[])
{
Animal an = new Animal(){ //Annonymous
class created
public void type()
{
System.out.println("Annonymous animal");
}
};
an.type();
}
}
Output :
Annonymous animal
Here a class is created which
implements Animal interace and its name will be
decided by the compiler. This annonymous class will
provide implementation of type() method.
Introduction to String
Handling
String is probably the most commonly used class in
java library. String class is encapsulated
under java.langpackage. 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.
Concatenating String
There are 2 methods to concatenate two or more
string.
1.Using concat() method
2.Using + operator
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 == 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
Reason:
Its because we are creating a new object using new
operator, and thus it gets created in a non-pool
memory area of the heap. s1 is pointing to the String
in string pool while s3 is pointing to the String in
heap and hence, when we compare s1 and s3, the
answer is false.
The following image will explain it more clearly.
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
equalsIgnoreCase()
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()
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 Profound {
public static void main(String[] args) {
String str="Profound";
System.out.println(str.indexOf('u')); //1st form
System.out.println(str.indexOf('t',
3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //3rd
form
System.out.println(str.indexOf(subString,7)); //4th
form
}
}
Output:
2
11
5
-1
Note: -1 indicates that the substring/Character is
not found in the given String.
length()
length() function returns the number of characters
in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
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()
substring() method returns a part of the
string. substring() method has two forms,
public String substring(int begin);
toLowerCase()
toLowerCase() method returns string with all
uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
toUpperCase()
This method returns string with all lowercase
character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
valueOf()
Overloaded version of valueOf() method is present
in String class for all primitive data types and for
type Object.
NOTE : valueOf() function is used to
convert primitive data types into Strings.
public class Example{
public static void main(String args[]){
int num=35;
String s1=String.valueOf(num); //converting int to
String
System.out.println(s1+"IAmAString");
}}
Output: 35IAmAString
But for objects, valueOf() method
calls toString() function.
toString()
toString() method returns the string
representation of the object used to invoke this
method. toString() is used to represent any Java
Object into a meaningful string representation. It is
declared in the Object class, hence can be
overrided by any java class. (Object class is super
class of all java classes.)
public class Car {
public static void main(String args[])
{
Car c=new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}
Output : This is my car object
Whenever we will try to print any object of class
Car, its toString() function will be called. toString()
can also be used with normal string objects.
String str = "Hello World";
System.out.println(str.toString());
Output : Hello World
Note: If we don't override the toString() method
and directly print the object, then it would print the
object id.
Example:
trim()
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 = "profound"; then
System.out.println(s1.trim()); will output "study
tonight".
trim() method removes only the leading and
trailing whitespaces.
StringBuffer class
StringBuffer class is used to create a mutable string
object i.e its state can be changed after it is created.
It represents growable and writable character
sequence. As we know that String objects are
immutable, so if we do a lot of changes
with String objects, we will end up with a lot of
memory leak.
So StringBuffer class is used when we have to
make lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it
simultaneously. StringBuffer defines 4 constructors.
They are,
1.StringBuffer ( )
2.StringBuffer ( int size )
3.StringBuffer ( String str )
4.StringBuffer ( charSequence [ ]ch )
StringBuffer append(int n)
insert()
This method inserts one string into another. Here
are few forms of insert() method.
StringBuffer insert(int index, String str)
reverse()
This method reverses the characters within
a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
Output : olleH
replace()
This method replaces the string from specified start
index to the end index.
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
Output : Hello java
capacity()
This method returns the current capacity
of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
Output : 16
Note: Empty constructor reserves space for 16
characters. Therefore the output is 16.
ensureCapacity()
This method is used to ensure minimum capacity
of StringBuffer object.
If the argument of the ensureCapacity() method is
less than the existing capacity, then there will be no
change in existing capacity.
If the argument of the ensureCapacity() method is
greater than the existing capacity, then there will be
change in the current capacity using following
rule: newCapacity = (oldCapacity*2) + 2.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity()); //output: 16
(since empty constructor reserves space for 16
characters)
str.ensureCapacity(30); //greater than the existing
capacity
System.out.println( str.capacity()); //output: 34 (by
following the rule - (oldcapacity*2) + 2.) i.e
(16*2)+2 = 34.
StringBuilder class
StringBuilder is identical to StringBuffer except for
one important difference that it is not synchronized,
which means it is not thread safe. Its because
StringBuilder methods are not synchronised.
StringBuilder Constructors
1.StringBuilder ( ), creates an empty StringBuilder
and reserves room for 16 characters.
2.StringBuilder ( int size ), create an empty string
and takes an integer argument to set capacity of
the buffer.
3.StringBuilder ( String str ), create a StringBuilder
object and initialize it with string str.
Difference between StringBuffer and
StringBuilder class
StringBuffer class StringBuilder
class
Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("study");
str.append( "tonight" );
System.out.println(str);
str.replace( 6, 13, "today");
System.out.println(str);
str.reverse();
System.out.println(str);
str.replace( 6, 13, "today");
}
}
Output :
studytonight
studyttoday
yadottyduts
Exception Handling
Exception Handling is the mechanism to handle
runtime malfunctions. We need to handle such
exceptions to prevent abrupt termination of program.
The term exception means exceptional condition, it
is a problem that may arise during the execution of
program. A bunch of things can lead to exceptions,
including programmer error, hardware failures, files
that need to be opened cannot be found, resource
exhaustion etc.
Exception
A Java Exception is an object that describes the
exception that occurs in a program. When an
exceptional events occurs in java, an exception is
said to be thrown. The code that's responsible for
doing something about the exception is called
an exception handler.
Uncaught Exceptions
When we don't handle the exceptions, they lead to
unexpected program termination. Lets take an
example for better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to
exception
}
}
This will lead to an exception at runtime, hence the
Java run-time system will construct an exception
and then throw it. As we don't have any mechanism
for handling exception in the above program, hence
the default handler will handle the exception and will
print the details of the exception on the terminal.
Exception Handling
Mechanism
In java, exception handling is done using five
keywords,
1.try
2.catch
3.throw
4.throws
5.finally
Exception handling is done by transferring the
execution of a program to an appropriate exception
handler when exception occurs.
Points to Remember
1.A resource is an object in a program that must be
closed after the program has finished.
2.Any object that implements
java.lang.AutoCloseable or java.io.Closeable can
be passed as a parameter to try statement.
3.All the resources declared in the try-with-
resources statement will be closed automatically
when the try block exits. There is no need to close
it explicitly.
4.We can write more than one resources in the try
statement.
5.In a try-with-resources statement, any catch or
finally block is run after the resources declared
have been closed.
throw Keyword
throw keyword is used to throw an exception
explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on
encountering throw statement, and the closest
catch statement is checked for matching type of
exception.
Syntax :
throw ThrowableInstance
throws Keyword
Any method that is capable of causing exceptions
must list all the exceptions possible during its
execution, so that anyone calling that method gets a
prior knowledge about which exceptions are to be
handled. A method can do so by using
the throws keyword.
Syntax :
type method_name(parameter_list) throws
exception_list
{
//definition of method
}
finally clause
A finally keyword is used to create a block of code
that follows a try block. A finally block of code is
always executed whether an exception has occurred
or not. Using a finally block, it lets you run any
cleanup type statements that you want to execute,
no matter what happens in the protected code. A
finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+
a[3]);
/* the above statement will throw
ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Output :
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array
Index out of bound exception.
You can see in above example even if exception is
thrown by the program, which is not handled by
catch block, still finally block will get executed.
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of
user-defined exception class
}
else
{
System.out.println(a+b);
}
}
Points to Remember
1.Extend the Exception class to create your own
exception class.
2.You don't have to implement anything inside it, no
methods are required.
3.You can have a Constructor if you want.
4.You can override the toString() function, to display
customized message.
Chained Exception
Chained Exception was added to Java in JDK 1.4.
This feature allow you to relate one exception with
another exception, i.e one exception describes
cause of another exception. For example, consider a
situation in which a method throws
an ArithmeticException because of an attempt to
divide by zero but the actual cause of exception was
an I/O error which caused the divisor to be zero. The
method will throw only ArithmeticException to the
caller. So the caller would not come to know about
the actual cause of exception. Chained Exception is
used in such type of situations.
Two new constructors and two new methods were
added to Throwable class to support chained
exception.
1.Throwable( Throwable cause )
2.Throwable( String str, Throwable cause )
In the first form, the paramter cause specifies the
actual cause of exception. In the second form, it
allows us to add an exception description in string
form with the actual cause of exception.
getCause() and initCause() are the two methods
added to Throwable class.
getCause() method returns the actual cause
associated with current exception.
initCause() set an underlying cause(exception)
with invoking exception.
Example
import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new
ArithmeticException("top layer");
ae.initCause( new IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);
}
}
Thread Priorities
Every thread has a priority that helps the operating
system determine the order in which threads are
scheduled for execution. In java thread priority
ranges between 1 to 10,
MIN-PRIORITY (a constant of 1)
MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-
PRIORITY(5). The main thread always have NORM-
PRIORITY.
Note: Thread priorities cannot guarantee that a
higher priority thread will always be executed first
than the lower priority thread. The selection of the
threads for execution depends upon the thread
scheduler which is platform dependent.
Thread Class
Thread class is the main class on which Java's
Multithreading system is based. Thread class, along
with its companion interface Runnable will be used
to create and run threads for utilizing Multithreading
feature of Java.
Method Description
Creating a thread
Java defines two ways by which a thread can be
created.
By implementing the Runnable interface.
By extending the Thread class.
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output :
concurrent thread started running..
To call the run() method, start() method is used. On
calling start(), a new stack is provided to the thread
and run() method is called to introduce the new
thread into the program.
Note: If you are implementing Runnable interface in
your class, then you need to explicitly create a
Thread class object and need to pass the Runnable
interface implemented class object as a parameter
in its constructor.
Joining threads
Sometimes one thread needs to know when another
thread is ending. In java, isAlive() and join() are two
different methods to check whether a thread has
finished its execution.
The isAlive() method returns true if the thread upon
which it is called is still running otherwise it
returns false.
final boolean isAlive()
But, join() method is used more commonly
than isAlive(). This method waits until the thread on
which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until
the specified thread completes its execution. There
are overloaded versions of join() method, which
allows us to specify time for which you want to wait
for the specified thread to terminate.
final void join(long milliseconds) throws
InterruptedException
Example of isAlive method
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output :
r1
true
true
r1
r2
r2
Example of thread
without join() method
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
Output :
r1
r1
r2
r2
In this above program two thread t1 and t2 are
created. t1 starts first and after printing "r1" on
console thread t1 goes to sleep for 500 ms. At the
same time Thread t2 will start its process and print
"r1" on console and then go into sleep for 500 ms.
Thread t1 will wake up from sleep and print "r2" on
console similarly thread t2 will wake up from sleep
and print "r2" on console. So you will get output
like r1 r1 r2 r2
try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}
t2.start();
}
}
Output :
r1
r2
r1
r2
In this above program join() method on thread t1
ensures that t1 finishes it process before thread t2
starts.
Synchronization
At times when more than one thread try to access a
shared resource, we need to ensure that resource
will be used by only one thread at a time. The
process by which this is achieved is
called synchronization. The synchronization
keyword in java creates a block of code referred to
as critical section.
Every Java object with a critical section of code gets
a lock associated with the object. To enter critical
section a thread need to obtain the corresponding
object's lock.
General Syntax :
synchronized (object)
{
//statement to be synchronized
}
Synchronized Keyword
To synchronize above program, we
must serialize access to the
shared display() method, making it available to only
one thread at a time. This is done by using
keyword synchronized with display() method.
synchronized void display (String msg)
Interthread
Communication
Java provide benefit of avoiding thread pooling using
interthread communication.
The wait(), notify(), notifyAll() of Object class.
These method are implemented as final in Object.
All three method can be called only from within
a synchronized context.
wait() tells calling thread to give up monitor and go
to sleep until some other thread enters the same
monitor and call notify.
notify() wakes up a thread that called wait() on
same object.
notifyAll() wakes up all the thread that called
wait() on same object.
class Customer
{
int amount=0;
int flag=0;
public synchronized int withdraw(int
amount)
{
System.out.println(Thread.currentThrea
d().getName()+" is going to withdraw");
if(flag==0)
{
try{
System.out.println("waiting....");
wait();
}catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw
completed");
return amount;
}
System.out.println(Thread.currentThrea
d().getName()+" is going to deposit");
this.amount+=amount;
notifyAll();
System.out.println("deposit
completed");
flag=1;
}
t1.start();
t2.start();
}
}
Thread Pooling
Pooling is usually implemented by loop i.e to check
some condition repeatedly. Once condition is true
appropriate action is taken. This waste CPU time.
Deadlock
Deadlock is a situation of complete Lock, when no
thread can complete its execution because lack of
resources. In the above picture, Thread 1 is holding
a resource R1, and need another resource R2 to
finish execution, but R2 is locked by Thread 2, which
needs R3, which in turn is locked by Thread 3.
Hence none of them can finish and are stuck in a
deadlock.
Example of deadlock
class Pen{}
class Paper{}
}
}
};
Thread t2 = new Thread(){
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is
holding Paper");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pn)
{ System.out.println("requesting for
Pen"); }
}
}
};
t1.start();
t2.start();
}
}
Output :
Thread1 is holding Pen
Thread2 is holding Paper
Enumerations
Enumerations was added to Java language in
JDK5. Enumeration means a list of named
constant. In Java, enumeration defines a class type.
An Enumeration can have constructors, methods
and instance variables. It is created
using enum keyword. Each enumeration constant
is public, static and final by default. Even though
enumeration defines a class type and have
constructors, you do not instantiate
an enum using new. Enumeration variables are
used and declared in much a same way as you do a
primitive variable.
Example of Enumeration
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }
class Test
{
public static void main(String args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is "+wk);
}
}
Output :
Today is sun
class EnumDemo
{
public static void main( String args[] )
{
Student S;
System.out.println("Age of Viraaj is "
+Student.Viraaj.getage()+ "years");
}
}
Output :
Age of Viraaj is 9 years
In this example as soon as we declare an enum
variable(Student S), the constructor is called once,
and it initializes age for every enumeration constant
with values specified with them in parenthesis.
type wrapper
Java uses primitive types such as int, double or float
to hold the basic data types for the sake of
performance. Despite the performance benefits
offered by the primitive types, there are situation
when you will need an object representation. For
example, many data structures in Java operate on
objects, so you cannot use primitive types with those
data structures. To handle these situations Java
provides type Wrappers which provide classes that
encapsulate a primitive type within an object.
Character : It encapsulates primitive type char
within object.
Character (char ch)
Boolean : It encapsulates primitive type boolean
within object.
Boolean (boolean boolValue)
Numeric type wrappers : It is the most commonly
used type wrapper.
IO Stream
Java performs I/O through Streams. A Stream is
linked to a physical layer by java I/O system to make
input and output operation in java. In general, a
stream means continuous flow of data. Streams are
clean way to deal with input/output without having
every part of your code understand the physical.
Java encapsulates Stream under java.io package.
Java defines two types of streams. They are,
1.Byte Stream : It provides a convenient means for
handling input and output of byte.
2.Character Stream : It provides a convenient
means for handling input and output of characters.
Character stream uses Unicode and therefore can
be internationalized.
Reading Characters
read() method is used with BufferedReader object
to read characters. As this function returns integer
type value has we need to use typecasting to
convert it into char type.
int read() throws IOException
Below is a simple example explaining character
input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new
InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function
with BufferedReader class's object.
String readLine() throws IOException
Serialization and
Deserialization in Java
Serialization is a process of converting an object
into a sequence of bytes which can be persisted to a
disk or database or can be sent through streams.
The reverse process of creating object from
sequence of bytes is called deserialization.
A class must implement Serializable interface
present in java.io package in order to serialize its
object successfully. Serializable is a marker
interface that adds serializable behaviour to the
class implementing it.
Java provides Serializable API encapsulated
under java.io package for serializing and
deserializing objects which include,
java.io.serializable
java.io.Externalizable
ObjectInputStream
and ObjectOutputStream etc.
Marker interface
Marker Interface is a special interface in Java
without any field and method. Marker interface is
used to inform compiler that the class implementing
it has some special behaviour or meaning. Some
example of Marker interface are,
java.io.Serializable
java.lang.Cloneable
java.rmi.Remote
java.util.RandomAccess
All these interfaces does not have any method and
field. They only add special behavior to the classes
implementing them. However marker interfaces have
been deprecated since Java 5, they were replaced
by Annotations. Annotations are used in place of
Marker Interface that play the exact same role as
marker interfaces did before.
Signature
of writeObject() and readObject()
writeObject() method of ObjectOutputStream class
serializes an object and send it to the output stream.
public final void writeObject(object x) throws
IOException
readObject() method of ObjectInputStream class
references object out of stream and deserialize it.
public final Object readObject() throws
IOException,ClassNotFoundException
while serializing if you do not want any field to be
part of object state then declare it either static or
transient based on your need and it will not be
included during java serialization process.
Serializing an Object
import java.io.*;
class studentinfo implements Serializable
{
String name;
int rid;
static String contact;
studentinfo(String n, int r, String c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}
class Test
{
public static void main(String[] args)
{
try
{
studentinfo si = new studentinfo("Abhi", 104,
"110044");
FileOutputStream fos = new
FileOutputStream("student.ser");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(si);
oos.close();
fos.close();
}
catch (Exception e)
{ e. printStackTrace(); }
}
}
Deserialization of Object
import java.io.* ;
class DeserializationTest
{
public static void main(String[] args)
{
studentinfo si=null ;
try
{
FileInputStream fis = new
FileInputStream("student.ser");
ObjectInputStream ois = new
ObjectInputStream(fis);
si = (studentinfo)ois.readObject();
}
catch (Exception e)
{ e.printStackTrace(); }
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
}
Output :
Abhi
104
null
Contact field is null because,it was marked as static
and as we have discussed earlier static fields does
not get serialized.
NOTE : Static members are never serialized
because they are connected to class not object of
class.
transient Keyword
While serializing an object, if we don't want certain
data member of the object to be serialized we can
mention it transient. transient keyword will prevent
that data member from being serialized.
class studentinfo implements Serializable
{
String name;
transient int rid;
static String contact;
}
Networking in Java
Java is a premier language for network
programming. java.net package encapsulate large
number of classes and interface that provides an
easy-to use means to access network resources.
Here are some important classes and interfaces of
java.net package.
Some Important Classes
CLASSES
CacheRequest CookieHandler
CookieManager Datagrampacket
Socket DatagramSocket
Proxy URL
URLConnection
CookiePolicy CookieStore
FileNameMap SocketOption
InetAddress ServerSocket
SocketImplFactory ProtocolFamily
InetAddress
Inet Address encapsulates both numerical IP
address and the domain name for that address. Inet
address can handle both IPv4 and Ipv6 addresses.
Inet Address class has no visible constructor. To
create an inet Address object, you have to
use Factory methods.
Three commonly used Inet Address factory methods
are.
1.static InetAddress getLocalHost() throws Unkno
wnHostException
2.static InetAddress getByName (String hostname)
throws UnknownHostException
3.static InetAddress[ ] getAllByName (String
hostname) throws UnknownHostException
Example using InetAddress class
import java.net.*;
class Test
{
public static void main(String[] args)
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address =
InetAddress.getByName("www.studyProfound.com");
System.out.println(address);
InetAddress sw[] =
InetAddress.getAllByName("www.google.com");
for(int i=0; i< sw.length; i++)
{
System.out.println(sw[i]);
}
}
}
Output:
Welcome-PC/59.161.87.227
www.studyProfound.com/208.91.198.55
www.google.com/74.125.236.115
www.google.com/74.125.236.116
www.google.com/74.125.236.112
www.google.com/74.125.236.113
www.google.com/74.125.236.114
www.google.com/2404:6800:4009:802:0:0:0:1014
URL class
Java URL Class present in java.net package, deals
with URL (Uniform Resource Locator) which
uniquely identify or locate resources on internet.
Generics
A class or interface that operates on parameterized
type is called Generic. Generics was first introduced
in Java5. Now it is one of the most profound feature
of java programming language. It provides facility to
write algorithm independent of any specific type of
data. Generics also provide type safety.
Using Generics, it becomes possible to create a
single class or method that automatically works with
all types of data(Integer, String, Float etc). It
expanded the ability to reuse code safely and easily.
class Test
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance
of Integer type Gen Class.
int x = iob.getOb();
System.out.print in(x);
Gen < String> sob = new Gen<>("Hello"); //instance
of String type Gen Class.
String str = sob.getOb();
}
}
Output :
100
Hello
Generic Methods
You can also create generic methods that can be
called with different types of arguments based on
the type of arguments passed to generic method,
the compiler handles each method.
Generic Constructors
It is possible to create a generic constructor even if
the class is not generic.
Example of Generic Constructor
class Gen
{
private double val;
< T extends Number> Gen(T ob)
{
val=ob.doubleValue();
}
void show()
{
System.out.println(val);
}
}
class Test
{
public static void main(String[] args)
{
Gen g = new Gen(100);
Gen g1 = new Gen(121.5f);
g.show();
g1.show();
}
}
Output :
100.0
121.5
Generic Interface
Like classes and methods, you can also create
generic interfaces.
interface MyInterface< T >
{ .. }
Collection Framework
Collection framework was not part of original
Java release. Collections was added to J2SE
1.2. Prior to Java 2, Java provided adhoc
classes such as Dictionary, Vector, Stack and
Properties to store and manipulate groups of
objects. Collection framework provides many
important classes and interfaces to collect and
organize group of alike objects.
Collection Heirarchy
All these Interfaces give several methods which
are defined by collections classes which
implement these interfaces.
Interfaces of Collection
Framework
The collection framework has a lot of Interfaces,
setting the fundamental nature of various collection
classes. Lets study the most important Interfaces in
the collection framework.
Methods Description
Methods Description
Methods Description
Example of ArrayList
import java.util.*
class Test
{
public static void main(String[] args)
{
ArrayList< String> al = new ArrayList< String>();
al.add("ab");
al.add("bc");
al.add("cd");
system.out.println(al);
}
}
Output :
[ab,bc,cd]
LinkedList class
1.LinkedList class
extends AbstractSequentialList and
implements List,Deque and Queue inteface.
2.It can be used as List, stack or Queue as it
implements all the related interfaces.
3.They are a dynamic in nature which allocates the
memory when required. Therefore insertion and
deletion operations can be easily implemented.
4.It can contain duplicate elements and is not
synchronized.
5.Reverse Traversing is difficult in linked list.
HashSet class
1.HashSet extends AbstractSet class and
implements the Set interface.
2.It creates a collection that uses hash table for
storage. A hash table stores information by
using a mechanism called hashing.
3.In hashing, the informational content of a key is
used to determine a unique value, called its
hash code. The hash code is then used as the
index at which the data associated with the key
is stored.
4.HashSet does not maintain any order of
elements.
LinkedHashSet Class
5.LinkedHashSet class extends HashSet class
6.LinkedHashSet maintains a linked list of entries
in the set.
7.LinkedHashSet stores elements in the order in
which elements are inserted.
TreeSet Class
8.It extends AbstractSet class and implements
the NavigableSet interface.
9.It stores elements sorted ascending order.
10. Uses a Tree structure to store elements.
11. Contains unique elements only like
HashSet.
12. Access and retrieval times are quite fast.
13. It has four Constructors.
TreeSet()
TreeSet( Collection C )
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :
Ajay
Ravi
Vijay
PriorityQueue Class
14. It extend the AbstractQueue class.
15. The PriorityQueue class provides the facility
of using queue.
16. It does not orders the elements in FIFO
manner.
Output :
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Accessing a Collection
To access, modify or remove any element from any
collection we need to first find the element, for which
we have to cycle throught the elements of the
collection. There are three possible ways to cycle
through the elements of any collection.
1.Using Iterator interface
2.Using ListIterator interface
3.Using for-each loop
Map Interface
A Map stores data in key and value association.
Both key and values are objects. The key must be
unique but the values can be duplicate. Although
Maps are a part of Collection Framework, they can
not actually be called as collections because of
some properties that they posses. However we can
obtain a collection-view of maps.
Interface Description
HashMap class
1.HashMap class extends AbstractMap and
implements Map interface.
2.It uses a hashtable to store the map. This allows
the execution time of get() and put() to remain
same.
3.HashMap has four constructor.
4.HashMap()
5.HashMap(Map< ? extends k, ? extends V> m)
6.HashMap(int capacity)
7.HashMap(int capacity, float fillratio)
8.HashMap does not maintain order of its element.
Example
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm = new HashMap<
String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));
TreeMap class
1.TreeMap class extends AbstractMap and
implements NavigableMap interface.
2.It creates Map, stored in a tree structure.
3.A TreeMap provides an efficient means of storing
key/value pair in efficient order.
4.It provides key/value pairs in sorted order and
allows rapid retrieval.
Example
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap< String,Integer> tm = new TreeMap<
String,Integer>();
tm.put("a",new Integer(100));
tm.put("b",new Integer(200));
tm.put("c",new Integer(300));
tm.put("d",new Integer(400));
LinkedHashMap class
1.LinkedHashMap extends HashMap class.
2.It maintains a linked list of entries in map in order
in which they are inserted.
3.LinkedHashMap defines the following constructor
4.LinkedHashMap()
5.
6.LinkedHashMap(Map< ? extends k, ? extends V> m)
7.
8.LinkedHashMap(int capacity)
9.
10. LinkedHashMap(int capacity, float fillratio)
11.
12. LinkedHashMap(int capacity, float fillratio,
boolean order)
13. It adds one new method removeEldestEntry().
This method is called by put() and putAll() By
default this method does nothing. However we can
override this method to remove oldest element in
the map. Syntax
14. protected boolean removeEldestEntry(Map.Entry e)
EnumMap class
1.EnumMap extends AbstractMap and
implements Map interface.
2.It is used for key as enum
3. Comparator Interface
4.In Java, Comparator interface is used to order
the object in your own way. It gives you ability to
decide how element are stored within sorted
collection and map.
5.Comparator Interface defines compare() method.
This method compare two object and return 0 if
two object are equal. It returns a positive value if
object1 is greater than object2. Otherwise a
negative value is return. The method can throw
a ClassCastException if the type of object are
not compatible for comparison.
6.
7. Example
8.Student class
9.class Student
10.int roll;
11. String name;
12. Student(int r,String n)
13. {
14. roll = r;
15. name = n;
16. }
17. public String toString()
18. {
19. return roll+" "+name;
20. }
21. MyComparator class
22. This class defines the comparison logic for
Student class based on their roll. Student object
will be sotred in ascending order of their roll.
23.class MyComparator implements Comparator
24.{
25. public int compare(Student s1,Student s2)
26. {
27. if(s1.roll == s2.roll) return 0;
28. else if(s1.roll > s2.roll) return 1;
29. else return -1;
30. }
31.}
32.public class Test
33.{
34.
35. public static void main(String[] args)
36. {
37. TreeSet< Student> ts = new TreeSet<
Student>(new MyComparator());
38. ts.add(new Student(45, "Rahul"));
39. ts.add(new Student(11, "Adam"));
40. ts.add(new Student(19, "Alex"));
41. System.out.println(ts);
42. }
43.
44.}
Output :
[ 11 Adam, 19 Alex, 45 Rahul ]
As you can see in the ouput Student object are
stored in ascending order of their roll.
Legacy Classes
Early version of java did not include
the Collection framework. It only defined
several classes and interface that provide
method for storing objects.
When Collection framework were added in
J2SE 1.2, the original classes were reengineered
to support the collection interface. These classes
are also known as Legacy classes. All legacy
claases and interface were redesign by JDK 5 to
support Generics.
The following are the legacy classes defined
by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface
called Enumeration
NOTE: All the legacy classes are syncronized
Enumeration interface
1. Enumeration interface defines method to
enumerate through collection of object.
2. This interface is suspended
by Iterator interface.
3. However some legacy classes such
as Vector and Properties defines several
method in which Enumeration interface is
used.
4. It specifies the following two methods
boolean hasMoreElements()
Object nextElement()
Vector class
1. Vector is similar to ArrayList which
represents a dynamic array.
2. The only difference
between Vector and ArrayList is that Vector
is synchronised while Array is not.
3. Vector class has following four constructor
4.Vector()
5.
6.Vector(int size)
7.
8.Vector(int size, int incr)
9.
10. Vector(Collection< ? extends E> c)
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
}
Output :
10
20
30
40
50
60
Hashtable class
1. Like HashMap, Hashtable also stores
key/value pair in hashtable. However
neither keys nor values can be null.
2. There is one more difference
between HashMap and Hashtable that is
Hashtable is synchronized while HashMap is
not.
3. Hashtable has following four constructor
4.Hashtable()
5.Hashtable(int size)
6.Hashtable(int size, float fillratio)
7.Hashtable(Map< ? extends K, ? extends V> m)
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable<
String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+"
"+itr.getValue());
}
}
}
Output:
a 100
b 200
c 300
d 400
Difference between HashMap and
Hashtable
Hashtable HashMap
Properties class
1. Properties class extends Hashtable class.
2. It is used to maintain list of value in which
both key and value are String
3. Properties class define two constructor
4.Properties()
5.Properties(Properties default)
6. One advantage
of Properties over Hashtable is that we can
specify a default property that will be useful
when no value is associated with a certain
key.
Output :
Java was created by James Ghosling
C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc
Applet in Java
Applets are small Java applications that can be
accessed on an Internet server, transported over
Internet, and can be automatically installed and
run as apart of a web document. Any applet in
Java is a class that extends
the java.applet.Applet class.
An Applet class does not have any main() method.
It is viewed using JVM. The JVM can use either a
plug-in of the Web browser or a separate runtime
environment to run an applet application.
JVM creates an instance of the applet class and
invokes init() method to initialize an Applet.
A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must declare
a paint() method. This method is defined
by AWT class and must be overridden by the
applet. paint() method is called each time an applet
neede to redisplay its output. Another important
thing to notice about applet application is that,
execution of an applet does not begin
at main()method. In fact an applet application does
not have any main() method.
Advantages of Applets
1.Very less response time as it works on the client
side.
2.Can be run using any browser, which has JVM
running in it.
Applet class
Applet class provides all necessary support for
applet execution, such as initializing and destroying
of applet. It also provide methods that load and
display images and methods that load and play
audio clips.
An Applet Skeleton
Most applets override these four methods. These
four methods forms Applet lifecycle.
init() : init() is the first method to be called. This is
where variable are initialized. This method is
called only once during the runtime of applet.
start() : start() method is called after init(). This
method is called to restart an applet after it has
been stopped.
stop() : stop() method is called to suspend thread
that does not need to run when applet is not
visible.
destroy() : destroy() method is called when your
applet needs to be removed completely from
memory.
AWT Hierarchy
Component class
Component class is at the top of AWT hierarchy.
Component is an abstract class that encapsulates all
attribute of visual component. A component object is
responsible for remembering the current foreground
and background colours and the currently selected
text font.
Container
Container is a component in AWT that contains
another component like button, text field, tables
etc. Container is a subclass of component
class. Conatiner class keeps track of components
that are added to another component.
Panel
Panel class is concrete sub class of Container.
Panel does not contain title bar, menu bar or border.
Window class
Window class creates a top level window. Window
does not have borders and menubar.
Frame
Frame is a sub class of Window and have resizing
canvas. It is a container that contain several different
components like button, title bar, textfield, label etc.
In Java, most of the AWT applications are created
using Frame window. Frame class has two different
constructors,
Frame() throws HeadlessException
Creating a Frame
There are two ways to create a Frame. They are,
1.By Instantiating Frame class
2.By extending Frame class
import java.awt.*;
import java.awt.event.*;
Features of JFC
Swing GUI components.
Look and Feel support.
Java 2D.
Creating a JFrame
There are two way to create a JFrame Window.
1.By instantiating JFrame class.
2.By extending JFrame class.
Swing Component
Swing Framework contains a large set of
components which provide rich functionalities and
allow high level of customization. All these
components are lightweight components. They all
are derived from JComponent class. It supports the
pluggable look and feel.
JButton
JButton class provides functionality of a button.
JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating
a Yes Button.
JButton bt2 = new JButton("No"); //Creating
a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
//setting close operation.
setLayout(new FlowLayout()); //setting layout
using FlowLayout object
setSize(400, 400); //setting size of
Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single line of
text. It is most widely used text component. It has
three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
cols represent the number of columns in text field.
Now instead of implementing an event listener interface, you can extend the
corresponding event adapter class and define only those methods in which you are
interested. For example, The following code segment shows that a class
MyWindowAdapter extends WindowAdapter and implements the windowClosing()
method.
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
This class can be registered using the following statement,
this.addWindowListener(new MyWindowAdapter());
However, if the class is a subclass of a Frame or Applet class, then you cannot define
the class as a subclass of WindowAdapter. In such a case, you can use inner classes. So
the preceding MyWindowAdapter class and addWindowListener statement replaced
with the following statements,
this.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}) ;
You can read this syntax as defining an anonymous inner class as a subclass
ofWindowAdapter, create an instance of this inner class and use this instance as an
argument to the addWindowListener () method.
The following program demonstrates how the adapter class is created and used.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class AdapterExample extends JFrame
{
AdapterExample()
{
this.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
class AdapterClassJavaExample
{
public static void main(String [] args)
{
AdapterExample frame = new AdapterExample();
frame.setTitle("Adapter Class Java Example");
frame.setBounds(100,200,200,200);
frame.setVisible(true);
}
}
Reflection API
Reflection means ability of a software to analyze
itself. In Java, Reflection API provides facility to
analyze and change runtime behaviour of a Class, at
runtime.
For example, using reflection at the runtime you can
determine what method, field, constructor or
modifers a class supports.
Uses of Reflection
Developing IDE
Debugging and Test tools
Loading drivers and providing dynamic information
Disadvantages of Reflection
Low performance
Security risk
Violation of Oops concept
java.lang.Class class
Class is a final class in java.lang package
which extends Object class. Instance of this
class represents classes and interfaces in a
running Java application. It is used to
analyze and change dynamic behaviour of a
class at runtime.
forName()
This method takes fully qualified name of
classes or interface as its argument and
returns instance of the class assocaited with
it. Syntax
static Class< ?> forName(String className)
Example using forName() method
class Student{}
class Test
{
public static void main(String args[])
{
Class c = Class.forName("Student");
System.out.println(c.getName());
}
}
Output :
Student
getConstructors() and
getDeclaredConstructors()
getConstructors() method returns array
of Constructors object that represent all the
public constructors of the invoking object.
Remember, this method only returns public
constructors. If you want to see all the
declared constructors of a class then
use getDeclaredConstructors(). Following is
the general syntax of both,
Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();
Example using getConstructors() and
getDeclaredConstructors() method
import java.lang.reflect.*;
class Student
{
public Student(){}
public Student(String name){}
}
class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("Student");
Constructor< Student>[] ct =
c.getConstructors();
for(int i=0; i< ct.length; i++)
{ System.out.println(ct[i]); }
Constructor< Student>[] cdt =
c.getDeclaredConstructors();
for(int i=0;i< cdt.length;i++)
{ System.out.println(cdt[i]);}
}
catch(Exception e)
{ e.printStackTrace();}
}
}
Output :
public Student()
public Student()
Student(java.lang.String)
getMethods() and
getDeclaredMethods()
getMethods() method returns array of Method
object that reflect all the public method of
invoking
object. getDeclaredMethods() returns only the
declared methods of the invoking class
object. Syntax for both is following,
Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();
RMI
Remote method invocation(RMI) allow a java
object to invoke method on an object running on
another machine. RMI provide remote
communication between java program. RMI is
used for building distributed application.
}catch(Exception e){System.out.println(e);}
}
}
JDBC-ODBC bridge
Type-1 Driver act as a bridge between JDBC and
other database connectivity mechanism(ODBC).
This driver converts JDBC calls into ODBC calls and
redirects the request to the ODBC driver.
Advantage
Easy to use
Allow easy connectivity to all database supported
by the ODBC Driver.
Disadvantage
Slow execution time
Dependent on ODBC Driver.
Uses Java Native Interface(JNI) to make ODBC
call.
Thin Driver
This is Driver called Pure Java Driver because. This
driver interact directly with database. It does not
require any native database library, that is why it is
also known as Thin Driver.
Advantage
Does not require any native library.
Does not require any Middleware server.
Better Performance than other driver.
Disadvantage
Slow due to increase number of network call.
javax.sql.DataSource Represent
the DataSource interfac
e used in an application.
Create a Connection
getConnection() method of DriverManager class is
used to create a connection.
Syntax
getConnection(String url)
getConnection(String url, String username, String
password)
getConnection(String url, Properties info)
Example establish connection with Oracle Driver
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","pa
ssword");
Connecting to Access
Database using Type-1
Driver
To connect a Java application with Access database
using JDBC-ODBC Bridge(type-1) Driver. You need
to follow the following steps
Example
We suppose that you have created a student table
with sid and name column name in access
database.
import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:Test", "",
"");
Statement s=con.createStatement(); //creating
statement
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Connecting to Oracle
Database using Thin Driver
To connect a Java application with Oracle database
using Thin Driver. You need to follow the following
steps
1.Load Driver Class: The Driver Class for oracle
database
is oracle.jdbc.driver.OracleDriver and Class.for
Name("oracle.jdbc.driver.OracleDriver") metho
d is used to load the driver class for Oracle
database.
2.Create Connection: For creating a connection
you will need a Connection URL. The Connection
URL for Oracle is
or,
2.Set it into classpath. For more detail see how to
set classpath
Download ojdbc14.jar file
NOTE: Here we are discussing about Oracle 10g as
database. For other version of Oracle you will be
require to do some small changes in the Connection
URL.
Example
Create a table in Oracle Database
create table Student(sid number(10),sname
varchar2(20));
//creating connection
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","pa
ssword");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
//creating connection...
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","username","pa
ssword");
PreparedStatement pst=con.prepareStatement("insert
into Student values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();
Connecting to MySQL
Database using Thin Driver
To connect a Java application with MySQL
database using Thin Driver. You need to follow
the following steps
1. Load Driver Class: The Driver Class for
MySQL database
is com.mysql.jdbc.Driver and Class.forName(
"com.mysql.jdbc.Driver") method is used to
load the driver class for MySQL database.
2. Create Connection: For creating a
connection you will need a Connection URL.
The Connection URL for MySQL is
You will also
require Username and Password of your
MySQL Database Server for creating
connection.
3. Loading jar file: To connect your java
application with MySQL, you will also need
to load mysql-connector.jar file. This file can
be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\
Java\jre7\lib\ext folder.
or,
2. Set it into classpath. For more detail
see how to set classpath
Download mysql-connector.jar file
Example
Create a table in MySQL Database
create table Student(sid int(10),name varchar(20));
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Output
102 adam
103 abhi
Inserting record into a table using java
application
import java.sql.*;
class Test
{
public static void main(String []args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver");
//creating connection
Connection con = DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
PreparedStatement pst=con.prepareStatement("insert
into Student values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();
Statement vs PreparedStatement
vs CallableStatement in java
Java Regex
The Java Regex or Regular Expression is an API to define a pattern for searching or
manipulating strings.
It is widely used to define the constraint on strings such as password and email validation.
After learning Java regex tutorial, you will be able to test your regular expressions by the
Java Regex Tester Tool.
java.util.regex package
The Matcher and Pattern classes provide the facility of Java regular expression. The
java.util.regex package provides following classes and interfaces for regular expressions.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
1st way
Pattern p = Pattern.compile(".s");
Matcher m = p.matcher("as");
boolean b = m.matches();
2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();
3rd way
boolean b3 = Pattern.matches(".s", "as");
The . (dot) represents a single character.
import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
}}
5 [a-z&&[def]] d, e, or f (intersection)
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
Regex Metacharacters
The regular expression metacharacters work as shortcodes.
Regex Description
\b A word boundary
}}
import java.util.regex.*;
class RegexExample6{
public static void main(String args[]){
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));//false (more than 6
char)
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));//false ($ is not matched
)
}}
import java.util.regex.*;
class RegexExample7{
public static void main(String args[]){
System.out.println("by character classes and quantifiers ...");
System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//true
System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));//true
}}