Java Concepts
Java Concepts
Java Concepts
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
What is JVM?
It is:
What it does?
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation.Here the term ?compiler? refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction set
of a specific CPU.
Variable
Variable is name of reserved area allocated in memory.
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
void method(){
int n=90;//local variable
}
}//end of class
false
1 bit
char
'\u0000'
2 byte
byte
1 byte
short
2 byte
int
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
ASCII (American Standard Code for Information Interchange) for the United
States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
Operators in java
Operator is a special symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.
Precedence of Operators
Operators
Precedence
postfix
expr++ expr--
unary
multiplicative
* / %
additive
+ -
shift
relational
equality
== !=
bitwise AND
&
bitwise exclusive OR
bitwise inclusive OR
logical AND
&&
logical OR
||
ternary
? :
assignment
Useful Programs:
There is given some useful programs such as factorial number, prime number, fibonacci
series etc.
It is better for the freshers to skip this topic and come to it after OOPs
concepts.
class Fabnoci{
}
}
System.out.println("armstrong number");
else
System.out.println("it is not an armstrong number");
}
}
n=a,b=a,rev=0;
while(n>0)
{
a=n%10;
rev=rev*10+a;
n=n/10;
}
if(rev==b)
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}
class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
return n*=fact(n-1);
}
int f=fact(5);
System.out.println(f);
}
}
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or rectangle
etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Do You Know ?
Advantage of OOPs
Naming Convention
Object and class
Method overloading
Constructor
static keyword
this keyword with 6 usage
Inheritance
Aggregation
Method Overriding
Covariant Return Type
super keyword
Instance Initializer block
final keyword
Abstract class
Interface
Runtime Polymorphism
Static and Dynamic Binding
Downcasting with instanceof operator
Package
Access Modifiers
Encapsulation
Object Cloning
Name
Convention
class name
should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface
should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name
ActionListener etc.
method name
should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable name
package
name
constants
name
6. Annonymous Object
In this page, we will learn about java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.
An object has three characteristics:
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.
data member
method
constructor
block
class and interface
Test it Now
Output:0 null
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student2 s1=new Student2();
14. Student2 s2=new Student2();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Test it Now
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both
By
By
By
By
new keyword
newInstance() method
clone() method
factory method etc.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4.
int fact=1;
5.
for(int i=1;i<=n;i++){
6.
fact=fact*i;
7.
}
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20. }
21. }
In java, Methood Overloading is not possible by changing the return type of the
method.
In this example, we have created two overloaded methods that differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
1. class Calculation2{
2.
void sum(int a,int b){System.out.println(a+b);}
3.
void sum(double a,double b){System.out.println(a+b);}
4.
5.
public static void main(String args[]){
6.
Calculation2 obj=new Calculation2();
7.
obj.sum(10.5,10.5);
8.
obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:21.0
40
As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.
60
Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
class Bike1{
Bike(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output: Bike is created
Parameterized constructor
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
by taking into account the number of parameters in the list and their type.
1. class Student5{
2.
int id;
3.
String name;
4.
int age;
5.
Student5(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
Student5(int i,String n,int a){
10.
id = i;
11.
name = n;
12.
age=a;
13.
}
14.
void display(){System.out.println(id+" "+name+" "+age);}
15.
16.
public static void main(String args[]){
17.
Student5 s1 = new Student5(111,"Karan");
18.
Student5 s2 = new Student5(222,"Aryan",25);
19.
s1.display();
20.
s2.display();
21. }
22. }
Test it Now
Output:111 Karan 0
222 Aryan 25
Constructor
Constructor is used to initialize the state of an object.
Method
Method is used to expose behaviour of
an object.
any case.
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using
constructor.
1. class Student6{
2.
int id;
3.
String name;
4.
Student6(int i,String n){
5.
id = i;
6.
name = n;
7.
}
8.
9.
Student6(Student s){
10.
id = s.id;
11.
name =s.name;
12.
}
13.
void display(){System.out.println(id+" "+name);}
14.
15.
public static void main(String args[]){
16.
Student6 s1 = new Student6(111,"Karan");
17.
Student6 s2 = new Student6(s1);
18.
s1.display();
19.
s2.display();
20. }
21. }
Test it Now
Output:111 Karan
111 Karan
We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
1. class Student7{
2.
int id;
3.
String name;
4.
Student7(int i,String n){
5.
id = i;
6.
name = n;
7.
}
8.
Student7(){}
9.
void display(){System.out.println(id+" "+name);}
10.
11.
public static void main(String args[]){
12.
Student7 s1 = new Student7(111,"Karan");
13.
Student7 s2 = new Student7();
14.
s2.id=s1.id;
15.
s2.name=s1.name;
16.
s1.display();
17.
s2.display();
18. }
19. }
Test it Now
Output:111 Karan
111 Karan
static keyword
1. Static variable
2. Program of counter without static variable
3. Program of counter with static variable
4. Static method
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees,college name of
students etc.
The static variable gets memory only once in class area at the time of class loading.
2) static method
If you apply static keyword with any method, it is known as static method
7.
8.
public static void main(String args[]){
9.
int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Test it Now
Output:125
3)static block
1. class A2{
2.
3.
static{System.out.println("static block is invoked");}
4.
5.
public static void main(String args[]){
6.
System.out.println("Hello main");
7.
}
8. }
Test it Now
Output:static block is invoked
Hello main
this keyword
1. this keyword
2. Usage of this keyword
1. to refer the current class instance variable
2. to invoke the current class constructor
3. to invoke the current class method
4. to pass as an argument in the method call
5. to pass as an argument in the constructor call
6. to return the current class instance
Suggestion:If you are beginner to java, lookup only two usage of this keyword.
4.
5.
student(int id,String name){
6.
id = id;
7.
name = name;
8.
}
9.
void display(){System.out.println(id+" "+name);}
10.
11.
public static void main(String args[]){
12.
Student10 s1 = new Student10(111,"Karan");
13.
Student10 s2 = new Student10(321,"Aryan");
14.
s1.display();
15.
s2.display();
16.
}
17. }
Test it Now
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same
that is why we are using this keyword to distinguish between local variable and instance
variable.
If local variables(formal arguments) and instance variables are different, there is no need
to use this keyword like in the following program:
4.
String city;
5.
6.
Student14(int id,String name){
7.
this.id = id;
8.
this.name = name;
9.
}
10.
Student14(int id,String name,String city){
11.
this(id,name);//now no need to initialize id and name
12.
this.city=city;
13.
}
14.
void display(){System.out.println(id+" "+name+" "+city);}
15.
16.
public static void main(String args[]){
17.
Student14 e1 = new Student14(111,"karan");
18.
Student14 e2 = new Student14(222,"Aryan","delhi");
19.
e1.display();
20.
e2.display();
21. }
22. }
Test it Now
Output:111 Karan null
222 Aryan delhi
1. class S{
2.
void m(){
3.
System.out.println("method is invoked");
4.
}
5.
void n(){
6.
this.m();//no need because compiler does it for you.
7.
}
8.
void p(){
9.
n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }
Test it Now
Output:method is invoked
The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling. Let's see the example:
1. class S2{
2.
void m(S2 obj){
3.
System.out.println("method is invoked");
4.
}
5.
void p(){
6.
m(this);
7.
}
8.
9.
public static void main(String args[]){
10. S2 s1 = new S2();
11. s1.p();
12. }
13. }
Test it Now
Output:method is invoked
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now
Output:10
program, we are printing the reference variable and this, output of both variables are
same.
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5.
6. public static void main(String args[]){
7. A5 obj=new A5();
8. System.out.println(obj);//prints the reference ID
9.
10. obj.m();
11. }
12. }
Test it Now
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as Parent-Child relationship.
Syntax of Inheritance
1. class Subclass-name extends Superclass-name
2. {
3.
//methods and fields
4. }
The keyword extends indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means
that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4.
5. class Programmer extends Employee{
6. int bonus=10000;
7. public static void main(String args[]){
8.
Programmer p=new Programmer();
9.
System.out.println("Programmer salary is:"+p.salary);
10. System.out.println("Bonus of Programmer is:"+p.bonus);
11. }
12. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and
hierarchical in java.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HASA relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such
as city, state, country, zipcode etc. as given below.
1.
2.
3.
4.
5.
6.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3.
return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Test it Now
Output:78.5
Code reuse is also best achieved by aggregation when there is no is-a relationship.
Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
Address.java
1. public class Address1 {
2. String city,state,country;
3.
4. public Address1(String city, String state, String country) {
5.
this.city = city;
6.
this.state = state;
7.
this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7.
this.id = id;
8.
this.name = name;
9.
this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Test it Now
Output:111 varun
gzb UP india
112 arun
gno UP india
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
6.
public static void main(String args[]){
7.
Bike obj = new Bike();
8.
obj.run();
9.
}
10. }
Test it Now
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that
is why we use method overriding.
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Method Overloading
Method Overriding
program.
within a class.
relationship.
Note: If you are beginner to java, skip this topic and return to it after OOPs
concepts.
As you can see in the above example, the return type of the get() method of A class is A but
the return type of the get() method of B class is B. Both methods have different return type
but it is method overriding. This is known as covariant return type.
super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you
don't have either this() or super() as the first statement, compiler will provide super() as
the first statement of the constructor.
Output:Vehicle is created
10
In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class
does not have message() method, so you can directly call message() method.
Que) What is the use of instance initializer block while we can directly
assign a value in instance data member? For example:
1. class Bike{
2.
int speed=100;
3. }
Let's see the simple example of instance initializer block the performs initialization.
1. class Bike7{
2.
int speed;
3.
4.
Bike7(){System.out.println("speed is "+speed);}
5.
6.
{speed=100;}
7.
8.
public static void main(String args[]){
9.
Bike7 b1=new Bike7();
10.
Bike7 b2=new Bike7();
11.
}
12. }
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler
copies the instance initializer block in the constructor after the first statement super().
So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in
every constructor.
3. The instance initializer block comes in the order in which they appear.
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
2) final method
If you make any method as final, you cannot override it.
3. }
4.
5. class Honda extends Bike{
6.
void run(){System.out.println("running safely with 100kmph");}
7.
8.
public static void main(String args[]){
9.
Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error
3) final class
If you make any class as final, you cannot extend it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it Now
Output:running...
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
10. }
11. }
Test it Now
Output:running safely with 60km.
0;}
8;}
7;}
9;}
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
Test it Now
Output: eating
eating fruits
drinking Milk
Understanding Type
Let's understand the type of instance.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Java instanceof
1. java instanceof
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof operator
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instanceof in java is also known as typecomparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with
any variable that has null value, it returns false.
An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.
Output:true
8.
9.
10.
11.
12.
13.
14.
15.
16.
}
}
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
}
}
Test it Now
Output:ok downcasting performed
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
File: TestAbstraction1.java
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class Circle1 extends Shape{
10. void draw(){System.out.println("drawing circle");}
11. }
12.
13. //In real scenario, method is called by programmer or user
14. class TestAbstraction1{
15. public static void main(String args[]){
16. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape
() method
17. s.draw();
18. }
19. }
Test it Now
drawing circle
File: TestAbstraction2.java
1. //example of abstract class that have method body
2. abstract class Bike{
3.
Bike(){System.out.println("bike is created");}
4.
abstract void run();
5.
void changeGear(){System.out.println("gear changed");}
6. }
7.
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. obj.run();
15. obj.changeGear();
16. }
17. }
Test it Now
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error
Rule: If you are extending any abstract class that have abstract method, you must
either provide the implementation of the method or make this class abstract.
Note: If you are beginner to java, learn interface first and skip this example.
1.
2.
3.
4.
5.
interface A{
void a();
void b();
void c();
void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Test it Now
Output:I am a
I am b
I am c
I am d
Next TopicInterface in Java
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of class.
5. Marker Interface
6. Nested Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.
The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body. It is used to achieve fully
abstraction and multiple inheritance in Java.
The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public
and abstract.
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. obj.print();
17. obj.show();
18. }
19. }
Test it Now
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void print();
7. }
8.
9. class testinterface1 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. testinterface1 obj = new testinterface1();
15. obj.print();
16. }
17. }
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class A, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Test it Now
Hello
Welcome
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
4. public class A{
5.
public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7.
public static void main(String args[]){
8.
A obj = new A();
9.
obj.msg();
10. }
11. }
Output:Hello
//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
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize
the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3.
public static void main(String args[]){
4.
System.out.println("Hello subpackage");
5.
}
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
1.
2.
3.
4.
5.
6.
7.
8.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Temporary
o By setting the classpath in the command prompt
o By -classpath switch
Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved
by the public class name.
1.
2.
3.
4.
5.
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
Name
class name
Convention
should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface
should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name
ActionListener etc.
method name
should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable name
package
name
constants
name
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
4.
5.
6.
7.
8.
9.
Method
public final ClassgetClass()
Description
returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.
CloneNotSupportedException
object.
timeout)throws InterruptedException
nanos)throws InterruptedException
InterruptedException
Throwable
The clone() method saves the extra processing task for creating the exact copy of an
object. If we perform it by using the new keyword, it will take a lot of processing to be
performed that is why we use object cloning.
If we create another object by new keyword and assign the values of another object to this
one, it will require a lot of processing on this object. So to save the extra processing task
we use clone() method
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory
location.
Java array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Test it Now
Output:33
3
4
5
Test it Now
Output:3
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
12. System.out.println();
13. }
14.
15. }}
Test it Now
Output:1 2 3
2 4 5
4 4 5
4.
'i', 'n', 'a', 't', 'e', 'd' };
5.
char[] copyTo = new char[7];
6.
7.
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8.
System.out.println(new String(copyTo));
9.
}
10. }
Test it Now
Output:caffein
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you
perform operations in the floating-point variable. The precision may differ from platform
to platform that is why java programming language have provided the strictfp keyword,
so that you get same result on every platform. So, now you have better control over the
floating-point arithmetic.
class B{
strictfp int data=10;//modifier strictfp not allowed here
}
class B{
strictfp B(){}//modifier strictfp not allowed here
}
We can create document api in java by the help of javadoc tool. In the java file, we must
use the documentation comment /**... */ to post information for the class, method,
constructor, fields etc.
Let's see the simple class that contains documentation comment.
1.
2.
3.
4.
5.
6.
7.
package com.abc;
/** This class is a user-defined class that contains one methods cube.*/
public class M{
/** The cube method prints cube of the given number */
public static void cube(int n){System.out.println(n*n*n);}
}
To create the document API, you need to use the javadoc tool followed by java file name.
There is no need to compile the javafile.
On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the
index.html file to get the information about the classes.
In this example, we are receiving only one argument and printing it. To run this java
1.
2.
3.
4.
5.
program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
ava String
1. Java String Handling
2. How to create string object
1. String literal
2. new keyword
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in java
and how to create the string object.
1) String Literal
In the above example only one object will be created. Firstly JVM will not find any string
object with the value "Welcome" in string constant pool, so it will create a new object. After
that it will find the string with the value "Welcome" in the pool, it will not create new object
but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant
pool.
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
No.
1
Method
char charAt(int index)
Description
returns char value for the particular
index
int length()
args)
locale
index
boolean contains(CharSequence s)
CharSequence... elements)
10
11
boolean isEmpty()
12
13
14
15
new)
CharSequence
String trim()
Do You Know ?
Concept of String
Immutable String
String Comparison
String Concatenation
Concept of Substring
String class methods and its usage
StringBuffer class
StringBuilder class
Creating Immutable class
toString() method
StringTokenizer class
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3.
String s="Sachin";
4.
s=s.concat(" Tendulkar");
5.
System.out.println(s);
6. }
7. }
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
We can compare two given strings on the basis of content and reference.
It is used in authentication (by equals() method),sorting (by compareTo()
method), reference matching (by == operator) etc.
There are three ways to compare String objects:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) By equals() method
equals() method compares the original content of the string.It compares values of string
for equality.String class provides two methods:
1. class Teststringcomparison1{
2. public static void main(String args[]){
3.
4.
String s1="Sachin";
5.
String s2="Sachin";
6.
String s3=new String("Sachin");
7.
String s4="Saurav";
8.
9.
System.out.println(s1.equals(s2));//true
10. System.out.println(s1.equals(s3));//true
11. System.out.println(s1.equals(s4));//false
12. }
13. }
Test it Now
Output:true
true
false
1. //Example of equalsIgnoreCase(String) method
2. class Teststringcomparison2{
3. public static void main(String args[]){
4.
5.
String s1="Sachin";
6.
String s2="SACHIN";
7.
8.
System.out.println(s1.equals(s2));//false
9.
System.out.println(s1.equalsIgnoreCase(s3));//true
10. }
11. }
Test it Now
Output:false
true
2) By == operator
The = = operator compares references not values.
1. //<b><i>Example of == operator</i></b>
2.
3. class Teststringcomparison3{
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values
compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
Note:If either operand is a string, the resulting operation will be string concatenation. If
both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
1. //<b><i>Example of concat(String) method</i></b>
2.
3. class TestStringConcatenation3{
4. public static void main(String args[]){
5.
6.
String s1="Sachin ";
7.
String s2="Tendulkar";
8.
9.
String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
13. }
Test it Now
Output:Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is
inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
Method
Description
another)
case.
endIndex)
string.
secondString)
First seven methods have been discussed earlier. Now Let's take the example of other
methods:
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Test it Now
SACHIN
sachin
Sachin
The string trim() method eliminates white spaces before and after string.
1. String s=" Sachin ";
2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin
Test it Now
Sachin
Sachin
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.
2.
3.
4.
5.
6.
7.
8.
9.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
2.
3.
4.
5.
6.
7.
8.
9.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK1.5.
The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
4.
5.
6.
7.
8.
9.
5.
6.
7.
8.
9.
sb.reverse();
System.out.println(sb);//prints olleH
}
}
calls toString() method, overriding this method will return the specified values. Let's
understand it with the example given below:
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor
Description
StringTokenizer(String str)
StringTokenizer(String str,
String delim)
StringTokenizer(String str,
returnValue)
Public method
Description
boolean hasMoreTokens()
String nextToken()
boolean hasMoreElements()
Object nextElement()
int countTokens()
Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the
Java Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.
1.
2.
3.
4.
MatchResult interface
Matcher class
Pattern class
PatternSyntaxException class
Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match
operations on a character sequence.
No.
Method
Description
boolean matches()
boolean find()
boolean find(int
finds the next expression that matches the pattern from the given
start)
start number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
No.
1
Method
Description
regex)
pattern.
Matcher matcher(CharSequence
input)
pattern.
String pattern()
Output
true true true
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)
}}
Test it Now
Character Class
Description
[abc]
a, b, or c (simple class)
[^abc]
[a-zA-Z]
[a-d[m-p]]
[a-z&&[def]]
d, e, or f (intersection)
[a-z&&[^bc]]
[a-z&&[^m-p]]
import java.util.regex.*;
class RegexExample3{
public static void main(String args[]){
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more t
han once)
7. }}
Test it Now
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex
Description
X?
X+
X*
X{n}
X{n,}
X{y,z}
import java.util.regex.*;
class RegexExample4{
public static void main(String args[]){
System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex
Description
\d
\D
\s
\S
\w
\W
\b
A word boundary
\B
import java.util.regex.*;
class RegexExample5{
public static void main(String args[]){
System.out.println("metacharacters d....");\\d means digit
5.
6.
7.
8.
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-Z09]{6}", "kkvarun32"));//false (more than 6 char)
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true
10. System.out.println(Pattern.matches("[a-zA-Z09]{6}", "arun$2"));//false ($ is not matched)
11. }}
Test it Now
Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the
Java Regex Tester Tool.
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.
1.
2.
3.
4.
MatchResult interface
Matcher class
Pattern class
PatternSyntaxException class
Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match
operations on a character sequence.
No.
Method
Description
boolean matches()
boolean find()
boolean find(int
finds the next expression that matches the pattern from the given
start)
start number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
No.
1
Method
static Pattern compile(String
Description
compiles the given regex and return the instance of
regex)
pattern.
Matcher matcher(CharSequence
input)
pattern.
String pattern()
Output
true true true
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)
}}
Test it Now
Character Class
Description
[abc]
a, b, or c (simple class)
[^abc]
[a-zA-Z]
[a-d[m-p]]
[a-z&&[def]]
d, e, or f (intersection)
[a-z&&[^bc]]
[a-z&&[^m-p]]
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex
Description
X?
X+
X*
X{n}
X{n,}
X{y,z}
import java.util.regex.*;
class RegexExample4{
public static void main(String args[]){
System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one tim
e)
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes m
ore than one time)
Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex
Description
\d
\D
\s
\S
\w
\W
\b
A word boundary
\B
import java.util.regex.*;
class RegexExample5{
public static void main(String args[]){
System.out.println("metacharacters d....");\\d means digit
/*Create a regular expression that accepts alpha numeric characters only. Its
length must be 6 characters long only.*/
import java.util.regex.*;
class RegexExample6{
public static void main(String args[]){
System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true
Test it Now
In this page, we will learn about java exception, its type and the difference between
checked and unchecked exceptions.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
1;
2;
3;
4;
5;//exception occurs
6;
7;
8;
9;
10;
Do You Know ?
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
1. int a=50/0;//ArithmeticException