Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
java traning report_Summer.docx
1. “Java technology”
A Industrial Training Report
Submitted
in partial fulfillment
for the award of the Degree of
Bachelor of Technology
in Department of Computer Science & Engineering
(With specialization in Computer Science & Engineering)
Guided By: Submitted By:
Mr. Arvind Sharma Harsh , Krati , Gaurav Sharma,
Bhanushi , Hetain , Chirag
Department of Computer Science & Engineering
Modern Institute of Technology & Research Centre
Bikaner Technical University, Bikaner
November, 2021
2. ACKNOWLEDGEMENT
Firstly, we would like to express our gratitude to our advisor for the
beneficial comments and remarks.
It gives us immense pleasure to express our sincere thanks towards Mr.
Neha Gopaliya CSE Department, Modern Institute of Technology &
Research Centre, Alwar for their constant support and guidance
throughout the course of this work. Their sincerity, thoroughness and
preservance have been a constant source of inspiration for us.
I would like to thank my institution and my faculty members without
whom this project would have been a distant reality, I also entend my
heartiest thanks to my family and well wishers.
- Prachi Sethi
3. TABLE OF CONTENT
Certificate
Acknowledgement
1. Introduction to java
………………………………………………………1
1.1 What is Java……………………………………………………………....1
1.2 Java Basic Syntax………………………………………………….……..3
1.3 Java Identifiers…………………………………………………………....5
1.4 Java Arrays…………………………………………………………….….6
1.5 Java Enums…………………………………………………………….....6
1.6 Java Keywords…………………………………………………………....6
1.7 Inheritance……………………………….…….……………………….…7
1.8 Interfaces……………………………………………………………….....8
1.9 Features of Java……………………………………………………….....8
1.10 Constructor……………………………………………………………....9
1.11 Creating an object………………………………………………….…...9
1.12 Java Packages…………………………………………………….…..10
1.13 Import Statement……………………………………………………....10
2.Access Specifiers in
Java………………………………………………..11
2.1 Introduction………………………………………………..……………..11
2.2 Private Access Specifier…………………………………..……….…...11
2.3 Default Access Specifier………………………………..……………...12
2.4 Protected Access Specifier………………………………….…….…...12
4. 2.5 Public Access Specifier…………………………………….………......12
3. Inheritance In Java
……………………………………………………...13
3.1 Why we use Inheritance in Java……………………………………….13
3.2 Syntax of Inheritance………………………………………….……..…13
3.3 Example of Inheritance……………………………………………...….14
3.4 Types of Inheritance……………………………………….………...….14
3.4.1 Single Level Inheritance……………………………………....14
3.4.2 Multilevel Level Inheritance…………………………………...15
3.4.3 Hierarchical Level Inheritance………………………………..16
4. Polymorphism
…………………………………………………………..18
4.1 Method Overloading in Java…..………………………………………18
4.2 Method Overriding in Java……………………..................................19
4.3 Super Keyword in Java..………………………………………….......21
4.4 Final Keyword in Java...…………………….......................................23
4.5Static and Dynamic Binding in Java……………………………….…..26
5. Abstraction
………………………………………………………….…….29
5.1 Abstract Class……………………………………………………………29
5.2 Interface in Java………………………………..….………………….…31
12. Reference……………………………………………………………….61
5. CHAPTER 1:INTRODUCTION TO JAVA
1.1 WHAT IS JAVA?
Java is a high-level programming language originally developed by Sun
Microsystems and released in 1995. Java runs on a variety of platforms,
such as Windows, Mac OS, and the various versions of UNIX. This
tutorial gives a complete understanding of Java. This reference will take
you through simple and practical approaches while learning Java
Programming language.
Why to Learn java Programming?
Java is a MUST for students and working professionals to become a
great Software Engineer specially when they are working in Software
Development Domain. I will list down some of the key advantages of
learning Java Programming:
Object Oriented − In Java, everything is an Object. Java can be
easily extended since it is based on the Object model.
Platform Independent − Unlike many other programming
languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever
platform it is being run on.
6. 1
1 Simple − Java is designed to be easy to learn. If you understand
the basic concept of OOP Java, it would be easy to master.
2 Secure − With Java's secure feature it enables to develop virus-
free, tamper-free systems. Authentication techniques are based
on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-
neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java
runtime system.
Portable − Being architecture-neutral and having no
implementation dependent aspects of the specification makes
Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
Robust − Java makes an effort to eliminate error prone situations
by emphasizing mainly on compile time error checking and
runtime checking.
Multithreaded − With Java's multithreaded feature it is possible to
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native
machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java
2
enables high performance.
Distributed − Java is designed for the distributed environment of
the internet.
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.
Hello World using Java programming
7. publicclassMyFirstJavaProgram{
publicstaticvoid main(String[]args){
System.out.println("Hello World");// prints Hello World
}
}
1.2 JAVA BASIC SYNTAX
When we consider a Java program, it can be defined as a collection of
objects that communicate via invoking each other's methods. Let us
now briefly look into what do class, object, methods, and instance
variables mean.
Object − Objects have states and behaviors. Example: A dog has
states - color, name, breed as well as behavior such as wagging
their tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that
3
describes the behavior/state that the object of its type supports.
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.
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. If several words are used to form a name of the
class, each inner word's 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.
8. 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).
4
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).
But please make a note that in case you do not have a public
class present in the file then file name can be different than class
name. It is also not mandatory to have a public class in the file.
public static void main(String args[]) − Java program
processing starts from the main() method which is a mandatory
part of every Java program.
1.3 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.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
5
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
1.4 JAVA ARRAYS
9. 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.
1.5 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 small, medium, or large.
1.6 JAVA KEYWORDS
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.
6
Some keywords are:
Abtract
Boolean
Break
Byte
Class
Void
Char
Throw
While
Try
Static
10. If
and many more
1.7 INHERITANCE
In Java, classes can be derived from classes. Basically, if you need to
create a new class and here is already a class that has some of the
code you require, then it is possible to derive your new class from the
already existing code.This concept allows you to reuse the fields and
methods of the existing
7
class without having to rewrite the code in a new class. In this scenario,
the existing class is called the superclassand the derived class is called
the subclass.
1.8 INTERFACES
In Java language, an interface can be defined as a contract between
objects on how to communicate with each other. Interfaces play a vital
role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class (subclass) should
use. But the implementation of the methods is totally up to the subclass.
1.9 FEATURES OF JAVA
Java is an Object-Oriented Language. As a language that has the
Object-Oriented feature, Java supports the following fundamental
concepts –
Polymorphism
Message passing
Inheritance
Method
Object
11. Class
8
Abstraction
Platform Independent
Object − Objects have states and behaviors. Example: A dog has states
-color, name, breed as well as behaviors – wagging the tail, barking,
eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes
the behavior/state that the object of its type support.
1.10 CONSTRUCTORS
When discussing about classes, one of the most important sub topic
would be constructors. Every class has a constructor. If we do not
explicitly write a constructor for a class, the Java compiler builds a
default constructor for that class.
Each time a new object is created, at least one constructor will be
invoked. The main rule of constructors is that they should have the
same name as the class. A class can have more than one constructor.
1.11 CREATING AN OBJECT
As mentioned previously, a class provides the blueprints for objects. So
basically, an object is created from a class. In Java, the new keyword is
used to create new objects.
There are three steps when creating an object from a class –
9
Declaration − A variable declaration with a variable name with an
object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a
constructor. This call initializes the new object
12. 1.12 JAVA PACKAGES
In simple words, it is a way of categorizing the classes and interfaces.
When developing applications in Java, hundreds of classes and
interfaces will be written, therefore categorizing these classes is a must
as well as makes life much easier.
1.13 IMPORT STATEMENTS
In Java if a fully qualified name, which includes the package and the
class name is given, then the compiler can easily locate the source
code or classes. Import statement is a way of giving the proper location
for the compiler to find that particular class.
10
CHAPTER 2: ACCESS SPECIFIER
2.1 INTRODUCTION
There are two types of modifiers in Java:access modifiers andnon-
access modifiers.
The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access modifier
on it. There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
13. 4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
2.2 PRIVATE ACCESS SPECIFIER
The private access modifier is accessible only within the class.
11
2.3 DEFAULT ACCESS SPECIFIER
If you don't use any modifier, it is treated as defaultby default. The
default modifier is accessible only within package. It cannot be accessed
from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.
2.4PROTECTED ACCESS SPECIFIER
The protected access modifier is accessible within package and outside
the package but through inheritance only.
The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
It provides more accessibility than the default modifier.
2.5 PUBLIC ACCESS SPECIFIER
The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
14. 12
CHAPTER 3: INHERITANCE IN JAVA
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of
OOPs (Object Oriented programming system).
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 the parent class. Moreover,
you can add new methods and fields in your current class also.
3.1 WHY WE USE INHERITANCE IN JAVA?
o For Method Overriding (so runtime polymorphism can be
achieved).
o For Code Reusability.
3.2 SYNTAX OF INHERITANCE
class Subclass-name extends Superclass-name {
//methods and fields
}
The extends keywordindicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.
In the terminology of Java, a class which is inherited is called a parent or
superclass, and the new class is called child or subclass.
13
3.3 EXAMPLE OF INHERITANCE
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
15. public static void main(String args[]){
15
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT
Programmer salary is 40000
Bonus of Programmer is 10000
3.4 TYPES OF INHERITANCE
3.4.1 SINGLE LEVEL INHERITANCE
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
14
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
OUTPUT
barking…
eating…
3.4.2 MULTILEVEL INHERITANCE
class Animal{
void eat(){System.out.println("eating...");} }
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
16. public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
15
OUTPUT
weeping…
eating…
3.4.3 HIERARCHICAL INHERITANCE
Class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
OUTPUT
meowing…
eating…
16
WHY MULTIPLE INHERITANCE IS NOT SUPPORTED IN JAVA?
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 the same method and
you call it from child class object, there will be ambiguity to call the
17. method of A or B class.Since compile-time errors are better than 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.
17
CHAPTER 4: POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single
action in different ways. Polymorphism is derived from 2 Greek words:
poly and morphs. The word "poly" means many and "morphs" means
forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.
If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
4.1 METHOD OVERLOADING IN JAVA
18. If a class has multiple methods having same name but different in
parameters, it is known asMethod Overloading.
If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but
therecan be any number of arguments, if you write the method such as
a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the
18
behavior of the method because its name differs.
Advantage of method overloading
Method overloadingincreases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
OUTPUT
22
33
19. 4.2 METHOD OVERRIDING IN JAVA
If subclass (child class) has the same method as declared in the
19
parent class, it is known as method overriding in Java.
In other words, If a subclass provides the specific implementation of
the method that has been declared by one of its parent class, it is
known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation
of a method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism
Rules forJava Method overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent
class.
3. There must be an IS-A relationship (inheritance).
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
20
obj.run();//calling method
}
}
OUTPUT
Bike is running safely
20. 4.3 SUPER KEYWORD IN JAVA
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class. In
21
other words, it is used if method is overridden.
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class
constructor.
EXAMPLE OF SUPER KEYWORD
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
21. }
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
22
}}
OUTPUT
1 ankit45000
4.4 FINAL KEYWORD IN JAVA
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.
1) Java final variable
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
22. 23
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.
1) Java final variable
If you make any variable as final, you cannot change the
value of final variable(It will be constant).
Example of final variable
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.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
OUTPUT
24
Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
23. class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
OUTPUT
Compile Time Error
2) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{
25
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
OUTPUT
Compile Time Error
4.5 STATIC AND DYNAMIC BINNDING
Connecting a method call to the method body is known as binding.
There are two types of binding
1.Static Binding (also known as Early Binding).
2.Dynamic Binding (also known as Late Binding).
24. static binding
When type of the object is determined at compiled time(by the compiler),
it is known as static binding.
If there is any private, final or static method in a class, there is static
binding.
EXAMPLE
class Dog{
26
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as
dynamic binding.
EXAMPLE
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
27
25. OUTPUT
dog is eating…
28
CHAPTER 5: ABSTARCTION
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
26. Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you 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.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
5.1 ABSTARCT CLASS
A class which is declared with the abstract keyword is known as an
abstract class in Java. It can have abstract and non-abstract methods
(method with the body).A class which is declared as abstract is known
as an abstract. It can have abstract and non-abstract methods.
29
Points to remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to
change the body of the method.
Abstract Method in Java
A method which is declared as abstract and does not have
implementation is known as an abstract method.
EXAMPLE OF ABSTRACT METHOD AND CLASS
abstract class Bike{
abstract void run();
27. }
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
OUTPUT
running safely
30
5.2 INTERFACE IN JAVA
An interface in java is a blueprint of a class. It has static constants and
abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can
be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple
inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods
declared in the interface.
SYNTAX
28. 31
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
EXAMPLE OF JAVA INTERFACE
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
OUTPUT
Hello
Q) Multiple inheritance is not supported through class in java, but it is
possible by an interface, why?
multiple inheritance is not supported in the case of class because of
32
ambiguity. However,it is
supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class. For
example:
interface Printable{
void print();
}
interface Showable{
29. void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
OUTPUT
Hello
INTERFACE INHERITANCE
A class implements an interface, but one interface extends another
interface.
33
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
OUTPUT
Hello
Welcome
30. 34
CHAPTER 6: JAVA PACKAGE
A java package is a group of similar types of classes, interfaces and
sub-packages.
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.
The package keyword is used to create a package in java.
EXAMPLE
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
35
CHAPTER 7: COLLECTIONS
31. The collection in java is a framework that provides an architecture to
store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
7.1 Java ArrayList Class
Java ArrayList class uses a dynamic array for storing the elements. It
inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the
index basis.
o In Java ArrayList class, manipulation is slow because a lot of
shifting needs to occur if any element is removed from arraylist.
36
EXAMPLE
import java.util.*;
class ArrayList1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
32. list.add("Ajay");
//Invoking arraylist object
System.out.println(list);
}
}
}
OUTPUT
[Ravi,Vijay,Ravi,Ajay]
7.2Java LinkedList Class
Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class and
implements List and Deque interfaces.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements
o Java LinkedList class maintains insertion order
.
37
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting
needs to occur.
o Java LinkedList class can be used as a list, stack or queue.
EXAMPLE
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
33. OUTPUT
Ravi
Vijay
Ravi
Ajay
7.3 Java HashSet Class
38
Java HashSet class is used to create a collection that uses a hash table
for storage. It inherits the AbstractSet class and implements Set
interface.The important points about Java HashSet class are:
o HashSet stores the elements by using a mechanism called
hashing.
o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet is the best approach for search operations.
EXAMPLE
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
39
}
OUTPUT
Five
One
Four
34. Two
Three
7.4 Java TreeSet Class
Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet
interface. The objects of the TreeSet class are stored in ascending
order.The important points about Java TreeSet class are:
o Java TreeSet class contains unique elements only like HashSet.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.
EXAMPLE
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
40
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
OUTPUT
Ajay
Ravi
Vijay
7.5 Java HashMap Class
35. Java HashMap class implements the map interface by using a hash
table. It inherits AbstractMap class and implements Map interface.
Points to remember
o Java HashMap class contains values based on the key.
o Java HashMap class contains only unique keys.
o Java HashMap class may have one null key and multiple null
values.
41
o Java HashMap class is non synchronized.
o Java HashMap class maintains no order.
7.6 Java HashTable Class
Java Hashtable class implements a hashtable, which maps keys to
values. It inherits Dictionary class and implements the Map interface.
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket.
The position of the bucket is identified by calling the hashcode()
method. A Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
EXAMPLE
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
42
System.out.println(m.getKey()+" "+m.getValue());
36. }
} }
OUTPUT
103 Rahul
102 Ravi
101 Vijay
100 Amit
43
CHAPTER 8:SERVLETS IN JAVA
Servlet technology is used to create a web application (resides at server
side and generates a dynamic web page).
Servlettechnology is robust and scalable because of java language.
Before Servlet, CGI (Common Gateway Interface) scripting language
was common as a server-side programming language. However, there
were many disadvantages to this technology. We have discussed these
disadvantages below.
37. There are many interfaces and classes in the Servlet API such as
Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse,
etc.
8.1 WHAT IS SERVLET
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes
including documentation.
o Servlet is an interface that must be implemented for creating any
Servlet.
o Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to
create a dynamic web pages.
44
8.2 ADVANTAGES OF SERVLET
There are many advantages of Servlet over CGI. The web container
creates threads for handling the multiple requests to the Servlet.
Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the
threads are low. The advantages 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: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
4. Secure: because it uses java language.
8.3HTTPSERVLET CLASS METHODS
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res)
dispatches the request to the protected service method by converting
the request and response object into http type.
38. 2. protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the service
method, and dispatches the request to the doXXX() method depending
on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
45
4. protected void doPost(HttpServletRequest req,
HttpServletResponse
res) handles the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req,
HttpServletResponse res) handles the HEAD request. It is invoked by
the web container.
6. protected void doOptions(HttpServletRequest req,
HttpServletResponse res) handles the OPTIONS request. It is invoked
by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse
res) handles the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req,
HttpServletResponse res) handles the TRACE request. It is invoked by
the web container.
9. protected void doDelete(HttpServletRequest req,
HttpServletResponse res) handles the DELETE request. It is invoked
by the web container
8.4 EVENT AND LISTENER IN SERVLET
Events are basically occurrence of something. Changing the state of an
object is known as an event.
We can perform some important tasks at the occurrence of these
exceptions, such as counting total and current logged-in users, creating
tables of the database at time of deploying the project, creating
database connection object etc.
There are many Event classes and Listener interfaces in the
javax.servlet and javax.servlet.http packages.
39. 8.5 CLASSES IN EVENTTS
46
The event classes are as follows:
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
8.6 EVENT INTERFACES
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener
8.7 LIFE CYCLE OF SERVLET
The web container maintains the life cycle of a servlet instance. Let's
see the life cycle of the servlet:
47
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
40. 1.SERVLET CLASS IS LOADED
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.
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.
3.INIT METHOD IS INVOKED
The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is the
life cycle method of the javax.servlet.Servlet interface
4.SERVICE METHOD IS INVOKED
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.
48
If servlet is initialized, it calls the service method.
5.DESTROY METHOD IS INVOKEDThe 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.
8.8STEPS TO CREATE A SERVLET
There are given 6 steps to create a servlet example. These steps are
required for all the servers.
The servlet example can be created by three ways:
1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class
41. The mostly used approach is by extending HttpServlet because it
provides http request specific method such as doGet(), doPost(),
doHead() etc.
Here, we are going to use apache tomcat server in this example. The
steps are as follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
49
5. Start the server and deploy the project
6. Access the servlet
8.9CREATING SERVLET EXAMPLE IN ECLIPSE
Eclipse is an open-source ide for developing JavaSE and JavaEE
(J2EE) application.
You need to download the eclipse ide for JavaEE developers.
Creating servlet example in eclipse ide, saves a lot of work to be done. It
is easy and simple to create a servlet example. Let's see the steps, you
need to follow to create the first servlet example.
o Create a Dynamic web project
o create a servlet
o add servlet-api.jar file
o Run the servlet
1.CREATE A DYNAMIC WEB PROJECT
For creating a dynamic web project click on File Menu -> New ->
Project..-> Web -> dynamic web project -> write your project name e.g.
first -> Finish.
42. 2.CREATE A SERVLET IN ECLIPSE IDE
50
For creating a servlet, explore the project by clicking the + icon ->
explore the Java Resources -> right click on src -> New -> servlet ->
write your servlet name e.g. Hello -> uncheck all the checkboxes except
doGet() -> next -> Finish.
3.ADD JAR FILE IN ECLIPSE IDE
For adding a jar file, right click on your project -> Build Path -> Configure
Build Path -> click on Libraries tab in Java Build Path -> click on Add
External JARs button -> select the servlet-api.jar file under tomcat/lib ->
ok.
4.START THE SERVER AND DEPLOY THE PROJECT
For starting the server and deploying the project in one step, Right click
on your project -> Run As -> Run on Server -> choose tomcat server ->
next -> addAll -> finish.
HOW TO CONFIGURE TOMCAT SERVER IN ECLIPSE?
If you are using Eclipse IDE first time, you need to configure the tomcat
server First.
For configuring the tomcat server in eclipse IDE, click on servers tab at
the bottom side of the IDE -> right click on blank area -> New -> Servers
-> choose tomcat then its version -> next -> click on Browse button ->
select the apache tomcat root folder previous to bin -> next -> addAll ->
Finish.
51
CHAPTER 9: INTERFACES IN SERVLET
9.1 ServletRequest Interface
43. An object of ServletRequest is used to provide the client request
information to a servlet such as content type, content length, parameter
names and values, header informations, attributes etc.
METHODS OF SERVLETREQUEST INTERFACE
There are many methods defined in the ServletRequest interface. Some
of them are as follows:
1. public String getParameter(String name): is used to
obtain the value of a parameter by name.
2. public String[] getParameterValues(String name): returns
an array of String containing all values of given parameter
name. It is mainly used to obtain values of a Multi select list
box.
9.2 RequestDispatcher in servlet
The RequestDispatcher interface provides the facility of dispatching the
request to another resource it may be html, servlet or jsp. This interface
can also be used to include the content of another resource also. It is
one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
52
1. Publicvoidforward(ServletRequestrequest,ServletResponse
response)throws ServletException,java.io.IOException:Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
2. publicvoidinclude(ServletRequestrequest,ServletResponseresponse)thro
-wsServletException,java.io.IOException:Includes the content of a
resource (servlet, JSP page, or HTML file) in the response.
9.3HttpServletResponse Interface
44. The sendRedirect() method of HttpServletResponse interface can be
used to redirect response to another resource, it may be servlet, jsp or
html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make
another request. So, it can work inside and outside the server.
9.4 ServletContext Interface
An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration
information from web.xml file. There is only one ServletContext object
per web application.
53
ADVANTAGES
Easy to maintain if any information is shared to all the servlet, it is better
to make it available for all the servlet. We provide this information from
the web.xml file, so if the information is changed, we don't need to
modify the servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
There can be a lot of usage of ServletContext object. Some of them are
as follows:
1. The object of ServletContext provides an interface between the
container and servlet.
2. The ServletContext object can be used to get configuration information
from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute
from the web.xml file.
4. The ServletContext object can be used to provide inter-application
communication.
9.5HttpSession Interface
45. In such case, container creates a session id for each user.The container
uses this id to identify the particular user.An object of HttpSession can
be used to perform two tasks:
54
1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
55
46. CHAPTER 10 : COOKIE
10.1 COOKIE IN SERVLET
A cookie is a small piece of information that is persisted between the
multiple client requests.
A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number.
10.2 HOW COOKIE WORK
By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the
user, cookie is added with request by default. Thus, we recognize the
user as the old user.
10.3 TYPES OF COOKIE
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
10.4ADVANTAGES AND DISADVANTAGES OF COOKIE
ADVANTAGE
56
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
DISADVANTAGE
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
47. 57
CHAPTER 11: JAVA SERVER PAGES
JSP technology is used to create web application just like Servlet
technology. It can be thought of as an extension to Servlet because it
provides more functionality than servlet such as expression language,
JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are
easier to maintain than Servlet because we can separate designing and
development. It provides some additional features such as Expression
Language, Custom Tags, etc.
Advantages of JSP over Servlet:
There are many advantages of JSP over the Servlet. They are as
follows:
48. 1.Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all
the features of the Servlet in JSP. In addition to, we can use implicit
objects, predefined tags, expression language and Custom tags in JSP,
that makes JSP development easy.
2.Easy to Maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. In Servlet technology, we mix our
58
business logic with the presentation logic.33.
3.Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the
project. The Servlet code needs to be updated and recompiled if we
have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags,
etc. that reduces the code. Moreover, we can use EL, implicit
objects,etc.
11.1 The Lifecycle of a JSP Page
The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
49. o Destroy ( the container invokes jspDestroy() method).
59
11.2 CREATING A JSP PAGE
index.jsp
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
OUTPUT
It will print 10 on the Browser.
60
REFERENCES
50. 1.Head First Java:Head First Java was the first java
related book that I read.This is a great book and one
should read it.the book is simple and easy to relate java
programming concept to real life. The book is used for
the core part of java.
2.Effective Java :This book contains 78 best practices
program.Book used for the writing programs.
3.Javatpoint:The site is the combination of well short
codes and theory.Short dedinations are taken from it
4.Tutorialspoint:The site makes everyone understand
the Java ver easily.The site helped me to took some part
of concepts.
61