Java Programming Language Overview
Java Programming Language Overview
Introduction
Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]).
As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE). With the
advancement of Java and its widespread popularity, multiple configurations were built to suite
various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere.
Features
1. Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
4. Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
7. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
10. High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
11. Distributed: Java is designed for the distributed environment of the internet.
12. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top
box projects. The language, initially called Oak after an oak tree that stood outside Gosling's
office, also went by the name Green and ended up later being renamed as Java, from a list of
random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere(WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
1) Why they choosed java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.
2) Java is an island of Indonesia where first coffee was produced (called java coffee).
5) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
Let's see what is the meaning of class, public, static, void, main, String[], [Link]().
Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describes the behaviors/states
that object of its type support.
Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names – For all class names the first letter should be in Upper Case.
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive)
and append '.java' to the end of the name (if the file name and the class name do not match your
program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as'[Link]'
public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program..
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character identifiers can have any combination of characters.
Java Modifiers:
Java Variables:
We would see following type of variables in Java:
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static variables)
Java Arrays:
Arrays are objects that store multiple variables of the same type. However, an array itself is an
object on the heap. We will look into how to declare, construct and initialize in the upcoming
chapters.
Java Enums:
Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few
predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict
the glass size to small, medium and large. This would make sure that it would not allow anyone
to order any size other than the small, medium or large.
Java Keywords:
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
8
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
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
JRE
JRE is an acronym for Java Runtime [Link] is used to provide runtime [Link]
is the implementation of [Link] physically [Link] 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 [Link] physically [Link] contains JRE +
development tools.
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
5) Program Counter Register : PC (program counter) register. It contains the address of the Java
virtual machine instruction currently being executed.
6) Native Method Stack: It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
Variable is a name of memory location. There are three types of variables: local, instance and
static. There are two types of datatypes in java, primitive and non-primitive.
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.
Operators in java
Operator in java is a 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.
Modifiers are keywords that you add to those definitions to change their meanings. The Java
language has a wide variety of modifiers, including the following:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13;
now in binary format they will be as follows:
b = 0000 1101
-----------------
~a = 1100 0011
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type(class type or interface type). instanceof operator is wriiten as:
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is the example:
true
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:
true
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used as
an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
24
5. }
1. compile by > javac [Link]
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<[Link];i++)
5. [Link](args[i]);
6.
7. }
8. }
1. compile by > javac [Link]
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
25
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
public class Test {
while( x < 20 ) {
[Link]("value of x : " + x );
x++;
[Link]("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
do{
[Link]("value of x : " + x );
x++;
[Link]("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as long as
a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example:
public class Test {
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test {
for(int x : numbers ){
[Link]( x );
[Link](",");
}
[Link]("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
[Link]( name );
[Link](",");
10,20,30,40,50,
James,Larry,Tom,Lacy,
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
[Link]( x );
[Link]("\n");
}
}
}
10
20
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
[Link]( x );
[Link]("\n");
}
}
}
10
20
40
50
if statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
public class Test {
if( x < 20 ){
[Link]("This is if statement");
}
}
}
This is if statement
if(Boolean_expression){
Example:
public class Test {
if( x < 20 ){
[Link]("This is if statement");
}else{
[Link]("This is else statement");
}
}
}
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
Example:
public class Test {
if( x == 10 ){
[Link]("Value of X is 10");
}else if( x == 20 ){
[Link]("Value of X is 20");
}else if( x == 30 ){
[Link]("Value of X is 30");
}else{
[Link]("This is else statement");
}
}
}
Value of X is 30
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
34
public class Test {
if( x == 30 ){
if( y == 10 ){
[Link]("X = 30 and Y = 10");
}
}
}
}
X = 30 and Y = 10
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Example:
public class Test {
switch(grade)
{
case 'A' :
[Link]("Excellent!");
break;
case 'B' :
case 'C' :
[Link]("Well done");
break;
case 'D' :
[Link]("You passed");
case 'F' :
[Link]("Better try again");
break;
default :
[Link]("Invalid grade");
}
[Link]("Your grade is " + grade);
}
}
Compile and run above program using various command line arguments. This would produce the
following result:
$ java Test
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
36
Well done
Your grade is a C
$
Example:
int i = 5000;
float gpa = 13.65;
byte mask = 0xaf;
However, in development, we come across situations where we need to use objects instead of
primitive data types. In-order to achieve this Java provides wrapper classes for each primitive
data type.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract
class Number.
This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive
is used when an object is required, the compiler boxes the primitive type in its wrapper class.
Similarly, the compiler unboxes the object to a primitive as well. The Number is part of the
[Link] package.
Here is an example of boxing and unboxing:
15
When x is assigned integer values, the compiler boxes the integer because x is integer objects.
Later, x is unboxed so that they can be added as integers.
Number Methods:
Here is the list of the instance methods that all the subclasses of the Number class implement:
xxxValue()
1
Converts the value of this Number object to the xxx data type and returned it.
compareTo()
2
Compares this Number object to the argument.
equals()
3
Determines whether this number object is equal to the argument.
valueOf()
4
Returns an Integer object holding the value of the specified primitive.
toString()
5
Returns a String object representing the value of specified int or Integer.
parseInt()
6
This method is used to get the primitive data type of a certain String.
abs()
7
Returns the absolute value of the argument.
floor()
9 Returns the largest integer that is less than or equal to the argument. Returned as
a double.
rint()
10
Returns the integer that is closest in value to the argument. Returned as a double.
round()
11 Returns the closest long or int, as indicated by the method's return type, to the
argument.
min()
12
Returns the smaller of the two arguments.
max()
13
Returns the larger of the two arguments.
exp()
14
Returns the base of the natural logarithms, e, to the power of the argument.
log()
15
Returns the natural logarithm of the argument.
pow()
16 Returns the value of the first argument raised to the power of the second
argument.
sqrt()
17
Returns the square root of the argument.
sin()
18
Returns the sine of the specified double value.
tan()
20
Returns the tangent of the specified double value.
asin()
21
Returns the arcsine of the specified double value.
acos()
22
Returns the arccosine of the specified double value.
atan()
23
Returns the arctangent of the specified double value.
atan2()
24 Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns
theta.
toDegrees()
25
Converts the argument to degrees
toRadians()
26
Converts the argument to radians.
random()
27
Returns a random number.
Escape Sequences:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the
compiler.
The newline character (\n) has been used frequently in this tutorial in [Link]()
statements to advance to the next line after the string is printed.
Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class
implement:
isLetter()
1
Determines whether the specified char value is a letter.
isDigit()
2
Determines whether the specified char value is a digit.
isWhitespace()
3
Determines whether the specified char value is white space.
isUpperCase()
4
Determines whether the specified char value is uppercase.
isLowerCase()
5
Determines whether the specified char value is lowercase.
toLowerCase()
7
Returns the lowercase form of the specified char value.
toString()
8 Returns a String object representing the specified character valuethat is, a one-
character string.
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
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.
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.
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.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.
There are many differences between object and class. A list of differences between object and
class are given below:
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
45
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.
By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important. It indicates that less
time is spent to figure out what the code does.
Name Convention
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionList
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), p
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.
Object is the physical as well as logical entity whereas class is the logical entity only.
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.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
data member
method
constructor
block
class and interface
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student1 s1=new Student1();//creating an object of Student
7. [Link]([Link]);
8. [Link]([Link]);
9. }
10. }
Output:0 null
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
1. class Student2{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){[Link](rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student2 s1=new Student2();
14. Student2 s2=new Student2();
15.
16. [Link](111,"Karan");
17. [Link](222,"Aryan");
18.
19. [Link]();
20. [Link]();
21.
22. }
23. }
Output:111 Karan
222 Aryan
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
50
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 are reference
variables that refer to the objects allocated in memory.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){[Link](length*width);}
11.
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. [Link]("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
52
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){[Link](length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. [Link](11,5);
16. [Link](3,15);
17.
18. [Link]();
19. [Link]();
20. }
21. }
Output:55
45
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
In java, Method Overloading is not possible by changing the return type of the method.
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){[Link](a+b);}
3. void sum(int a,int b,int c){[Link](a+b+c);}
4.
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){[Link](a+b);}
3. void sum(double a,double b){[Link](a+b);}
4.
5. public static void main(String args[]){
6. Calculation2 obj=new Calculation2();
7. [Link](10.5,10.5);
8. [Link](20,20);
9.
10. }
11. }
Output:21.0
40
Que) Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:
1. class Calculation3{
2. int sum(int a,int b){[Link](a+b);}
3. double sum(int a,int b){[Link](a+b);}
4.
5. public static void main(String args[]){
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
55
6. Calculation3 obj=new Calculation3();
7. int result=[Link](20,20); //Compile Time Error
8.
9. }
10. }
int result=[Link](20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
1. class Overloading1{
2. public static void main(int a){
3. [Link](a);
4. }
5.
6. public static void main(String args[]){
7. [Link]("main() method invoked");
8. main(10);
9. }
10. }
Output: main() method invoked
10
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){[Link]("int arg method invoked");}
3. void sum(long a,long b){[Link]("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. [Link](20,20);//now int arg sum() method gets invoked
8. }
9. }
Output: int arg method invoked
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){[Link]("a method invoked");}
3. void sum(long a,int b){[Link]("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. [Link](20,20);//now ambiguity
8. }
9. }
Output:Compile Time Error
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){[Link]("eating bread...");}
6. }
Typically, you will use a constructor to give initial values to the instance variables defined by the
class, or to perform any other startup procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once you
define your own constructor, the default constructor is no longer used.
Constructor in java is a special type of method that is used to initialize the object.
Java 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.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
at the time of object creation.
1. class Bike1{
2. Bike1(){[Link]("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you
a default constructor. Here 0 and null values are provided by default constructor.
1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){[Link](id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
62
13. Student4 s2 = new Student4(222,"Aryan");
14. [Link]();
15. [Link]();
16. }
17. }
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
63
222 Aryan 25
There are many differences between constructors and methods. They are given below.
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
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 java
constructor.
1. class Student6{
2. int id;
3. String name;
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(){[Link](id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. [Link]=[Link];
111 Karan
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in
the constructor as you perform in the method.
Example:
Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
int x;
Example:
Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
int x;
10 20
Variable Arguments(var-args):
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The
parameter in the method is declared as follows:
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-
length parameter may be specified in a method, and this parameter must be the last parameter.
Any regular parameters must precede it.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
67
Example:
public class VarargsDemo {
It is possible to define a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize( ), and it can be used to ensure that an object
terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by that object is
closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that
method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed before an
object is destroyed.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
68
The finalize( ) method has this general form:
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
This means that you cannot know when or even if finalize( ) will be executed. For example, if
your program ends before garbage collection occurs, finalize( ) will not execute.
Java – Inheritance
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.
The extends keyword 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 [Link] means that Programmer is
a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
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.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
1. class A{
2. void msg(){[Link]("Hello");}
3. }
4. class B{
5. void msg(){[Link]("Welcome");}
6. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
72
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. [Link]();//Now which msg() method would be invoked?
12. }
13. }
Output:
Inheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would
be extends and implements. These words would determine whether one object IS-A type of
another. By using these keywords we can make one object acquire the properties of another
object.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal{
}
Now, based on the above example, In Object Oriented terms, the following are true:
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class Dog extends Mammal{
true
true
true
Since we have a good understanding of the extends keyword let us look into how
the implementskeyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
public interface Animal {}
Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-
Acertain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class., which makes it possible to
reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
Java - Overriding
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the subclass type which
means a subclass can implement a parent class method based on its requirement.
Example:
Let us look at an example.
class Animal{
class Animal{
This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For
example: if the superclass method is declared public then the overridding method in the sub class
cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass in a different package can only override the non-final methods declared public
or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should not throw
checked exceptions that are new or broader than the ones declared by the overridden method.
The overriding method can throw narrower or fewer exceptions than the overridden method.
The super keyword in java 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.
1. class Vehicle{
2. int speed=50;
3. }
4. class Bike3 extends Vehicle{
5. int speed=100;
6. void display(){
7. [Link](speed);//will print speed of Bike
8. }
9. public static void main(String args[]){
10. Bike3 b=new Bike3();
11. [Link]();
12. }
13. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
79
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.
The super keyword can also be used to invoke the parent class constructor as given below:
1. class Vehicle{
2. Vehicle(){[Link]("Vehicle is created");}
3. }
4.
5. class Bike5 extends Vehicle{
6. Bike5(){
7. super();//will invoke parent class constructor
8. [Link]("Bike is created");
9. }
10. public static void main(String args[]){
As we know well that default constructor is provided by compiler automatically but it also adds
super() for the first [Link] 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.
Another example of super keyword where super() is provided by the compiler implicitly.
1. class Vehicle{
2. Vehicle(){[Link]("Vehicle is created");}
3. }
4.
5. class Bike6 extends Vehicle{
6. int speed;
7. Bike6(int speed){
8. [Link]=speed;
9. [Link](speed);
10. }
11. public static void main(String args[]){
12. Bike6 b=new Bike6(10);
13. }
14. }
Output:Vehicle is created
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
81
10
The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:
1. class Person{
2. void message(){[Link]("welcome");}
3. }
4.
5. class Student16 extends Person{
6. void message(){[Link]("welcome to java");}
7.
8. void display(){
9. message();//will invoke current class message() method
10. [Link]();//will invoke parent class message() method
11. }
12.
13. public static void main(String args[]){
14. Student16 s=new Student16();
15. [Link]();
16. }
17. }
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not of
Person class because priority is given to local.
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.
When invoking a superclass version of an overridden method the super keyword is used.
class Animal{
}
}
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Example:
Let us look at an example.
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
When we apply the reference variable facts to a Deer object reference, the following declarations
are legal:
Java – Abstraction
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
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.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Abstract Method
A method that is declared as abstract and does not have implementation is known as abstract
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: [Link]
drawing circle
File: [Link]
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
File: [Link]
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. }
Output:
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.
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){[Link]("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){[Link]("I am a");}
14. public void b(){[Link]("I am b");}
15. public void d(){[Link]("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. }}
Output:
Output:I am a
I am b
I am c
I am d
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.
There are mainly three reasons to use interface. They are given below.
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.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
In this example, Printable interface have only one method, its implementation is provided in
the A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){[Link]("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. [Link]();
11. }
12. }
Output:Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Q) Multiple inheritance is not supported through class in java but it is possible by interface,
why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
93
of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
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(){[Link]("Hello");}
12.
13. public static void main(String args[]){
14. testinterface1 obj = new testinterface1();
15. [Link]();
16. }
17. }
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
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(){[Link]("Hello");}
10. public void show(){[Link]("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. [Link]();
Hello
Welcome
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.
Note: An interface can have another interface i.e. known as nested interface. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Let us look at an example that depicts encapsulation:
An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
Example:
/* File name : [Link] */
interface Animal {
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
/* File name : [Link] */
public class MammalInt implements Animal{
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend
another class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: [Link]
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: [Link]
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain
any methods. For example, the MouseListener interface in the [Link] package extended
[Link], which is defined as:
package [Link];
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent
among a group of interfaces. For example, when an interface extends EventListener, the JVM
knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not
have any), but the class becomes an interface type through polymorphism.
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Let's see a simple example where we are using interface and abstract class both.
Output:
I am a
I am b
I am c
I am d
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
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.
Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is [Link] student have its unique rollno and name so instance data
member is [Link], college refers to the common property of all [Link] we make it
static,this field will get memory only once.
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. [Link](count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }
16. }
Output:1
1
1
1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter2(){
5. count++;
6. [Link](count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter2 c1=new Counter2();
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
104
12. Counter2 c2=new Counter2();
13. Counter2 c3=new Counter2();
14.
15. }
16. }
Output:1
2
3
If you apply static keyword with any method, it is known as static method.
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. [Link](a);
6. }
7. }
Output:Compile Time Error
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
106
Q) why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A3{
2. static{
3. [Link]("static block is invoked");
4. [Link](0);
5. }
6. }
Output:static block is invoked (if not JDK7)
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
There can be a lot of usage of java this keyword. In java, this is areference variable that refers
to the current object.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
1. class Student10{
2. int id;
3. String name;
4.
5. Student10(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){[Link](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. [Link]();
15. [Link]();
16. }
17. }
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:
The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
1. class Student14{
2. int id;
3. String name;
4. String city;
5.
6. Student14(int id,String name){
7. [Link] = id;
8. [Link] = name;
9. }
10. Student14(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. [Link]=city;
13. }
14. void display(){[Link](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. [Link]();
20. [Link]();
21. }
22. }
Output:111 Karan null
222 Aryan delhi
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example
1. class S{
2. void m(){
3. [Link]("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();
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
113
14. }
15. }
Output: method is invoked
1. class S2{
2. void m(S2 obj){
3. [Link]("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. }
Output: method is invoked
1. class B{
2. A4 obj;
3. B(A4 obj){
4. [Link]=obj;
5. }
6. void display(){
7. [Link]([Link]);//using data member of A4 class
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
114
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. [Link]();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Output:10
1. class A5{
2. void m(){
3. [Link](this);//prints same reference ID
4. }
5.
6. public static void main(String args[]){
7. A5 obj=new A5();
8. [Link](obj);//prints the reference ID
9.
10. obj.m();
11. }
12. }
Output:A5@22b3ea59
A5@22b3ea59
Instance Initializer block is used to initialize the instance data member. It run each time
when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra
operations while initializing the instance variable in the instance initializer block.
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. }
Suppose I have to perform some operations while assigning value to instance data member e.g.
a for loop to fill a complex array or error handling etc.
1. class Bike7{
2. int speed;
3.
4. Bike7(){[Link]("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. }
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
1. class Bike8{
2. int speed;
3.
4. Bike8(){[Link]("constructor is invoked");}
5.
6. {[Link]("instance initializer block invoked");}
7.
8. public static void main(String args[]){
9. Bike8 b1=new Bike8();
10. Bike8 b2=new Bike8();
11. }
12. }
Output: instance initializer block invoked
constructor is invoked
Note: The java compiler copies the code of instance initializer block in every constructor.
There are mainly three rules for the instance initializer block. They are as follows:
1. class A{
2. A(){
3. [Link]("parent class constructor invoked");
4. }
5. }
6. class B2 extends A{
7. B2(){
8. super();
9. [Link]("child class constructor invoked");
10. }
11.
12. {[Link]("instance initializer block is invoked");}
13.
14. public static void main(String args[]){
15. B2 b=new B2();
16. }
17. }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
1. class A{
2. A(){
3. [Link]("parent class constructor invoked");
4. }
5. }
6.
7. class B3 extends A{
8. B3(){
9. super();
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
119
10. [Link]("child class constructor invoked");
11. }
12.
13. B3(int a){
14. super();
15. [Link]("child class constructor invoked "+a);
16. }
17.
18. {[Link]("instance initializer block is invoked");}
19.
20. public static void main(String args[]){
21. B3 b1=new B3();
22. B3 b2=new B3(10);
23. }
24. }
Output: parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. [Link]();
9. }
10. }//end of class
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){[Link]("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. [Link](speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Output:70
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.
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. [Link](5);
9. }
10. }
Output: Compile Time Error
Java Array
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.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
124
Array in java is index based, first element of the array is stored at 0 index.
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
125
1. class Testarray{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<[Link];i++)//length is the property of array
13. [Link](a[i]);
14.
15. }}
Output: 10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
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<[Link];i++)//length is the property of array
8. [Link](a[i]);
9.
10. }}
Output:33
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
1. class Testarray2{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<[Link];i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. [Link](min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array to method
15.
16. }}
Output:3
In such case, data is stored in row and column based index (also known as matrix form).
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class Testarray3{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. [Link](arr[i][j]+" ");
11. }
12. [Link]();
13. }
14.
15. }}
Output:1 2 3
245
445
In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.
1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
1. class Testarray5{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
129
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. [Link](c[i][j]+" ");
15. }
16. [Link]();//new line
17. }
18.
19. }}
Output:2 6 8
6 8 10
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
131
1. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
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.
1. //save by [Link]
2.
3. package pack;
4. public class A{
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
132
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }
11. }
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
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. [Link]();
10. }
11. }
Output:Hello
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. [Link] and [Link] packages
contain Date class.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. [Link]();
8. }
9. }
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
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 [Link];
2. class Simple{
3. public static void main(String args[]){
4. [Link]("Hello subpackage");
5. }
6. }
To Compile: javac -d . [Link]
Output:Hello subpackage
There is a scenario, I want to put the class file of [Link] source file in classes folder of c:
drive. For example:
1. //save as [Link]
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. [Link]("Welcome to package");
7. }
8. }
To Compile:
e:\sources> javac -d c:\classes [Link]
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
Output:Welcome to package
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. //save as [Link] otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as [Link]
2.
3. package javatpoint;
4. public class A{}
1. //save as [Link]
2.
3. package javatpoint;
4. public class B{}
Java String
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.
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="javapython";
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.
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
Note: String objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).
2) By new keyword
In such case, JVM will create a new string object in normal(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
java
strings
example
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
140
Java String class methods
The [Link] class provides many useful methods to perform operations on sequence of
char values.
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. [Link](" Tendulkar");//concat() method appends the string at the end
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
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".
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=[Link](" Tendulkar");
5. [Link](s);
6. }
7. }
Output
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. [Link]([Link](s2));//true
8. [Link]([Link](s3));//true
9. [Link]([Link](s4));//false
10. }
11. }
Output
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. [Link]([Link](s2));//false
7. [Link]([Link](s3));//true
8. }
9. }
Output
Output:false
true
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. [Link](s1==s2);//true (because both refer to same instance)
7. [Link](s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Output
Output:true
false
The String compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. [Link]([Link](s2));//0
7. [Link]([Link](s3));//1(because s1>s3)
8. [Link]([Link](s1));//-1(because s3 < s1 )
9. }
10. }
Output
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
146
Output:0
1
-1
In java, string concatenation forms a new string that is the combination of multiple strings. There
are two ways to concat string in java:
Java string concatenation operator (+) is used to add strings. For Example:
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. [Link](s);//Sachin Tendulkar
5. }
6. }
Output
Output:Sachin Tendulkar
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and its append method. String concatenation operator produces a new string by appending the
second operand onto the end of the first operand. The string concatenation operator can concat
not only string but primitive values also. For Example:
1. class TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. [Link](s);//80Sachin4040
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
147
5. }
6. }
Output
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
The String concat() method concatenates the specified string to the end of current string. Syntax:
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=[Link](s2);
6. [Link](s3);//Sachin Tendulkar
7. }
8. }
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 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.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
148
In case of string:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. [Link]([Link](0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Tendulkar
Sachin
The [Link] class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form
in window based, web based or mobile application.
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
1. String s="Sachin";
2. [Link]([Link]());//SACHIN
3. [Link]([Link]());//sachin
4. [Link](s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
The string trim() method eliminates white spaces before and after string.
Sachin
Sachin
true
true
1. String s="Sachin";
2. [Link]([Link](0));//S
S
h
1. String s="Sachin";
2. [Link]([Link]());//6
Output
When the intern method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is returned.
Sachin
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and
char array into string.
1. int a=10;
2. String s=[Link](a);
3. [Link](s+10);
Output:
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Output:
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link]("Java");//now original string is changed
5. [Link](sb);//prints Hello Java
6. }
7. }
The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link](1,"Java");//now original string is changed
5. [Link](sb);//prints HJavaello
6. }
7. }
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link](1,3,"Java");
5. [Link](sb);//prints HJavalo
6. }
7. }
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link](1,3);
5. [Link](sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link]();
5. [Link](sb);//prints olleH
6. }
7. }
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
154
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. [Link](10);//now no change
10. [Link]([Link]());//now 34
11. [Link](50);//now (34*2)+2
12. [Link]([Link]());//now 70
13. }
14. }
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK
1.5.
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
155
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity as
length.
The StringBuilder append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. [Link]("Java");//now original string is changed
5. [Link](sb);//prints Hello Java
6. }
7. }
The StringBuilder insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. [Link](1,"Java");//now original string is changed
5. [Link](sb);//prints HJavaello
6. }
7. }
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. [Link](1,3,"Java");
5. [Link](sb);//prints HJavalo
6. }
7. }
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. [Link](1,3);
5. [Link](sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. [Link]();
5. [Link](sb);//prints olleH
6. }
7. }
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is
16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. [Link](10);//now no change
10. [Link]([Link]());//now 34
11. [Link](50);//now (34*2)+2
12. [Link]([Link]());//now 70
13. }
14. }
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
As you can see in the program given below, String returns new hashcode value when you concat
string but StringBuffer returns same.
There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
StringBuffer Example
hellojava
StringBuilder Example
hellojava
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
Signature
1. public int compareTo(String anotherString)
Parameters
Returns
an integer value
Output:
0
-5
-1
The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.
Signature
Parameter
Returns
combined string
java string
java string is immutable so assign it explicitly
The java string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it returns
true.
The String equals() method overrides the equals() method of Object class.
Signature
1. public boolean equals(Object anotherObject)
Parameter
Returns
Overrides
true
false
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
165
false
The java string length() method length of the string. It returns count of total number of
characters. The length of java string is same as the unicode code units of the string.
Signature
Specified by
CharSequence interface
Returns
length of characters
Signature
1. public String substring(int startIndex)
2. and
3. public String substring(int startIndex, int endIndex)
If you don't specify endIndex, java substring() method will return all the characters from
startIndex.
Parameters
Returns
specified string
Throws
va
vapython
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
167
Java String split
The java string split() method splits this string against given regular expression and returns a
char array.
Signature
Parameter
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.
Returns
array of strings
Throws
Since
1.4
The given example returns total number of words in a string excluding space only. It also
includes special characters.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
168
1. public class SplitExample{
2. public static void main(String args[]){
3. String s1="java string split method by javatpoint";
4. String[] words=[Link]("\\s");//splits the string based on string
5. //using java foreach loop to print elements of string array
6. for(String w:words){
7. [Link](w);
8. }
9. }}
java
string
split
method
by
javatpoint
The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:
The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.
Returns
Output:
The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:
The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.
Returns
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before and
after the string, if it exists then removes the spaces and returns the omitted string.
Signature
Returns
Java I/O (Input and Output) is used to process the input and produce the output based on the
input.
Java uses the concept of stream to make I/O operation fast. The [Link] package contains all the
classes required for input and output operations.
A stream is a sequence of [Link] Java a stream is composed of bytes. It's called a stream because
it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
Let's see the code to print output and error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class is an abstract [Link] is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
InputStream class is an abstract [Link] is the superclass of all classes representing an input
stream of bytes.
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
If you have to write primitive values then use [Link], for character-oriented
data, prefer [Link] you can write byte-oriented as well as character-oriented data.
Java FileInputStream class obtains input bytes from a [Link] is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc.
We can read the data of any file using the FileInputStream class whether it is java file, image
file, video file etc. In this example, we are reading the data of [Link] file and writing it into
another file [Link].
1. import [Link].*;
2. class C{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin=new FileInputStream("[Link]");
5. FileOutputStream fout=new FileOutputStream("[Link]");
6. int i=0;
7. while((i=[Link]())!=-1){
8. [Link]((byte)i);
9. }
10. [Link]();
11. }
12. }
Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the
data is written into a byte array that can be written to multiple stream.
Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.
1. import [Link].*;
2. class S{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("[Link]");
5. FileOutputStream fout2=new FileOutputStream("[Link]");
6.
7. ByteArrayOutputStream bout=new ByteArrayOutputStream();
8. [Link](139);
9. [Link](fout1);
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
179
10. [Link](fout2);
11.
12. [Link]();
13. [Link]();//has no effect
14. [Link]("success...");
15. }
16. }
success...
Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the performance fast.
In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
1. import [Link].*;
2. class Test{
3. public static void main(String args[])throws Exception{
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
180
4. FileOutputStream fout=new FileOutputStream("[Link]");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Sachin is my favourite player";
7. byte b[]=[Link]();
8. [Link](b);
9.
10. [Link]();
11. [Link]();
12. [Link]();
13. [Link]("success");
14. }
15. }
Output:
success...
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
Let's see the simple example to read data of file using BufferedInputStream.
1. import [Link].*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("[Link]");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=[Link]())!=-1){
9. [Link]((char)i);
10. }
11. [Link]();
12. [Link]();
13. }catch(Exception e){[Link](e);}
14. }
15. }
Output:
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
181
Sachin is my favourite player
Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to
read and write the textual information.
Output:
success...
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
In this example, we are reading the data from the file [Link] file.
1. import [Link].*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("[Link]");
5. int i;
6. while((i=[Link]())!=-1)
7. [Link]((char)i);
8.
9. [Link]();
10. }
11. }
12. Output:
13. my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the
Appendable interface. Its buffer automatically grows when data is written in this stream. Calling
the close() method on this object has no effect.
In this example, we are writing a common data to 4 files [Link], [Link], [Link] and [Link].
1. import [Link].*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. [Link]("my name is");
7.
8. FileWriter f1=new FileWriter("[Link]");
9. FileWriter f2=new FileWriter("[Link]");
10. FileWriter f3=new FileWriter("[Link]");
11. FileWriter f4=new FileWriter("[Link]");
12.
13. [Link](f1);
14. [Link](f2);
15. [Link](f3);
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
184
16. [Link](f4);
17.
18.
19. [Link]();
20. [Link]();
21. [Link]();
22. [Link]();
23. }
24. }
There are many ways to read data from the keyboard. For example:
InputStreamReader
Console
Scanner
DataInputStream etc.
InputStreamReader class:
InputStreamReader class can be used to read data from [Link] performs two tasks:
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
In this example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.
Another Example of reading data from keyboard by InputStreamReader and BufferdReader class
until the user writes stop
In this example, we are reading and printing the data until the user prints stop.
1. import [Link].*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader([Link]);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while([Link]("stop")){
11. [Link]("Enter data: ");
12. name=[Link]();
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
186
13. [Link]("data is: "+name);
14. }
15.
16. [Link]();
17. [Link]();
18. }
19. }
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
[Link] class:
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.
1. import [Link].*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("[Link]");
6. PrintStream pout=new PrintStream(fout);
7. [Link](1900);
8. [Link]("Hello Java");
9. [Link]("Welcome to Java");
10. [Link]();
11. [Link]();
12.
13. }
14. }
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest
of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the exception will be executed. That is why we use exception handling in java.
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
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions [Link], SQLException etc. Checked exceptions are checked at
compile-time.
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
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. [Link]([Link]());//NullPointerException
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java catch block is used to handle the Exception. It must be used after the try block only.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
193
Internal working of java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Rule: At a time only one Exception is occured and at a time only one catch block is
executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
1. class TestMultipleCatchBlock1{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){[Link]("common task completed");}
8. catch(ArithmeticException e){[Link]("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. [Link]("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){[Link](e);}
8.
9. try{
10. int a[]=new int[5];
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
196
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){[Link](e);}
13.
14. [Link]("other statement);
15. }catch(Exception e){[Link]("handeled");}
16.
17. [Link]("normal flow..");
18. }
19. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
o Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. [Link](data);
6. }
7. catch(NullPointerException e){[Link](e);}
8. finally{[Link]("finally block is always executed");}
9. [Link]("rest of the code...");
10. }
11. }
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. [Link](data);
6. }
7. catch(NullPointerException e){[Link](e);}
8. finally{[Link]("finally block is always executed");}
9. [Link]("rest of the code...");
10. }
11. }
Output:finally block is always executed
Exception in thread main [Link]:/ by zero
Let's see the java finally example where exception occurs and handled.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling [Link]()
or by causing a fatal error that causes the process to abort).
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
1. import [Link];
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){[Link]("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. [Link]("normal flow...");
18. }
19. }
Output:
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
202
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or
declare the exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. [Link]();
12. }catch(Exception e){[Link]("exception handled");}
13.
14. [Link]("normal flow...");
15. }
16. }
Output:exception handled
normal flow...
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. [Link]();
11.
12. [Link]("normal flow...");
13. }
14. }
Output:Runtime Exception
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){[Link](e);}
6. finally{[Link]("finally block is executed");}
7. }}
1. class FinalizeExample{
2. public void finalize(){[Link]("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. [Link]();
9. }}
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
A main() method is not invoked on an applet, and an applet class will not define main().
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Advantages of Applet
Drawback of Applet
Plugin is required at client browser to execute applet.
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
The [Link] class 4 life cycle methods and [Link] class provides 1 life
cycle methods for an applet.
For creating any applet [Link] class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
Four methods in the Applet class give you the framework on which you build any serious
applet:
init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
[Link].
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The [Link] class provide a method drawImage() to display the image.
The [Link] class provides getImage() method that returns the object of Image.
Syntax:
1. import [Link].*;
2. import [Link].*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"[Link]");
11. }
12.
13. public void paint(Graphics g) {
14. [Link](picture, 30,30, this);
15. }
16.
17. }
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The [Link] class provide a method drawImage() to display the image.
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
1. import [Link].*;
2. import [Link].*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"[Link]");
11. }
12.
13. public void paint(Graphics g) {
14. [Link](picture, 30,30, this);
15. }
16. }
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
213
6. </html>
Audio was originally used with Java applets. For this reason, the AudioClip interface is in the
[Link] package.
The following statements, for example, create an AudioClip for the [Link] audio file in the
same directory with the class you are running.
Playing Audio
«interface»
[Link]
+play() Starts playing this audio clip. Each time this method
is called, the clip is restarted from the beginning.
+loop()To manipulate a sound for an
Plays
audiothe clip
clip, userepeatedly.
the play(), loop(), and stop() methods in
+stop() [Link]. Stops playing the clip.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
214
public class LoadSoundApplet extends Applet implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if([Link]().equals(PLAY)){
[Link]();
}else if([Link]().equals(STOP)){
[Link]();
}else{
[Link]();
}
}
}
2. Create a HTML
Create a HTML file to include the Applet.
</body>
</html>
3. Output
After you clicked on the Play button, Applet will start to play the “[Link]”
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The [Link] package provides many event classes and Listener interfaces
for event handling.
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
217
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
repaint();
}
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for source object.
The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event. The user interface element is able to delegate the processing of an
event to the separate piece of code. In this model ,Listener needs to be registered with the
source object so that the listener can receive the event notification. This is an efficient way of
handling the event because the event notifications are sent only to those listener that want to
receive them.
Now the object of concerned event class is created automatically and information about
the source and the event get populated with in same object.
OR
The event model is based on the Event Source and Event Listeners. Event Listener is an object
that receives the messages / events. The Event Source is any object which creates the message /
event. The Event Delegation model is based on – The Event Classes, The Event Listeners, Event
Objects.
An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted
by the event source by invoking an agreed method on all event listeners. The event object is
passed as argument to the agreed-upon method. Later the event listeners respond as they fit, like
submit a form, displaying a message / alert etc.
Keyboard Event
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
221
public void init()
{
addKeyListener(this);
requestFocus();
setBackground([Link]);
setForeground([Link]);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=[Link]();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=[Link]();
repaint();
}
public void paint(Graphics g)
{
[Link](msg,X,Y);
}
}
OR
import [Link].*;
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
222
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
Mouse Event
ColorChangeCanvas() { // constructor
setBackground([Link]);
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
223
addMouseListener(this); // Canvas will listen for
// its own mouse events.
}
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
The methods of Component class are widely used in java swing that are given below.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
1. import [Link].*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. [Link](130,100,100, 40);//x axis, y axis, width, height
8.
9. [Link](b);//adding button in JFrame
10.
11. [Link](400,500);//400 width and 500 height
12. [Link](null);//using no layout managers
13. [Link](true);//making the frame visible
14. }
15. }
Adapter Class
In java programming language, adapter class is used to implement an interface having a set of
dummy methods. The developer can then further subclass the adapter class so that he can
override to the methods he requires. Implementing an interface directly, requires to write all the
dummy methods. In general an adapter class is used to rapidly construct your own Listener class
to field events.
Java provides a special feature, called an adapter class, that can simplify the creation of event
handlers in certain [Link] adapter class provides an empty implementation of all methods
in an event listener interface i.e this class itself write definition for methods which are present in
particular event listener interface. However these definitions does not affect program flow or
meaning at all. Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface. You can define a new class to act
as an event listener by extending one of the adapter classes and implementing only those events
in which you are interested.
E.g. Suppose you want to use MouseClicked Event or method from MouseListener, if you do not
Java provides a special feature, called an adapter class, that can simplify the creation of
event handlers in certain situations.
Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which you are interested.
E.g. Suppose you want to use MouseClicked Event or method from MouseListener, if
you do not use adapter class then unnecessarily you have to define all other methods from
MouseListener such as MouseReleased, MousePressed etc.
But If you use adapter class then you can only define MouseClicked method and don’t
worry about other method definition because class provides an empty implementation of
all methods in an event listener interface.
Below Table Indicates Listener Interface with their respective adapter class.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Runnable Interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
Starting A Thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
234
Syntax of sleep() method in java
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second time,
it will throw exception.
Output:running...
When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issue. For example if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can overrite data or while one thread is opening the
same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block.
Following is the general form of the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor
that the synchronized statement represents. Now we are going to see two examples where we
will print a counter using two different threads. When threads are not synchronized, they print
counter value which is not in sequence, but when we print counter by putting inside
synchronized() block, then it prints counter very much in sequence for both the threads.
Example:-
package [Link];
WHY ?
Copy constructors are widely used for creating a duplicates of objects known as cloned objects.
Duplicate object in the sense the object will have the same characteristics of the original object
from which duplicate object is created. But we have to ensure that both original and duplicate
objects refer to different memory locations.
WHERE ?
It’s our responsibility to implement a copy constructor in our class in the right way. As
mentioned above, it’s used to duplicate objects. So we are free to use copy constructors instead
of clone method in java.
For example:-
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
6) Socket
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.
Important methods
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Let's see a simple of java socket programming in which client sends a text and server receives it.
File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
File: [Link]
import [Link];
import [Link];
import [Link];
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
244
import [Link];
import [Link];
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was many disadvantages of this technology.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.
What is a Servlet?
A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter etc. and other components such as HTML. The web
components typically execute in Web Server and respond to HTTP request.
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many advantages of servlet over CGI. The web container creates threads for handling
the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they
share a common memory area, lightweight, cost of communication between the threads are low.
The basic benefits of servlet are as follows:
1. Better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage
collection etc.
4. Secure: because it uses java language..
Servlet Terminology
There are some key points that must be known by the servlet programmer like server, container,
get request, post request etc. Let's first discuss these points before starting the servlet technology.
1. HTTP
2. HTTP Request Types
3. Difference between Get and Post method
4. Container
5. Server and Difference between web server and application server
6. Content Type
7. Introduction of XML
8. Deployment
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
248
HTTP (Hyper Text Transfer Protocol)
1. Http is the protocol that allows web servers and browsers to exchange data over the web.
2. It is a request response protocol.
3. Http uses reliable TCP connections bydefault on TCP port 80.
4. It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user bydefault.
Every request has a header that tells the status of the client. There are many request methods. Get
and Post requests are mostly used.
GET
POST
HEAD
PUT
DELETE
OPTIONS
TRACE
There are many differences between the Get and Post request. Let's see these differences:
Container
Server
1. Web Server
2. Application Server
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It
can't be used for EJB.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is
a HTTP header that provides the description about what are you sending to the browser.
text/html
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
251
text/plain
application/msword
application/[Link]-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
video/quicktime etc.
Servlet API
The [Link] and [Link] packages represent interfaces and classes for servlet api.
The [Link] package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The [Link] package contains interfaces and classes that are responsible for http
requests only.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
254
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:
Servlet Interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.
Let's see the simple example of servlet by implementing the servlet interface.
File: [Link]
1. import [Link].*;
2. import [Link].*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. [Link]=config;
9. [Link]("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
256
15. [Link]("text/html");
16.
17. PrintWriter out=[Link]();
18. [Link]("<html><body>");
19. [Link]("<b>hello simple servlet</b>");
20. [Link]("</body></html>");
21.
22. }
23. public void destroy(){[Link]("servlet is destroyed");}
24. }
Java Inner Class
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested [Link] non-static nested
classes are also known as inner classes.
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
258
Java Member Inner Class Example
In this example, we are creating msg() method in member inner class that is accessing the private
data member of outer class.
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){[Link]("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. [Link] in=[Link] Inner();
9. [Link]();
10. }
11. }
The java compiler creates two class files in case of inner class. The class file name of inner class
is "Outer$Inner". If you want to instantiate inner class, you must have to create the instance of
outer class. In such case, instance of inner class is created inside the instance of outer class.
The java compiler creates a class file named Outer$Inner in this case. The Member inner class
have the reference of Outer class that is why it can access all the data members of Outer class
including private.
1. import [Link];
2. class Outer$Inner
3. {
4. final Outer this$0;
5. Outer$Inner()
6. { super();
7. this$0 = [Link];
8. }
9. void msg()
10. {
11. [Link]((new StringBuilder()).append("data is ")
12. .append([Link]$000([Link])).toString());
13. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
259
14. }
A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by two
ways:
Output:
nice fruits
1. import [Link];
2. static class TestAnonymousInner$1 extends Person
3. {
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
260
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. [Link]("nice fruits");
8. }
9. }
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){[Link]("nice fruits");}
8. };
9. [Link]();
10. }
11. }
Output:
nice fruits
1. import [Link];
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
261
5. void eat(){[Link]("nice fruits");}
6. }
Java Local Inner Class
A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
Output:
30
In such case, compiler creates a class named Simple$1Local that have the reference of the outer
class.
1. import [Link];
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = [Link];
9. }
10. void msg()
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
262
11. {
12. [Link]([Link]$000([Link]));
13. }
14. }
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is
possible to access the non-final local variable in local inner class.
Output:
50
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){[Link]("data is "+data);}
5. }
6. public static void main(String args[]){
7. [Link] obj=new [Link]();
8. [Link]();
9. }
10. }
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of Outer class because nested class is static
and static properties, methods or classes can be accessed without object.
If you have the static member inside static nested class, you don't need to create instance of static
nested class.
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
264
4. static void msg(){[Link]("data is "+data);}
5. }
6. public static void main(String args[]){
7. [Link]();//no need to create the instance of static nested class
8. }
9. }
Output:
data is 30
Java Nested Interface
An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitely.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class TestNestedInterface1 implements [Link]{
9. public void msg(){[Link]("Hello nested interface");}
10.
11. public static void main(String args[]){
12. [Link] message=new TestNestedInterface1();//upcasting here
13. [Link]();
14. }
15. }
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside the
room, we cannot access the almirah directly because we must enter the room first. In
collection frameword, sun microsystem has provided a nested interface Entry. Entry is the
subinterface of Map i.e. accessed by [Link].
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class TestNestedInterface2 implements [Link]{
8. public void msg(){[Link]("Hello nested interface");}
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
266
9.
10. public static void main(String args[]){
11. [Link] message=new TestNestedInterface2();//upcasting here
12. [Link]();
13. }
14. }
Output:hello nested interface
Yes, If we define a class inside the interface, java compiler creates a static nested class.
1. interface M{
2. class A{}
3.
Wrapper classes
Java is an object-oriented language and can view everything as an object. A simple file can be
treated as an object (with [Link]), an address of a system can be seen as an object
(with [Link]), an image can be treated as an object (with [Link]) and a simple
data type can be converted into an object (with wrapper classes). This tutorial discusses wrapper
classes.
Wrapper classes are used to convert any data type into an object.
The primitive data types are not objects; they do not belong to any class; they are defined in the
language itself. Sometimes, it is required to convert data types into objects in Java language. For
example, upto JDK1.4, the data structures accept only objects to store. A data type is to be
converted into an object and then added to a Stack or Vector etc. For this conversion, the
designers introduced wrapper classes.
What are Wrapper classes?
As the name says, a wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type. It can be compared
with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from
pollution. The user takes the chocolate, removes and throws the wrapper and eats it. For ex:-
The int data type k is converted into an object, it1 using Integer class. The it1 object can be
used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = [Link]();
[Link](m*m); // prints 10000
1. To convert simple data types into objects, that is, to give object form to a data type; here
constructors are used.
2. To convert strings into data types (known as parsing operations), here methods of type
parseXXX() are used.
The following program expresses the style of converting data type into an object and at the same
time retrieving the data type from the object.
The most common methods of the Integer wrapper class are summarized in below table. Similar
methods for the other wrapper classes are found in the Java API documentation.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
For example
1. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
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
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
273
the current package.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. [Link]();
10. }
11. }
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
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. [Link] and [Link] packages
contain Date class.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. [Link]();
8. }
9. }
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
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 [Link];
2. class Simple{
3. public static void main(String args[]){
4. [Link]("Hello subpackage");
5. }
6. }
To Compile: javac -d . [Link]
There is a scenario, I want to put the class file of [Link] source file in classes folder of c:
drive. For example:
1. //save as [Link]
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. [Link]("Welcome to package");
7. }
8. }
To Compile:
e:\sources> javac -d c:\classes [Link]
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
Output:Welcome to package
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. //save as [Link] otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as [Link]
2.
3. package javaxyz;
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.
Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc
JDBC Driver
Example :-
import [Link].*;
[Link](e);
}
}}
ResultSet interface (Scrollable & Updateable)
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor
points to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import [Link].*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. [Link]("[Link]");
6. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
7. Statement stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);
8. ResultSet rs=[Link]("select * from emp765");
9.
10. //getting the record of 3rd row
11. [Link](3);
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13.
14. [Link]();
15. }}
The metadata means data about data i.e. we can get further information from the data.
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
284
If you have to get metadata of a table like total number of column, column name, column type
etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
1. import [Link].*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("select * from emp");
11. ResultSet rs=[Link]();
12.
13. ResultSetMetaData rsmd=[Link]();
14.
15. [Link]("Total columns: "+[Link]());
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
285
16. [Link]("Column Name of 1st column: "+[Link](1));
17. [Link]("Column Type Name of 1st column: "+[Link](1)
);
18.
19. [Link]();
20.
21. }catch(Exception e){ [Link](e);}
22.
23. }
24. }
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
JDBC RowSet
The instance of RowSet is the java bean component because it has properties and java bean
notification mechanism. It is introduced since JDK 5.
It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to
use.
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
Advantage of RowSet
Let's see the simple example of JdbcRowSet without event handling code.
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. while ([Link]()) {
24. // Generating cursor Moved event
25. [Link]("Id: " + [Link](1));
26. [Link]("Name: " + [Link](2));
27. [Link]("Salary: " + [Link](3));
28. }
29.
30. }
Brain Mentors Pvt. Ltd.
23, 1st floor, Block – C, Pocket – 9, Sector -7,Opp. To Metro Pillar No. 400,Rohini, Delhi
287
31. }
Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another consistent state.
Durability means once a transaction has been committed, it will remain so, even in the event of
errors, power loss etc.
fast performance It makes the performance fast because database is hit at the time of commit.
1. import [Link].*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
6. [Link](false);
7.
8. Statement stmt=[Link]();
9. [Link]("insert into user420 values(190,'abhi',40000)");
10. [Link]("insert into user420 values(191,'umesh',50000)");
11.
12. [Link]();
13. [Link]();
14. }}