Java Notes - Know Program
Java Notes - Know Program
Language Notes
Know Program
Index
1. Introduction to Programming --------------------------------------- 3
2. Introduction to Java Programming ----------------------------------- 4
3. Java Language Fundamentals ----------------------------------------- 7
1. Tokens in Java -------------------------------------------------- 7
2. Identifiers in Java --------------------------------------------- 7
3. Keywords in Java ------------------------------------------------ 8
4. Variables and Data Types ---------------------------------------- 10
5. Literals in Java ------------------------------------------------ 11
6. Escape Sequence in Java ----------------------------------------- 11
7. Operators in Java ----------------------------------------------- 12
8. Comments in Java ------------------------------------------------ 15
9. Java Basic Program Examples ------------------------------------- 16
4. Control Flow Statements in Java ------------------------------------ 17
1. Conditions in Java ---------------------------------------------- 17
2. Loop Control Instruction in Java -------------------------------- 20
3. Flow Control Program Examples ----------------------------------- 24
5. Array in Java ------------------------------------------------------ 27
1. Single & Multidimensional Array --------------------------------- 27
2. Arrays Class ---------------------------------------------------- 29
3. Array Program Examples ------------------------------------------ 31
6. String in Java ----------------------------------------------------- 33
7. Methods in Java ---------------------------------------------------- 37
8. Introduction to OOPs ----------------------------------------------- 40
1. Modifiers in Java ----------------------------------------------- 42
2. Getters and Setters --------------------------------------------- 43
3. Constructors in Java -------------------------------------------- 45
4. Inheritance in Java --------------------------------------------- 47
5. Abstract classes and Methods ------------------------------------ 50
6. Interfaces in Java ---------------------------------------------- 52
7. Polymorphism in Java -------------------------------------------- 54
9. Packages in Java --------------------------------------------------- 55
10. Multithreading in Java ---------------------------------------------------------------------------------------------------- 60
11. Error & Exception in Java -------------------------------------------------------------------------------------------------- 64
1. Errors in Java -------------------------------------------------- 64
2. Exceptions in Java ---------------------------------------------- 66
3. Exception Handling ---------------------------------------------- 67
12. File Class in Java ------------------------------------------------------------------------------------------------------------ 73
13. Collection Framework in Java ------------------------------------------------------------------------------------------- 76
14. Others -------------------------------------------------------------------------------------------------------------------------- 80
1. Creating our own Java Documentation ------------------------- 80
2. Annotations in Java ------------------------------------------- 81
3. Java Lambda Expressions -------------------------------------- 82
4. Generics in Java ---------------------------------------------- 82
5. File handling in Java ----------------------------------------- 83
6. Web Application ----------------------------------------------- 84
7. Java Servlets ------------------------------------------------- 87
8. Introduction to JSPs ----------------------------------------- 89
9. MVC in Java --------------------------------------------------- 91
10. Hibernate Framework -------------------------------------------------------------------------------------------- 92
11. Spring Framework -------------------------------------------------------------------------------------------------- 93
Programming language is the way of communication between the user and a computer.
Examples of programming language are C, C++, Java, Python e.t.c
Java was developed by SUN microsystems, Inc. (Sun for short) for developing internet-based,
high performance, distributed, dynamically extensible applications. Oracle Corporation acquired
Sun microsystems on January 27, 2010; Now, Java is owned by Oracle Corporation.
Java was invented by James Gosling. He, with his team of 11 members, invented the Java
language in SUN microsystems.
Features of Java
Java came into the market with the main 10 following features.
1. Simple
2. Secure
3. Robust
4. Portable
5. Architectural natural
6. OOP
7. Multithread
8. High performance
9. Distributed
10. Dynamic natural
Applications of Java
Desktop applications. Example:- Calculator, Trader Console
Web servers and applications servers
Enterprise applications. Example:- bank applications.
Interoperable applications. Example:- Facebook
Mobile applications. Example:- Android apps
Gaming applications
Robotics application
Database connections like Oracle database e.t.c.
Step1:- To Run Java programs in windows, Download the latest version of JDK from the Oracle
website. Download .exe or .zip file.
Step2:- Install the downloaded .exe file. Or, for .zip file just extract it.
Step3:- Go to the Advanced system setting.
Step4:- Click on Environment variables.
Step5:- In this Window, in the User variables section or System variables section, we must
create a Path.
Step6:- Add, Variable name = “path”
Step7:- Now, check if the installation is done correctly or not. Open, Command prompt (cmd)
and type java -version.
Class block:- Only class allows us to define the method with logic.
The main method:- It is the initial point of class logic execution.
Print statement:- All kinds of data are printed using this statement.
Output:-
Hello, World!
Read More:-
Java Hello World Program
Different ways to set the Java path
Set classpath environment variables
Every word or symbol written in the below Java program will come under any one of the above
five tokens.
Output:-
10.5
false
Hello
There are certain rules for defining an identifier. If we define any basic programming element
without a name then we will get a compile-time error: <identifier> expected.
In Java, there are 64 reserved words, among them 51 are keywords, 3 are literals and 10
restricted words are there.
abstract finally
native throw
transient throws
volatile assert
synchronized
strictfp
Other keyword
_ (Underscore)
Reserved literals
Boolean literals:- true, and false
Null literals:- null
Restricted Words
module
requires
transitive
exports
open
opens
to
provides
with
uses
In order to read data from the keyword, java has a scanner class. Scanner class has a lot of
methods to read the data from the keyword.
Variables in Java
A variable is a named memory location which is used for storing one value or one object
reference. An object is also a memory location but it is used for storing multiple values/objects.
This value can be changed during the execution of the program.
int number = 5;
Here,
int - data type
number - variable name
5 - value it stores
Based on the different types of data we store in the program, Java supports 7 types of literals.
1 Integral literals
2 Floating-point literals
3 Character literals
4 Conditional literals
5 String literals
6 Null Literals
\b Backspace \u0008
\\ Backslash \u005c
There are many types of operators in Java which are given below:-
1. Unary Operator
2. Arithmetic Operator
3. Shift Operator
4. Relational Operator
5. Bitwise Operator
6. Logical Operator
7. Ternary Operator
8. Assignment Operator
Arithmetic Multiplicative * / %
Additive + -
Equality == !=
Bitwise exclusive OR ^
Bitwise inclusive OR |
Logical OR ||
Ternary Ternary ? :
Associativity of Operators
Associativity tells the direction of execution of operators. It can either be left to right or right to
left.
Increment and decrement operators in Java are also known as unary operators because they
operate on a single operand. The increment operator (++) adds 1 to its operand and the
decrement operator (- -) subtracts one.
Syntax:-
x = ++a 4 5 5
x = a++ 4 5 4
x = --a 4 3 3
4
x = a-- 4 3
Comments are totally ignored by Java compilers. The compiler will not generate bytecodes for
these comments. So, comments do not appear in the .class file.
All these are decisions which depend on a certain being met. In java, we can execute
instructions on the conditions being met.
1. If-else statement
2. Switch statement
If-else Statement
The Java if statement is used to test the condition. It checks boolean conditions: true or false.
There are various types of if statements in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
if Statement:- The Java if statement tests the condition. It executes the if block if the condition
is true.
Syntax:-
if(condition){
//code to be executed
}
if-else Statement:- The Java if-else statement also tests the condition. It executes the if block if
the condition is true otherwise the else block is executed.
Syntax:-
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else-if ladder Statement:- The if-else-if ladder statement executes one condition from
multiple statements.
Syntax:-
if(condition1) {
//code to be executed if condition1 is true
} else if(condition2) {
//code to be executed if condition2 is true
} else if(condition3) {
//code to be executed if condition3 is true
}
...
else {
//code to be executed if all the conditions are false
}
Nested if statement:- The nested if statement represents the if block within another if block.
Here, the inner if block condition executes only when the outer if block condition is true.
Syntax:-
if(condition) {
//code to be executed
if(condition) {
//code to be executed
}
}
Switch statement
The switch statement allows us to execute a block of code among many alternatives.
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Note:- “=” is used for assignment whereas “= =” is used for equality check.
You can use these conditions to perform different actions for different decisions.
The Java loop is used to iterate a part of the program several times. If the number of iterations
is fixed, it is recommended to use a loop.
For Loop:- Java for loop is used to run a block of code for a certain number of times.
Example:-
Output:-
1
2
3
4
5
6
7
8
9
10
While Loop:- The while loop is considered as a repeating if statement. If the number of iteration
is not fixed, it is recommended to use the while loop.
while (condition){
// code to be executed
// Increment or decrement statement
}
Example:-
Output:-
10
9
8
7
6
5
4
3
2
1
Do-While Loop:- Java do-while loop is called an exit control loop. Therefore, unlike while loop
and for loop, the do-while checks the condition at the end of loop body. The Java do-while loop
is executed at least once because the condition is checked after the loop body.
do {
// code to be executed / loop body
// update statement
} while (condition);
Example:-
Output:-
10
9
8
7
6
5
4
3
2
1
Break Statement
The break statement in Java terminates the loop immediately, and the control of the program
moves to the next statement following the loop.
break;
Example:-
// for loop
for (int i = 1; i <= 10; ++i) {
Output:-
1
2
3
4
5
6
Continue Statement
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In the case of an inner loop, it
continues the inner loop only.
jump-statement;
continue;
Example:-
}
}
Output:-
1
2
3
4
6
7
8
9
10
Note:-
1 Break statement completely exits the loop.
2 Continue statement skips the particular iteration of the loop.
5. Array in Java
The array in Java is a referenced data type used to create a fixed number of multiple variables
or objects of the same type to store multiple values of similar type in contiguous memory
locations with a single variable name.
Array indices start from 0 and go till n-1. Where, n is the size of the array.
Anonymous Array
In Java, an Array without having any name is called an anonymous array. Using anonymous
arrays we can pass an array with user values without the referenced variable.
Example:-
new int[] {10, 20, 30, 40};
new char[] {‘a’, ‘b’};
new int[] {}; // empty, no use
new int[][] { {40, 50}, {10, 20, 30} }; // anonymous multidimensional array
Array of Objects
In Java, like primitive values we can also create an array of objects.
Jagged Array
A multi-dimensional array with different sizes child array is called a Jagged array. It creates a
table with different sizes of columns in a row. To create a jagged array, in multidimensional
array creation we must not specify child array size instead we must assign child array objects
with different sizes.
Array Length
The length is an in-built property of the array variable, which stores the information about the
number of elements in the array.
Whenever we initialize an array then by default length property is assigned to the array and we
can access them through arrayVariable.length
Output:-
The length of the given array = 5
System.arraycopy()
The System.arraycopy() method in Java is given to copy an array to another array. It copies an
array from the specified source array, beginning at the specified position, to the specified
position of the destination array.
Argumnets:-
src:- The source array.
srcPos:- Starting position in the source array.
dest:- The destination array.
destPos:- starting position in the destination array.
length:- the number of array elements to be copied.
Since java.lang.System class is imported by default in all Java classes therefore to use
arraycopy() method there is no need to explicitly import the System class.
6. String in Java
In Java, string is basically an object that represents a sequence of char values. An array of
characters works the same as Java string. String is a sequence of characters. But in Java,
string is an object that represents a sequence of characters.
Syntax:-
<String_Type> <string_variable> = "<sequence_of_string>";
For example:-
char[] ch = {'k','n','o','w','p','r','o','g','r','a',’m’};
String s = new String(ch);
is same as:-
String s = "knowprogram";
String Constructor
The string class has a total of 15 constructors among them below 8 are regularly used
constructors. All these constructors are overloaded constructors with siblings.
1. public String()
2. public String(String s)
3. public String(StringBuffer sb)
4. public String(StringBuilder sb)
5. public String(char[] ch)
6. public String(char[] ch, int offset, int count)
7. public String(byte[] b)
8. public String(byte[] b, int offset, int length)
4) StringBuffer
Read More:- How to Define a Method to Take and Return String Data in Java
Immutable Class
Once we create an object then we can’t perform any changes on that object. If we are trying to
perform any changes, and if there will be a change in the content then with those changes a
new object will be created. If there is no change in the content then the existing object will be
reused. This behavior is nothing but immutability.
Let us understand it through an example. In Java, String is an immutable class. Therefore, its
objects are immutable objects, once a String object is created then we can’t perform any
changes on that object.
Output:-
517938326
Know Program
1100439041
Know Program – Java Tutorial
7. Methods in Java
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We are not required to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed
by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but
you can also create your own methods to perform certain actions:
Example:-
public class Main {
static void myMethod() {
// code to be executed
}
}
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example:-
Inside main() methos, call the myMethod() method:
Output:-
I just got executed!
Predefined Method:- In Java, predefined methods are the method that is already defined in the
Java class libraries and is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by calling them in the
program at any point.
User-defined Method:- The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
void return type:- When we don’t want our method to return anything, we use void as the
return type.
Statics Method:- A method that has a static keyword is known as static method. In other words,
a method that belongs to a class rather than an instance of a class is known as a static method.
We can also create a static method by using the keyword static before the method name.
Instance Method:- The method of the class is known as an instance method. It is a non-static
method defined in the class. Before calling or invoking the instance method, it is necessary to
create an object of its class. Let's see an example of an instance method.
Method Overloading
In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:
Here, the func() method is overloaded. These methods have the same name but accept
different arguments.
Note:- The return types of the above methods are not the same. It is because method
overloading is not associated with return types. Overloaded methods may have the same or
different return types, but they must differ in parameters.
Recursion in Java
A function/method that contains a call to itself is called the recursive function/method. A
technique of defining the recursive function/method is called recursion. The recursive
function/method allows us to divide the complex problem into identical single simple cases that
can be handled easily. This is also a well-known computer programming technique: divide and
conquer.
Syntax:-
returntype methodname(){
// code to be executed
methodname(); //calling same method
}
8. Introduction to OOPs
Object Oriented Programming tries to map code instructions with real world making the code
shot and easier to understand.
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
1. Coupling
2. Cohesion
3. Association
4. Aggregation
5. Composition
Objects
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
Objects are always called instances of a class. Objects are created from class in java or any
other language. Objects are those that have state and behaviour. Objects are abstract data
types (i.e., objects’ behavior is defined by a set of values and operations).
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Abstraction
Abstraction is one of the OOP Concepts in Java which is an act of representing essential
features without including background details. It is a technique of creating a new data type that
is suited for a specific application. Lets understand this one of the OOPs Concepts with
example, while driving a car, you do not have to be concerned with its internal working. Here
you just need to concern about parts like steering wheel, Gears, accelerator, etc.
Inheritance
Inheritance is a method in which one object acquires/inherits another object’s properties, and
inheritance also supports hierarchical classification. The idea behind this is that we can create
new classes built on existing classes, i.e., when you inherit from an existing class, we can reuse
methods and fields of the parent class. Inheritance represents the parent-child relationship.
Polymorphism
Polymorphism refers to one of the OOPs concepts in Java which is the ability of a variable,
object or function to take on multiple forms. For example, in English, the verb run has a different
meaning if you use it with a laptop, a foot race, and business. Here, we understand the meaning
of run based on the other words used along with it. The same also applied to Polymorphism.
Encapsulation
Encapsulation is one of the concepts in OOPs concepts; it is the process that binds together the
data and code into a single unit and keeps both from being safe from outside interference and
misuse. In this process, the data is hidden from other classes and can be accessed only
through the current class’s methods. Hence, it is also known as data hiding.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when
classes are aware of each other. If a class has the details information of another class, there is
strong coupling. In Java, we use private, protected, and public modifiers to display the visibility
level of a class, method, and field. You can use interfaces for the weaker coupling because
there is no concrete implementation.
Cohesion
Cohesion measures how the methods and the attributes of a class are meaningfully and
strongly related to each other and how focused they are in performing a single well-defined task
for the system. Cohesion is used to indicate the degree to which a class has a single, well-
focused responsibility. More cohesive classes are good to keep them for code reusability. Low
cohesive classes are difficult to maintain as they have a less logical relationship between their
methods and properties. It is always better to have highly cohesive classes to keep them well
focused for a single work.
Association
Association is a relationship between two objects. It is one of the OOP Concepts in Java which
defines the diversity between objects. In this OOP concept, all objects have their separate
lifecycle, and there is no owner. For example, many students can associate with one teacher
while one student can also associate with multiple teachers.
Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such that
child object can’t belong to another parent object. For example consider class/objects
department and teacher. Here, a single teacher can’t belong to multiple departments, but even if
we delete the department, the teacher object will never be destroyed.
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all the
child objects will be deleted automatically.
Access Modifiers
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces,
variables, methods, constructors, data members, and the setter methods. For example,
class Animal {
public void method1() {...}
private void method2() {...}
In the above example, we have declared 2 methods: method1() and method2(). Here,
Note the keyword public and private. These are access modifiers in Java. They are also known
as visibility modifiers.
Non-Access modifiers
Non-access modifiers provide information about the characteristics of a class, method, or
variable to the JVM. Seven types of Non-Access modifiers are present in Java. They are –
1 static
2 final
3 abstract
4 synchronized
5 volatile
6 transient
7 native
Getter returns the value (accessors), it returns the value of data type int, String, double, float,
etc. For the convenience of the program, getter starts with the word “get” followed by the
variable name.
While Setter sets or updates the value (mutators). It sets the value for any variable which is
used in the programs of a class, and starts with the word “set” followed by the variable name.
// constructor
Employee(String name, String designation, double salary, String city) {
this.name = name;
this.designation = designation;
this.salary = salary;
this.city = city;
}
Create a constructor:-
Outputs:-
5
Constructor Overloading
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
void display() {
System.out.println(id + " " + name + " " + age);
}
}
class Test {
public static void main(String args[]) {
Student s1 = new Student(111, "Karan");
Student s2 = new Student(222, "Aryan", 25);
s1.display();
s2.display();
}
}
Output:-
111 Karan 0
222 Aryan 25
Constructor Method
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be the same as the The method name may or may not be the same
class name. as the class name.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Example:-
Car is a Vehicle.
Orange is a Fruit.
Surgeon is a Doctor.
Dog is an Animal.
Code Example:-
class Animal {
// field and method of the parent class
String name;
Output:-
In the above example, we have derived a subclass Dog from superclass Animal. Notice the
statements,
labrador.name = "Rohu";
labrador.eat();
Here, labrador is an object of Dog. However, name and eat() are the members of the Animal
class.
Since Dog inherits the field and method from Animal, we are able to access the field and
method using the object of the Dog.
Important terminology
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Types of Inheritance
There are five types of inheritance.
1 Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass.
2 Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class.
3 Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one subclass.
4 Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can
have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritances with classes. In java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived
from interface A and B.
5 Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types
of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid
inheritance is also not possible with classes. In java, we can achieve hybrid inheritance
only through Interfaces.
In case of inheritance, child/subclass inherits the state (data members) and behavior (methods)
of parent/super class. But it does not inherits the constructor because of the following reason:
If the parent class constructor is inherited in the child class, then it can not be treated as a
constructor because the constructor name must be the same as the class name. It will be
treated as a method but now the problem is, the method should have an explicit return type
which the inherited parent class constructor can not have.
The abstract keyword is a non-access modifier, used for classes and methods:-
Abstract class is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).
Abstract method can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
Example:-
Though abstract classes cannot be instantiated, we can create subclasses from it. We can then
access members of the abstract class using the object of the subclass. For example,
Output:
This is Java programming
In the above example, we have created an abstract class named Language. The class contains
a regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the abstract class
using the object obj.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the 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. Java Interface also represents the IS-A
relationship.
interface Language {
public void getType();
public void getVersion();
}
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion().
Note:- All the methods inside an interface are implicitly public and all fields are implicitly public
static final.
To declare default methods inside interfaces, we use the default keyword. For example,
If a large number of classes were implementing this interface, we need to track all these classes
and make changes to them. This is not only tedious but error-prone as well.
To resolve this, Java introduced default methods. Default methods are inherited like ordinary
methods.
Similar to a class, we can access static methods of an interface using its references. For
example,
// create an interface
interface Polygon {
staticMethod(){..}
}
// access static method
Polygon.staticMethod();
Note:- With the release of Java 9, private methods are also supported in interfaces.
We cannot create objects of an interface. Hence, private methods are used as helper methods
that provide support to other methods in interfaces.
1) Abstract classes can have abstract and non- Interfaces can have only abstract methods.
abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the Interfaces can't provide the implementation of
5) The abstract keyword is used to declare The interface keyword is used to declare the
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using the An interface can be implemented using the
keyword "extends". keyword "implements".
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Let us interpret it with help. So, in java, the problem can be solved using an object-oriented
concept, void insertPhone(String name, int phone). So, this method is used to save the phone
number of the particular person. Similarly, we can use the same form but a different signature
means different parameters to store the alternative phone number of the person’s void
insertPhone(String name, int phone1, int phone2). One method has two different forms and
performs different operations. This is an example of polymorphism, which is method
overloading.
9. Packages in Java
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.
Creating a Package
While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown
below.
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
// save as Simple.java
package mypack;
public class Simple{
For example
javac -d . Simple.java
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).
Types of Packages
Packages are divided into two categories:-
1 Built-in Packages (packages from the Java API)
2 User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much much
more. The complete list can be found at Oracle's website:
https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contains all the classes that
belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax:-
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example:-
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read a complete line:
Example:-
Using the Scanner class to get user input:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter username: ");
Output:-
Enter username: KnowProgram
Username is: KnowProgram
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the java.util package. This package also contains date and time facilities, random-number
generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the java.util package:
Example:-
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to
store them. Just like folders on your computer:
Example:-
└── root
└── mypack
└── MyPackageClass.java
// MyPackageClass.java
package mypack;
public class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Example:-
package com.javatpoint.core;
public class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
// save as A.java
package kp;
public class A{}
// save as B.java
package kp;
public class B{}
Multithreading and Multiprocessing are used for multitasking in Java, but we prefer
multithreading over multiprocessing. This is because the threads use a shared memory area
which helps to save memory, and also, the content-switching between the threads is a bit faster
than the process.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
1 Process-based Multitasking (Multiprocessing)
2 Thread-based Multitasking (Multithreading)
Threads are independent. If an exception occurs in one thread, it doesn't affect other threads. It
uses a shared memory area.
5 Terminated (Dead): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
static void sleep() It sleeps a thread for the specified amount of time.
static void yield() It causes the currently executing thread object to pause
and allow other threads to execute temporarily.
void destroy() It is used to destroy the thread group and all of its
subgroups.
static boolean interrupted() It tests whether the current thread has been interrupted.
static int activeCount() It returns the number of active threads in the current
thread's thread group.
static boolean holdLock() It returns true if and only if the current thread holds the
monitor lock on the specified object.
static void dumpStack() It is used to print a stack trace of the current thread to the
standard error stream.
static int enumerate() It is used to copy every active thread's thread group and its
subgroup into the specified array.
ThreadGroup getThreadGroup() It is used to return the thread group to which this thread
belongs
void notify() It is used to give the notification for only one thread which
is waiting for a particular object.
static void setDefaultUncaughtEx It sets the default handler invoked when a thread abruptly
ceptionHandler() terminates due to an uncaught exception.
Output:
Thread is running…
In Java, we have the concept of errors as well as exceptions. Thus there exist several
differences between an exception and an error. Errors cannot be solved by any handling
techniques, whereas we can solve exceptions using some logic implementations. So, when an
error occurs, it causes termination of the program as errors cannot try to catch.
Run Time Errors: These errors are errors which occur when the program is running. Run time
errors are not detected by the java compiler. It is the JVM which detects it while the program is
running.
Compile Time Errors: These errors are errors which prevent the code from compiling because
of errors in the syntax such as missing a semicolon at the end of a statement or due to missing
braces, class not found, etc. These errors will be detected by the java compiler and display the
error onto the screen while compiling.
Logical Errors: These errors are due to the mistakes made by the programmer. It will not be
detected by a compiler nor by the JVM. Errors may be due to wrong ideas or concepts used by
a programmer while coding.
ClassFormatError When JVM attempts to read a class file and find that the file is
malformed or cannot be interpreted as a class file.
InstantiationError In case an application is trying to use the Java new construct for
instantiating an abstract class or an interface.
ThreadDeath Its instance is thrown in the victim thread when in thread class,
the stop method with zero arguments is invoked.
VirtualMachineError Indicate that the JVM is broken or has run out of resources,
essential for continuing operating.
UnsupportedClassVersionError When the JVM attempts to read a class file and get to know that
the major & minor version numbers in the file are unsupportable.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.
Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
// JavaExceptionExample.java
public class JavaExceptionExample {
public static void main(String args[]) {
System.out.println("JavaExceptionExample.main()");
try {
// code that may raise exception
System.out.println("try block");
int data = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("catch block");
System.out.println(e);
}
// rest code of the program
System.out.println("Rest of the code...");
}
}
Output:-
JavaExceptionExample.main()
try block
catch block
java.lang.ArithmeticException: / by zero
Rest of the code...
Exceptions Methods
Following is the list of important methods available in the Throwable class.
Method Description
public String Returns a detailed message about the exception that has
getMessage() occurred. This message is initialized in the Throwable
constructor.
public Throwable Returns the cause of the exception as represented by a
getCause() Throwable object.
public String toString() Returns the name of the class concatenated with the result of
getMessage().
public void Prints the result of toString() along with the stack trace to
printStackTrace() System.err, the error output stream.
public Returns an array containing each element on the stack trace.
StackTraceElement[] The element at index 0 represents the top of the call stack,
getStackTrace() and the last element in the array represents the method at the
bottom of the call stack.
public Throwable Fills the stack trace of this Throwable object with the current
fillInStackTrace() stack trace, adding to any previous information in the stack
trace.
try-catch block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
try{
// code that may throw an exception
} catch(Exception_class_Name ref) {
// exception handling code
}
try{
//code that may throw an exception
} finally{ }
Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Output:-
Arithmetic Exception occurs
rest of the code
Output:-
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:4)
at Main.main(Main.java:8)
In the above example, we are explicitly throwing the ArithmeticException using the throw
keyword.
Similarly, the throws keyword is used to declare the type of exceptions that might occur within
the method. It is used in the method declaration.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
// declaring the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
stream.close();
}
Output:-
java.io.FileNotFoundException: test.txt (No such file or directory)
When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.
The findFile() method specifies that an IOException can be thrown. The main() method calls this
method and handles the exception if it is thrown.
If a method does not handle exceptions, the type of exceptions that may occur within it must be
specified in the throws clause.
Note:- File class object creation doesn’t not create any physical files, it only creates instance of
the File class.
Return
Method Description
Type
createNewFile()
It creates an empty normal file with the given name in the given
boolean throws
IOException path.
boolean mkdir() It creates a directory with a given name in the given path.
Return
Method Description
Type
listFiles(FilenameFilter It returns all file and subdirectory names whose names are
File[ ]
filter) matched with a given filter as File objects using File array.
In the above five methods:- The array will be empty if the directory is empty. They return null if
the abstract path name is not a directory, or if an I/O error occurs.
For example, the LinkedList class of the collections framework provides the implementation of
the doubly-linked list data structure.
Collection class is available in java.util package. Collection class also provides static methods
for sorting, searching, etc.
Method Description
public boolean addAll(Collection<? extends E> It is used to insert the specified collection
c) elements in the invoking collection.
default boolean removeIf(Predicate<? super E> It is used to delete all the elements of the
filter) collection that satisfy the specified predicate.
Other Problems
1. City Library Fine Report in Java
2. Drivers License Exam Java Program
14. Others
JavaDoc Tool
JavaDoc tool is a document generator tool in Java programming language for generating
standard documentation in HTML format. It generates API documentation. It parses the
declarations ad documentation in a set of source files describing classes, methods,
constructors, and fields.
The JavaDoc comments are different from the normal comments because of the extra asterisk
at the beginning of the comment. It may contain the HTML tags as well.
// Single-Line Comment
/*
* Multiple-Line comment
*/
/**
* JavaDoc comment
*/
They provide additional information about the program to the compiler but are not part of the
program itself. These annotations do not affect the execution of the compiled program.
@interface MyAnnotation{ }
Types of Annotation
There are three types of annotations.
1 Marker Annotation
2 Single-Value Annotation
3 Multi-Value Annotation
Syntax:-
Expressions are limited. They have to immediately return a value, and they cannot contain
variables, assignments or statements such as if or for. In order to do more complex operations,
a code block can be used with curly braces. If the lambda expression needs to return a value,
then the code block should have a return statement.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and
user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is
possible to create classes that work with different data types. An entity such as class, interface,
Generic class
A class that can refer to any type is known as a generic class. Here, we are using the T type
parameter to create the generic class of specific type.
Let's see a simple example to create and use the generic class.
The T type indicates that it can refer to any type (like String, Integer, and Employee). The type
you specify for the class will be used to store and retrieve the data.
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:-
1 T - Type
2 E - Element
3 K - Key
4 N - Number
5 V - Value
us to store the output of any particular program in a file and allows us to perform certain
operations on it.
2. In simple words, file handling means reading and writing data to a file.
Streams in Java
1. In Java, a sequence of data is known as a stream.
2. This concept is used to perform I/O operations on a file.
Important point:-
Create NewFile() method: Creates a file object
For reading files we can use the same Scanner class and supply it a file object.
To delete a file in Java we can use File object’s delete() method.
The application server performs the task that is requested by the clients, which also may need a
database to store the information sometimes. Application server technologies range from
ASP.NET, ASP, and ColdFusion to PHP and JSP.
A client is a software that allows users to request and assist them in communicating with the
server. The web browsers are the clients in a web application; some leading clients are Google
Chrome, Firefox, Safari, Internet Explorer, etc.
The HTTP stands for HyperText Transfer Protocol; it is a communication protocol between the
client and the server. It runs on top of the TCP/IP protocol.
HTTP Method: The HTTP method defines an action to be performed; usually, they are GET,
POST, PUT, etc.
URL: URL is a web address that is defined while developing a web application. It is used to
access a webpage.
Form Parameters: The form parameter is just like an argument in a Java method. It is passed
to provide the details such as user, password details on a login page.
What is URL
URL stands for Universal Resource Locator used to locate the server and resource. It is the
address of a web page. Every web page on a project must have a unique name.
Where,
http or https: It is the starting point of the URL that specifies the protocol to be used for
communication.
localhost: The localhost is the address of the server. When we run our application
locally, it is called localhost; if we deployed our project over the web, then it is accessed
by using the domain name like "javatpoint.com". The domain name maps the server to
IP addresses.
8080: This is the port number for the local server; it is optional and may differ in different
machines. If we do not manually type the port number in the URL, then by default, the
request goes to the default port of the protocol. Usually, the port no between 0 to 1023
are reserved for some well-known services such as HTTP, HTTPS, FTP, etc.
What is Servlet
A Servlet is a Java program that runs within a web server; it receives the requests and responds
to them using related protocols (Usually HTTP). The Servlets are capable enough to respond to
any type of request; they are commonly used to make the application functional.
We can create a static website using only HTML and CSS, but when it comes to dynamic, we
need a server-side programming language. For these applications, Java provides Servlet
technology, which contains HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages contain interfaces and classes for creating
servlets. All servlets should implement the Servlet interface, which defines life-cycle methods.
To implement a generic service, we can use the GenericServlet class by extending it. It provides
doGet and doPost methods to handle HTTP-specific services.
The Servlets and JSPs are server-side technologies that extend the functionality of a web
server. They support dynamic response and data persistence. We can easily create a web
application using these technologies.
Web Container
Tomcat is a web container, when a request is made from Client to web server, it passes the
request to web container and it’s web container job to find the correct resource to handle the
request (servlet or JSP) and then use the response from the resource to generate the response
and provide it to web server. Then the web server sends the response back to the client.
When the web container gets the request and if it’s for servlet then the container creates two
Objects HTTPServletRequest and HTTPServletResponse. Then it finds the correct servlet
based on the URL and creates a thread for the request. Then it invokes the servlet service()
method and based on the HTTP method service() method invokes doGet() or doPost() methods.
Servlet methods generate the dynamic page and write it to the response. Once the servlet
thread is complete, the container converts the response to HTTP response and sends it back to
the client.
Lifecycle and Resource Management:- Container takes care of managing the life cycle of
servlets. The container takes care of loading the servlets into memory, initializing servlets,
invoking servlet methods and destroying them. The container also provides utilities like JNDI for
resource pooling and management.
Multithreading Support:- Container creates a new thread for every request to the servlet and
when it’s processed the thread dies. So servlets are not initialized for each request and save
time and memory.
JSP Support:- JSPs don't look like normal java classes and web containers provide support for
JSP. Every JSP in the application is compiled by container and converted to Servlet and then
container manages them like other servlets.
Miscellaneous Task:- Web container manages the resource pool, does memory optimizations,
runs garbage collector, provides security configurations, support for multiple applications, hot
deployment and several other tasks behind the scene that makes our life easier.
Also see:-
1. Servlet Container – How It Works
2. What is Tomcat Server
3. Tomcat Installation Directory
4. Server-Side Programming
5. Servlet in Java – Introduction
6. Simple Servlet Program in Java
7. Servlet Architecture & Workflow
8. Auto Refresh Servlet Page
9. MIME Type in Java Servlet
10. HttpServlet Class in Servlet
11. doGet() and doPost() method
12. HTML to Servlet Communication
13. HTML to Servlet using Hyperlinks
14. Add Tomcat Server in Eclipse
15. Tomcat failed to start in Eclipse
16. Simple Eclipse Java Web Application
17. Welcome File list in web.xml
18. HTML to Servlet using Forms
19. Form Validation in Servlet
20. Servlet to HTML using JavaScript
21. GET vs POST Request Method
22. HTTP Request Methods
23. Servlet Life Cycle
24. Load on Startup in Servlet
25. ServletConfig Interface
26. ServletContext Interface
27. ServletConfig vs ServletContext
28. Database Connectivity in Servlet
29. Servlet to MySQL Database in Eclipse
What is CGI?
CGI is actually an external application that is written by using any of the programming
languages like C or C++ and this is responsible for processing client requests and generating
dynamic content.
In CGI application, when a client makes a request to access dynamic Web pages, the Web
server performs the following operations:-
1. It first locates the requested web page i.e the required CGI application using URL.
2. It then creates a new process to service the client’s request.
3. Invokes the CGI application within the process and passes the request information to the
application.
4. Collects the response from the CGI application.
5. Destroys the process, prepares the HTTP response, and sends it to the client.
JSP syntax
Syntax available in JSP are following
Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>
2. Java Scriplets:- It allows us to add any number of JAVA code, variables and expressions.
Syntax:-
<% java code %>
Syntax:-
<%= expression %>
Example:-
<% num1 = num1+num2 %>
4. JSP Comments:- It contains the text that is added for information which has to be ignored.
Syntax:-
<%-- This is JSP comment --%>
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.
index.jsp
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
Read More:-
1. JSP vs Servlet
2. JSP in Java
3. JSP vs HTML
4. Overview to Java Server Pages (JSP)
Hibernate develops persistence logic, which stores and processes the data for longer use. It is
lightweight and an ORM tool, and most importantly open-source which gives it an edge over
other frameworks.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The javax.persistence package contains the JPA classes and
interfaces.
Hibernate almost supports all the major RDBMS which makes it efficient and easy to work with.
A key element of Spring is infrastructural support at the application level: Spring focuses on the
"plumbing" of enterprise applications so that teams can focus on application-level business
logic, without unnecessary ties to specific deployment environments.
Spring framework is an open source Java platform. It was initially written by Rod Johnson and
was first released under the Apache 2.0 license in June 2003.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules on the next page. Let's understand the IOC and
class Employee{
Address address;
Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:-
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
}
Thus, IOC makes the code loosely coupled. In such a case, there is no need to modify the code
if our logic is moved to new environment.
In the Spring framework, IOC container is responsible to inject the dependency. We provide
metadata to the IOC container either by XML file or annotation.