You are on page 1of 95

Java Programming

Language Notes

Know Program

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 2

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 3

1. Basic of Programming Language


What is Programming?
Just like we use English, Hindi or other languages to communicate with each other, we use the
programming language to communicate with the computer. A programming language is an
artificial language designed to express computations that can be performed by a machine,
particularly by a computer. It can be used to create programs that control the behavior of a
machine, to express algorithms precisely, or as a mode of human communication.

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

Types of Programming Language


There are three types of Programming languages:-

Low-Level Programming Language


 Machine Language
 Assembly Languages or Symbolic Languages

Middle-level Programming language


 C Programming Language

High-level Programming language


 Java, Python, etc..

Read More:- Basic of Programming Language

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 4

2. Introduction to Java Programming


Java is a simple, secured, high level, platform-independent, multithread, Object-oriented
programming language. Java has its own software-based platform called JVM (Java virtual
machine) to execute the programs.

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.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 5

Read more:- Introduction to Java Programming

JDK vs JRE vs JVM vs JIT


JDK provides an environment to develop and run Java applications.
JRE provides an environment just to run Java applications.
JVM is responsible to run the Java program line by line.
JIT helps interpreters for executing Java byte code fastly.

Read more:- JDK JRE JVM JIT in Java

How Java Works?


Java is compiled into the bytecode and then it is interpreted to machine code.

Java (Oracle JDK) Installation in Windows:-

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.

Read More:- How to run a Java program

Basic Structure of Java Program

public class Main {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Essential statements of Java program:-

 Class block:- Only class allows us to define the method with logic.
 The main method:- It is the initial point of class logic execution.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 6

 Print statement:- All kinds of data are printed using this statement.

Simple Hello World Program in Java


// FirstProgram.java
public class FirstProgram {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output:-
Hello, World!

Read More:-
 Java Hello World Program
 Different ways to set the Java path
 Set classpath environment variables

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 7

3. Java Language Fundamentals


3.1) Tokens in Java
Java supports five different tokens:-
1 Identifiers
2 Keywords
3 Literals
4 Operators
5 Special Symbols

Every word or symbol written in the below Java program will come under any one of the above
five tokens.

public class Main {


public static void main(String[] args) {
int number = 9;
double variable = 1.5;
System.out.println(number + variable);
System.out.println(variable == number);
System.out.println("Hello");
}
}

Output:-
10.5
false
Hello

Read more:- Tokens in Java

3.2) Identifiers in Java


The name of the basic programming element is called Identifier. The identifiers in Java are used
for identifying or finding a programming element from other parts of the program or project.

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.

Read more:- Identifiers in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 8

3.3) Keywords in Java


A predefined identifier that has special meaning in a Java program outside comment and string
is called a Keyword.

In Java, there are 64 reserved words, among them 51 are keywords, 3 are literals and 10
restricted words are there.

Integer values Floating point values Non-numeric values


 byte  float  char
 short  double  boolean
 int  void
 long

Conditional statements Keywords used in loop Control transfer keywords


 if  do  break
 else  while  continue
 switch  for  return
 case
 default

Access Modifiers keywords Class related keywords Object representation


 private  class  this
 protected  interface  super
 public  enum  instanceof
 new

Package related keywords Inheritance relationship Unused Keywords


related keywords
 import  extends  goto
 package  implements  const

Keywords used for modifiers Exception Handling Keywords


 static  try
 final  catch

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 9

 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

Read More:- Java Keywords

Reading Data From the Keyword

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.

// read from the keyword


Scanner scan = new Scanner(System.in);
// method to read from the keyword
int number = scan.nextInt();

3.4) Variables and Data Types


Just like we have some rules that we follow to speak English (the grammar), we have some
rules to follow while writing a java program. The set of these rules is called syntax.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 10

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

Rules for declaring a variable name:-


1. A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
two special characters such as _ underscore and $ dollar sign.
2. The first character must not be a digit.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive.
6. The maximum length of the variable is 64 characters.
7. Variable names always should exist on the left-hand side of assignment operators.

Here are a few valid Java variable name examples:-


 myvar
 myVar
 MYVAR
 _myVar
 $myVar
 myVar1
 myVar_1

Data Types in Java


In Java, a keyword that is used for creating variables and objects for storing single or multiple
values is called data types.

Java supports two types of data types:-


1. Primitive Data types
2. Referenced Data type

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 11

1. Primitive Data types


Numeric data types
 integer data types (int, double, char, boolean)
 floating-point data types (float, double)

Non-Numeric data types


 char
 boolean

2. Referenced Data type


 Array
 class
 Interface

Read More:- Data Types in Java

3.5) Literals in Java


Any constant value in the program is called a literal. Literals in Java are used to represent value
or assign variables value. Examples of literals:- 9, 9.5, ‘a’, "a", true, false, null, and e.t.c.

Types of Literals in Java

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

Read More:- Literals in Java

3.6) Escape Sequence in Java


In Java, the escape sequence is a character preceded by a backslash (\) and it has special
meaning to the compiler, JVM, Console, and Editor software. Every escape character must start
with ‘\’ following by a single character.

Java supports following escape characters:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 12

Escape character Description Unicode Value

\b Backspace \u0008

\t Horizontal tab \u0009

\n New line \u000a

\f Form feed \u000c

\r Carriage return \u000d

\" Double quote \u0022

\' Single quote \u0027

\\ Backslash \u005c

Read More:- Escape Sequence In Java

3.7) Operators in Java


Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

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

Table for operator type, category, and precedence:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 13

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr ~ !

Arithmetic Multiplicative * / %

Additive + -

Shift Shift << >> >>>

Relational Comparison < > <= >= instanceof

Equality == !=

Bitwise Bitwise AND &

Bitwise exclusive OR ^

Bitwise inclusive OR |

Logical Logical AND &&

Logical OR ||

Ternary Ternary ? :

Assignment Assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

Associativity of Operators

Associativity tells the direction of execution of operators. It can either be left to right or right to
left.

Table for Operators and their associativity:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 14

Category Operators Associativity

Postfix ++ - - Left to right

Unary + - ! ~ ++ - - Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= | Right to left


=

Read more:- Arithmetic Operators in Java

Increment and Decrement Operators

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:-

++variable; // pre increment operator


variable++; // post increment operator

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 15

--variable; // pre decrement operator


variable--; // post decrement operator

Expression Initial value of a Final value of a Value of x

x = ++a 4 5 5

x = a++ 4 5 4

x = --a 4 3 3

4
x = a-- 4 3

Read more:- Increment and Decrement Operators in Java

Equal Operator (==)


In Java an equal operator is used to compare two primitives based on their value and two
objects based on their references. After comparison, it gives a boolean result either true/false. It
is widely used in conditional statements. Syntax:-

LHS value == RHS value

Read more:- Equal Operator (==) in Java

3.8) Comments in Java


In Java programming, a comment is a piece of code that is not compiled by the compiler.
Comments are the portion of the program intended for you and your fellow programmers to
understand the code. In simple words, a description of the basic programming element is called
comments. There are different types of comments in Java.

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.

Java supports two types of comments:-

1 Implementation Comments ( // and /* … */ )


2 Documentation Comments ( /** … */ )

Read more:- Comments in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 16

3.9) Java Basic Program Examples


1. Java Hello World program
2. Java Addition Program
3. Average of Two Numbers
4. Average of 3 Numbers
5. Calculate Total & Average of 3 Subjects
6. Calculate Simple Interest
7. Calculate Compound Interest
8. Display ASCII value in Java
9. Calculate Area of Circle in Java
10. Find Area of Rectangle in Java
11. Find the Area of Triangle in Java
12. Swapping two Numbers in Java
13. Distance Between 2 Points in Java
14. Simple Mortgage Calculator in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 17

4. Control Flow Statements in Java


4.1) Conditions in Java
Sometimes we want to watch comedy videos on youtube if the day is sunday. You might want to
buy an umbrella if its raining and you have the money.

All these are decisions which depend on a certain being met. In java, we can execute
instructions on the conditions being met.

Decision making instructions in Java:-

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 18

}
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
}
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 19

Switch statement
The switch statement allows us to execute a block of code among many alternatives.

Syntax of the switch statement:-

switch (expression) {

case value1:
// code
break;

case value2:
// code
break;

...
...

default:
// default statements
}

Relation Operators in Java


Relational operators are used to evalute conditions (true or false) inside the if statements.

Java supports the usual logical conditions from mathematics:-


 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to: a == b
 Not Equal to: a != b

Note:- “=” is used for assignment whereas “= =” is used for equality check.

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:-


1. Use if to specify a block of code to be executed, if a specified condition is true.
2. Use else to specify a block of code to be executed, if the same condition is false.
3. Use else if to specify a new condition to test, if the first condition is false.
4. Use switch to specify many alternative blocks of code to be executed.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 20

4.2) Loop Control Instruction in Java


Sometimes we want our programs to execute a few set of instructions over and over again. For
example:- print 1 to 100 number, print multiplication table, etc..

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.

Types of Loops in Java


Primarily, there are three types of loops in Java.
1 For Loop
2 While Loop
3 Do-While Loop

For Loop:- Java for loop is used to run a block of code for a certain number of times.

The syntax of for loop is:-

for (initialExpression; testExpression; updateExpression) {


// body of the loop
}

Example:-

// Java Program to demonstrate the example of for loop


// which prints table of 1
public class ForExample {
public static void main(String[] args) {
// Code of Java for loop
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

Output:-

1
2
3
4
5
6
7

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 21

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.

The syntax of while loop is:-

while (condition){
// code to be executed
// Increment or decrement statement
}

Example:-

public class WhileLoopExample {


public static void main(String args[]) {
int i = 10;
while (i > 0) {
System.out.println(i);
i--;
}
}
}

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.

The syntax of do-while loop is:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 22

do {
// code to be executed / loop body
// update statement
} while (condition);

Example:-

public class WhileLoopExample {


public static void main(String args[]) {
int i = 10;
do {
System.out.println(i);
i--;
} while (i > 0);
}
}

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.

Syntax of the break statement in Java:-

break;

Example:-

// Java Program to demonstrate the use of break statement


public class BreakExample {
public static void main(String[] args) {

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 23

// for loop
for (int i = 1; i <= 10; ++i) {

// if the value of i is 5 the loop terminates


if (i == 7) {
break;
}
System.out.println(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.

Syntax of the continue statement in Java:-

jump-statement;
continue;

Example:-

// Java Program to demonstrate the use of continue statement


// inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
// using continue statement
continue;// it will skip the rest statement
}
System.out.println(i);
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 24

}
}

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.

4.3) Java Control Flow Programs

1. Java code to Check Even Odd


2. Find the Greatest of 3 numbers
3. How to Find exponents in Java
4. Students Grades using Switch Case
5. Leap year program in Java
6. Print Multiplication table
7. Find Reverse of a number
8. Find Factors of a number
9. LCM of two numbers in Java
10. HCF of two numbers in Java
11. Roots of a quadratic equation
12. Square Root of a Number
13. Perfect Square Program
14. Print 1 to 100 Without Loop
15. Simple Calculator Program
16. BMI (Body Mass Index) Calculator
17. Electric Bill Java Program
18. Factorial of a Number in Java
19. Chinese Zodiac Sign Java Program

Java Programs to find Sum

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 25

1. Sum of digits of a number in Java


2. The sum of N Natural numbers
3. The sum of even digits in a number
4. Sum of odd digits in a number
5. Sum of first & last digit of a number
6. The Sum of Digits Until Single Digit

Series Program in Java


1. Fibonacci Series program in Java
2. Fibonacci Series using Recursion
3. Sum of Series Program in Java

Conversion based on Flow Control


1. Celsius to Fahrenheit Java program
2. Fahrenheit to Celsius Java program
3. Decimal to Octal program in Java
4. Octal to Decimal program in Java

Pattern Programs in Java


1. Diamond Pattern Program
2. Pascal Triangle Program
3. Pyramid Pattern Program

Java Number Programs


1. Even Number in Java
2. Odd Number in Java
3. Prime Number in Java
4. Twin prime Number
5. Magic Number in Java
6. Armstrong Number
7. Palindrome Number
8. Perfect Number Java
9. Spy Number in Java
10. Tech Number in Java
11. Sunny Number in Java
12. Automorphic Number
13. Krishnamurthy Number
14. Evil Number in Java
15. Strong Number in Java
16. Disarium Number Java
17. Neon Number in Java
18. Pronic Number in Java
19. Duck Number in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 26

20. Harshad Number Java


21. Kaprekar Number Java
22. Buzz Number in Java
23. Nelson Number in Java
24. Special Number in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 27

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.

5.1) Single & Multidimensional Array

Array object creation


We have three ways to create an array object.
1 Array creation with explicit values.
2 Array object creation without explicit values or array object creation with default values.
3 Anonymous array

Use Case: Storing marks of 10 students


int[ ] marks = new int[10]

Array indices start from 0 and go till n-1. Where, n is the size of the array.

Different types of array referenced variables in Java


Like primitive and other referenced variables, we can store array referenced variables as static,
non-static, and local.

Read more:- Array in Java

Declaration of Multidimensional Array

Syntax for two dimensional array:-


<Accessibility modifier><Execution-level Modifiers> <datatype>[][] <array
variable name>;

Example of multidimensional array declaration:-


// 2d array
public static int[][] n1;
// 3d array
public static float[][][] n2;

The dimension or level is represented by [ ]. Single dimensional array contains [ ], two


dimensional array contains [ ][ ], and three dimensional array contains [ ][ ][ ], and so on.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 28

Multidimensional Array creation:-


1 Multidimensional array creation with values.
2 Array object creation without explicit values or with default values.

Syntax for two dimensional array:-


int[][] ia = new int[3][2];

Syntax for three dimensional array:-


int[][][] arr = new int[2][3][2];

Read more:- Multidimensional Array in Java

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.

Syntax to create anonymous array in Java:-


new <data type>[]{<list of values with comma separator>};

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

Read more:- Anonymous Array in Java

Array of Objects
In Java, like primitive values we can also create an array of objects.

There are three ways to create an array of objects in Java,


1 The Array of objects created with values.
2 The Array of objects creation without explicit values or with default values.
3 Anonymous array

Read more:- Array of Objects in Java

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 29

array creation we must not specify child array size instead we must assign child array objects
with different sizes.

Jagged Array Creation:-


 Jagged array creation in Java with explicit values.
 Jagged array object creation in Java without explicit values or with default values.

Read more:- Jagged Array in Java

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

Java program to display size or length of an array in Java,

public class ArrayLength {


public static void main(String[] args) {
// declare and initialize an array
int arr[] = { 10, 20, 30, 40, 50 };

// display array length


System.out.print("The length of the given array = ");
System.out.println(arr.length);
}
}

Output:-
The length of the given array = 5

5.2) Arrays Class


Arrays class was introduced in JDK 1.2 version. This class contains various methods for
manipulating arrays such as sorting, searching, copying, converting an array to string and e.t.c.
Java Arrays class also contains a static factory that allows arrays to be viewed as lists. It
belongs to the java.util package.

Arrays Class Declaration:-


public class Arrays
extends Object

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 30

Arrays Class Constructors


It doesn’t contain any public constructors therefore we can’t create objects of the java.util.Arrays
class through constructors. It contains:-
private Arrays() {}

Methods of Java Arrays Class:-


Method Description
Arrays.toString() To convert single dimensional array to string.
Arrays.deepToString() To convert multi-dimensional array to string.
Arrays.sort() To sort array in ascending order.
Arrays.parallelSort() Similar to Arrays.sort() (mainly for multiple thread).
Arrays.copyOf() To copy the complete array to another array.
Arrays.copyOfRange() Similar to Arrays.copyOf() but copy only within the given range.
Arrays.equals() For equality testing of two arrays.
Arrays.deepEquals() For equality testing given two arrays deeply.
Arrays.hashCode() To give hash code based on the contents of the specified array.
Arrays.deepHashCode() To give hash code based on the “deep contents” of given array.
Arrays.compare() Compares two specified arrays lexicographically.
Arrays.compareUnsigned() Compares two arrays lexicographically, numerically treating
elements as unsigned.
Arrays.setAll() It set all elements of the specified array.
Arrays.parallelSetAll() Set all elements of the specified array, in parallel.
Arrays.fill() To fill array elements with given value.
Arrays.stream() To return stream for the specified array.
Arrays.asList() To return array as List.
Arrays.binarySearch() Find index of array element.
Arrays.mismatch() To return the index of the first mismatch between the two arrays.
Arrays.spliterator() It returns a Spliterator covering all of the specified array.
Arrays.parallelPrefix() It performs a given mathematical function on the elements of the
array cumulatively, and them modifies the array concurrently.

Read more:- Java Arrays Class & Methods

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 31

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.

Syntax of the arraycopy() method in java.lang.System class,


public static native void arraycopy(Object src, int srcPos, Object dest, int
destPos, int length);

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.

To copy the complete array using System.arraycopy() method,


1) Take an array (source array)
2) Declare a new array with the same length.
3) Call System.arraycopy(src, 0, dest, 0, src.length);

Read more:- System.arraycopy() in Java

5.3) Array Program Examples


Complete list of array programs are listed here:- Java Array Programs

Single-dimensional (1D) Array Programs in Java

1. Find Length of Array in Java


2. Get Array Input in Java
3. Return Array from a method
4. Different ways to Print Array
5. Find the Sum of Array in Java
6. Find the average of an Array
7. Sum of Two Arrays Elements
8. Compare Two Arrays in Java
9. Copy Array in Java
10. Merge 2 Arrays in Java
11. Merge two sorted Arrays

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 32

12. Largest Number in Array


13. Smallest Number in Array
14. 2nd Largest Number in Array
15. How to Sort an Array in Java
16. Reverse an Array in Java
17. GCD of N Numbers in Java
18. Linear Search in Java
19. Binary Search Program in Java
20. Remove Duplicates From Array
21. Insert Element at Specific Position
22. Add Element to Array in Java
23. Remove Element From Array in Java
24. Count Repeated Elements in Array

Java Array Programs on Multidimensional Array

1. Print 2D array in Java


2. Program to Print 3×3 Matrix 
3. Sum of matrix elements in Java
4. Sum of Diagonal Elements of Matrix
5. Row sum and Column sum of Matrix
6. Matrix Addition in Java
7. Subtraction of two matrices in Java 
8. Transpose of a Matrix in Java 
9. Matrix Multiplication in Java
10. Menu-driven program for Matrix operations

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 33

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";

How to create a string object?


The java.lang.String class is used to create a string object.

There are two ways to create String object:-


 By string literal
 By new keyword (constructor)

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)

Other constructors of String class are:-


1. public String(int[] codePoints, int offset, int count)
2. public String(byte bytes[], Charset charset)
3. public String(byte bytes[], String charsetName) throws
UnsupportedEncodingException
4. public String(byte bytes[], int offset, int length, Charset charset)
5. public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 34

Read more:- Constructors of String class in Java

Methods of Java String


Java String class provides a lot of methods to perform operations on strings. Here are some of
those important methods:-
1. contains() - Checks whether the string contains a substring
2. substring() - Returns the substring of the string
3. join() - Join the given strings using the delimiter
4. replace() - Replaces the specified old character with the specified new character
5. replaceAll() - Replaces all substrings matching the regex pattern
6. replaceFirst() - Replace the first matching substring
7. charAt() - Returns the character present in the specified location
8. getBytes() - Converts the string to an array of bytes
9. indexOf() - Returns the position of the specified character in the string
10. compareTo() - Compares two strings in the dictionary order
11. compareToIgnoreCase() - Compares two strings ignoring case differences
12. trim() - Removes any leading and trailing whitespaces
13. format() - Returns a formatted string
14. split() - Breaks the string into an array of strings
15. toLowerCase() - Converts the string to lowercase
16. toUpperCase() - Converts the string to uppercase
17. valueOf() - Returns the string representation of the specified argument
18. toCharArray() - Converts the string to a char array
19. matches() - Checks whether the string matches the given regex
20. startsWith() - Checks if the string begins with the given string
21. endsWith() - Checks if the string ends with the given string
22. isEmpty() - Checks whether a string is empty of not
23. intern() - Returns the canonical representation of the string
24. contentEquals() - Checks whether the string is equal to charSequence
25. hashCode() - Returns a hash code for the string
26. subSequence() - Returns a subsequence from the string

How to Take & Return a String?


In the Java programming language Char[ ], String, StringBuffer, and StringBuilder are used to
store, take and return string data. One question can come into your mind: what is the best way
for defining a method to take string data and return string data in Java?

We have four ways to take and return string data as:-


1) char[ ] / byte[ ]
2) String
3) StringBuilder

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 35

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.

public class Test {


public static void main(String[] args) {
String s1 = "Know Program";
System.out.println(System.identityHashCode(s1));
System.out.println(s1);

s1 = s1.concat(" - Java Tutorial");


System.out.println(System.identityHashCode(s1));
System.out.println(s1);
}
}

Output:-
517938326
Know Program
1100439041
Know Program – Java Tutorial

Types of immutable class in Java


1) Immutable classes which allow modification.
2) Immutable classes which don’t allow modification.

Read More:- Immutable Class in Java

String Programs in Java


1. Take String Input In Java using Scanner Class
2. How to Find Length of String in Java
3. How to Iterate through String Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 36

4. Sum of digits in a String


5. Count No of Vowels String
6. String Pattern Programs in Java
7. How To Reverse a String In Java
8. String Palindrome In Java
9. Sort String In Java
10. How to Compare Strings In Java
11. Java Check If String Contains Uppercase And Lowercase
12. Java Check If Char is Uppercase
13. Check If String is Uppercase Java
14. Swap Characters in String Java
15. Generate Random Strings
16. Java Program to Find Weight of String
17. Find Second Occurrence of Character in String Java
18. Find Last Occurrence of Character in String Java
19. Java Replace nth Occurrence String
20. Replace Last Occurrence of Character in String Java
21. How to Replace Dot in Java
22. How To Remove Substring From String Java
23. Replace Special Characters In Java
24. Java Replace String With Escape Character
25. Java Remove Special Characters From String
26. How To Remove Character From a String Java
27. Remove Commas From String Java
28. Replace Comma in String Java
29. Golden Ratio Java Program

Number programs using String


1. Unique Number
2. Fascinating Number
3. ISBN Number

String Array Programs


1. Java Convert Number String to Array
2. How to Iterate Through a String Array In Java
3. Convert String Array to Lowercase Java
4. String Array to UpperCase Java

Game Programs using Java String


1. Hidden Word Java Program
2. Java Secret Message Program

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 37

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:

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

Output:-
I just got executed!

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 38

Types of Method in Java


There are two types of methods in Java:-
1 Predefined Method
2 User-defined Method

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:

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

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.

How to perform method overloading in Java?


1. Overloading by changing the number of parameters
2. Method Overloading by changing the data type of parameters

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 39

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
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 40

8. Introduction to OOPs
Object Oriented Programming tries to map code instructions with real world making the code
shot and easier to understand.

What is Object Oriented Programming?


Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some concepts:
1. Object
2. Class
3. Abstraction
4. Inheritance
5. Polymorphism
6. Encapsulation

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.

A class declaration consists of:-


 Modifiers: Can be public or default access.
 Class name: Initial letter.
 Superclass: A class can only extend (subclass) one parent.
 Interfaces: A class can implement more than one interface.
 Body: Body surrounded by braces, { }.

Abstraction

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 41

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 42

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.

Advantages of OOPs Concept


1. Re-usability
2. Data redundancy
3. Code maintenance
4. Security
5. Design benefits
6. Easy troubleshooting
7. Flexibility
8. Problem solving

Disadvantages of OOPs Concept


 Effort
 Speed
 Size

Q) Difference between an object-oriented programming language and object-based


programming language?
Object-based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-based programming languages.

8.1) Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

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() {...}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 43

In the above example, we have declared 2 methods: method1() and method2(). Here,

method1 is public - This means it can be accessed by other classes.


method2 is private - This means it can not be accessed by other classes.

Note the keyword public and private. These are access modifiers in Java. They are also known
as visibility modifiers.

Note:- You cannot set the access modifier of getters methods.

Types of Access Modifier


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.
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.

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

8.2) Getters and Setters


Getter and Setter are methods used to protect your data and make your code more secure.

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.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 44

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.

Naming convension for,


 Getter method:- getXXX()
 Setter method:- setXXX()
Here, XXX represents the variable name.

Why to use getters and setters?


Getters and setters allow you to control how important variables are accessed and updated in
your code. For example, consider this setter method:

public class Employee {


private String name;
private String designation;
private double salary;
private String city;

// constructor
Employee(String name, String designation, double salary, String city) {
this.name = name;
this.designation = designation;
this.salary = salary;
this.city = city;
}

// getter and setter methods


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 45

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}
}

8.3) Constructors in Java


Java constructors or constructors in Java is a terminology used to construct something in our
programs. A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.

Create a constructor:-

// Create a Main class


public class Main {
// Create a class attribute
int x;

// Create a class constructor for the Main class


public Main() {
// Set the initial value for the class attribute x
x = 5;
}

public static void main(String[] args) {


// Create an object of class Main (This will call the constructor)
Main myObj = new Main();
// Print the value of x
System.out.println(myObj.x);
}
}

Outputs:-
5

The rules for writing constructors are as follows:-


1. Constructor(s) of a class must have the same name as the class name in which it
resides.
2. A constructor in Java can not be abstract, final, static, or Synchronized.
3. Access modifiers can be used in constructor declaration to control its access i.e which

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 46

other class can call the constructor.

Types of Constructors in Java


1 Default Constructur (No-argument constructor)
2 Parameterized Constructor

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.

Example of Constructor Overloading:-

// Java program to overload constructors


public class Student {
int id;
String name;
int age;

// creating two arg constructor


Student(int i, String n) {
id = i;
name = n;
}

// creating three arg constructor


Student(int i, String n, int a) {
id = i;
name = n;
age = a;
}

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();
}
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 47

Output:-
111 Karan 0
222 Aryan 25

Difference between Constructor and Method in Java


There are many differences between constructors and methods. They are given below.

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 constructor is invoked implicitly. The method is invoked explicitly.

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.

8.5) Inheritance in Java


Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.

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:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 48

class Animal {
// field and method of the parent class
String name;

public void displayName() {


System.out.println("My name is: " + name);
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass


public void speak() {
System.out.println("I can bark");
}

public void eat() {


System.out.println("I eat bones");
}
}

class Cow extends Animal {


public void speak() {
System.out.println("I can moo");
}

public void eat() {


System.out.println("I eat grass");
}

public class Main {


public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();
// access field of superclass
labrador.name = "Rohu";
// call method of superclass
// using object of subclass
labrador.displayName();
labrador.eat();
labrador.speak();

Cow holstein = new Cow();


holstein.name = "Emma";
holstein.displayName();
holstein.eat();
holstein.speak();
}
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 49

Output:-

My name is: Rohu


I eat bones
I can bark
My name is: Emma
I eat grass
I can moo

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.

Why use inheritance in java


 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

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.

The syntax of Java Inheritance:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 50

class Subclass-name extends Superclass-name {


// methods and fields
}

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.

Is Constructor Inherited in Java?


Constructor is a block of statements that permits you to create an object of specified class and
has a similar name as class with no explicit or specific return type.

No, constructor cannot be inherited in Java.

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.

8.6) Abstract classes and Methods


Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 51

Ways to achieve Abstraction


There are two ways to achieve abstraction in java.

1 Abstract class (0 to 100%)


2 Interface (100%)

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,

abstract class Language {


// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {


public static void main(String[] args) {
// create an object of Main
Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}

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();

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 52

Here, obj is the object of the child class Main. We are calling the method of the abstract class
using the object obj.

8.7) Interfaces in Java


An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a class. An interface is a fully abstract
class. It includes a group of abstract methods (methods without a body).

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.

We use the interface keyword to create an interface in Java. For example,

interface Language {
public void getType();
public void getVersion();
}

Here,
 Language is an interface.
 It includes abstract methods: getType() and getVersion().

Advantages of Interface in Java


1. Similar to abstract classes, interfaces help us to achieve abstraction in Java.
2. Interfaces provide specifications that a class (which implements it) must follow.
3. Interfaces are also used to achieve multiple inheritance in Java.

Note:- All the methods inside an interface are implicitly public and all fields are implicitly public
static final.

default methods in Java Interfaces


With the release of Java 8, we can now add methods with implementation inside an interface.
These methods are called default methods.

To declare default methods inside interfaces, we use the default keyword. For example,

public default void getSides() {


// body of getSides()
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 53

Why default methods?


Suppose, we need to add a new method in an interface. We can add the method in our interface
easily without implementation. However, that's not the end of the story. All our classes that
implement that interface must provide an implementation for the method.

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.

private and static Methods in Interface


The Java 8 also added another feature to include static methods inside an interface.

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.

Difference between abstract class and interface

Abstract class Interface

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.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 54

implementation of interface. abstract classes.

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%).

8.8) Polymorphism in Java


Polymorphism is that it has many forms that mean one specific defined form is used in many
different ways. The simplest real-life example is let’s suppose we have to store the name of the
person and the phone number of the person, but there are many situations when a person has
two different phone numbers. We have to save the same phone number under the same name.

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.

Types of polymorphism in Java


1 Run time polymorphism (Method overriding)
2 Compile-time polymorphism (Method overloading)

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 55

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.

Some of the existing packages in Java are:-


 java.lang − bundles the fundamental classes
 java.io − classes for input , output functions are bundled in this package

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.

javac -d Destination_folder file_name.java

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.

Advantage of Java Package


 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.
 Java package removes naming collision.

Simple example of java package:-


The package keyword is used to create a package in java.

// save as Simple.java
package mypack;
public class Simple{

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 56

public static void main(String args[]){


System.out.println("Welcome to package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

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:

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 57

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: ");

String userName = scan.nextLine();


System.out.println("Username is: " + userName);
scan.close();
}
}

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 58

└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:-

// MyPackageClass.java
package mypack;
public class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my 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.

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");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple

Output: Hello subpackage

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name the same. For example:

// save as A.java
package kp;
public class A{}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 59

// save as B.java
package kp;
public class B{}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 60

10. Multithreading in Java


In Java, Multithreading refers to a process of executing two or more threads simultaneously for
maximum utilization of the CPU. A thread in Java is a lightweight process requiring fewer
resources to create and share the process resources.

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.

Few more advantages of Multithreading are:-


 Multithreading saves time as you can perform multiple operations together.
 The threads are independent, so it does not block the user to perform multiple
operations at the same time and also, if an exception occurs in a single thread, it does
not affect other threads.

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)

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If an exception occurs in one thread, it doesn't affect other threads. It
uses a shared memory area.

Life Cycle of a Thread


There are five states a thread has to go through in its life cycle. This life cycle is controlled by
JVM (Java Virtual Machine). These states are:
1 New: In this state, a new thread begins its life cycle. This is also called a born thread.
The thread is in the new state if you create an instance of Thread class but before the
invocation of the start() method.
2 Runnable: A thread becomes runnable after a newly born thread is started. In this state,
a thread would be executing its task.
3 Running: When the thread scheduler selects the thread then, that thread would be in a
running state.
4 Non-Runnable (Blocked): The thread is still alive in this state, but currently, it is not
eligible to run.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 61

5 Terminated (Dead): A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Threads can be created by using two mechanisms:-


1 Extending the Thread class
2 Implementing the Runnable Interface

Java Thread class


Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.

Modifier Method Description


&
Type

void start() It is used to start the execution of the thread.

void run() It is used to do an action for a thread.

static void sleep() It sleeps a thread for the specified amount of time.

static Thread currentThread() It returns a reference to the currently executing thread


object.

void join() It waits for a thread to die.

int getPriority() It returns the priority of the thread.

void setPriority() It changes the priority of the thread.

String getName() It returns the name of the thread.

void setName() It changes the name of the thread.

long getId() It returns the id of the thread.

boolean isAlive() It tests if the thread is alive.

static void yield() It causes the currently executing thread object to pause
and allow other threads to execute temporarily.

void suspend() It is used to suspend the thread.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 62

void resume() It is used to resume the suspended thread.

void stop() It is used to stop the thread.

void destroy() It is used to destroy the thread group and all of its
subgroups.

boolean isDaemon() It tests if the thread is a daemon thread.

void setDaemon() It marks the thread as a daemon or user thread.

void interrupt() It interrupts the thread.

boolean isinterrupted() It tests whether the thread has been interrupted.

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.

void checkAccess() It determines if the currently running thread has permission


to modify the thread.

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.

StackTraceElem getStackTrace() It returns an array of stack trace elements representing the


ent[] stack dump of the thread.

static int enumerate() It is used to copy every active thread's thread group and its
subgroup into the specified array.

Thread.State getState() It is used to return the state of the thread.

ThreadGroup getThreadGroup() It is used to return the thread group to which this thread
belongs

String toString() It is used to return a string representation of this thread,


including the thread's name, priority, and thread group.

void notify() It is used to give the notification for only one thread which
is waiting for a particular object.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 63

void notifyAll() It is used to give the notification to all waiting threads of a


particular object.

void setContextClassLoade It sets the context ClassLoader for the Thread.


r()

ClassLoader getContextClassLoade It returns the context ClassLoader for the thread.


r()

static getDefaultUncaughtEx It returns the default handler invoked when a thread


Thread.Uncaug ceptionHandler() abruptly terminates due to an uncaught exception.
htExceptionHan
dler

static void setDefaultUncaughtEx It sets the default handler invoked when a thread abruptly
ceptionHandler() terminates due to an uncaught exception.

Java Thread Example by extending Thread Class:-

public class MyThread extends Thread {


public void run() {
System.out.println("Thread is running...");
}

public static void main(String args[]) {


MyThread thread1 = new MyThread();
thread1.start();
}
}

Output:
Thread is running…

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 64

11. Error & Exception in Java


11.1) Errors in Java
In Java, an error is a subclass of Throwable that tells that something serious problem is existing
and a reasonable Java application should not try to catch that error. Generally, it has been
noticed that most of the occurring errors are abnormal conditions and cannot be resolved by
normal conditions. As these errors are abnormal conditions and should not occur, thus, error
and its subclass are referred to as Unchecked Exceptions.

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.

Types of Errors in Java


There are three types of errors in java.
1 Runtime Errors
2 Compile-time Errors
3 Logical Errors

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.

Certain Errors in Java


The Java.lang.Errors provide varieties of errors that are thrown under the lang package of Java.

Some of the errors are:-

Error Name Description

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 65

AbstractMethodError When a Java application tries to invoke an abstract method.

Error Indicating a serious but uncatchable error is thrown. This type of


error is a subclass of Throwable.

AssertionError To indicate that an assertion has failed.

ClassCircularityError While initializing a class, a circularity is detected.

IllegalAccessError A Java application attempts either to access or modify a field or


maybe invoking a method to which it does not have access.

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.

ExceptionInInitializerError Signals that tell an unexpected exception have occurred in a


static initializer.

InternalError Indicating the occurrence of an unexpected internal error in the


JVM.

IncompatibleClassChangeError When an incompatible class change has occurred to some class


of definition.

LinkageError Its subclass indicates that a class has some dependency on


another data.

NoSuchFieldError In case an application tries to access or modify a specified field


of an object, and after it, that object no longer has this field.

OutOfMemoryError In case JVM cannot allocate an object as it is out of memory,


such error is thrown that says no more memory could be made
available by the GC.

NoClassDefFoundError If a class loader instance or JVM, try to load in the class


definition and not found any class definition of the class.

ThreadDeath Its instance is thrown in the victim thread when in thread class,
the stop method with zero arguments is invoked.

NoSuchMethodError In case an application tries to call a specified method of a class


that can be either static or instance, and that class no longer
holds that method definition.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 66

StackOverflowError When a stack overflow occurs in an application because it has


recursed too deeply.

UnsatisfiedLinkError In case JVM is unable to find an appropriate native language for


a native method definition.

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.

UnknownError In case a serious exception that is unknown has occurred in the


JVM.

VerifyError When it is found that a class file that is well-formed although


contains some sort of internal inconsistency or security problem
by the verifier.

11.2) Exceptions in Java


An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time, that disrupts the normal flow of the program’s instructions. Exceptions
can be caught and handled by the program.

An exception can occur for many reasons. Some of them are:-


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

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.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 67

Exceptions can be Categorized into 2 Ways:-


1) Built-in Exceptions
 Checked Exception
 Unchecked Exception
2) User-Defined Exceptions

11.3) Exception Handling


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

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.

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:
 Checked Exception
 Unchecked Exception
 Error

Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 68

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.

throw The "throw" keyword is used to throw an exception.

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.

Example of Exception Handling


Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

// 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...

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 69

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

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.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch:-

try{
// code that may throw an exception
} catch(Exception_class_Name ref) {
// exception handling code
}

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 70

Syntax of try-finally block:-

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.

Example multi-catch block:-

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try {
int a[] = new int[5];
a[5] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:-
Arithmetic Exception occurs
rest of the code

Java throw and throws keyword


The Java throw keyword is used to explicitly throw a single exception. When we throw an
exception, the flow of the program moves from the try block to the catch block.

Example of Exception handling using Java throw:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 71

public class Main {


public static void divideByZero() {
// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}

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.

Example of Java throws keyword:-

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();
}

public static void main(String[] args) {


try {
findFile();
} catch (IOException e) {
System.out.println(e);
}
}
}

Output:-
java.io.FileNotFoundException: test.txt (No such file or directory)

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 72

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.

Exception Handling Programs


1. Develop User-defined Custom exception
2. Java Custom Exception Example
3. Different ways to get the exception message
4. Exception Propagation in Java
5. Nested try-catch in Java
6. Catch All Exceptions in Java

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 73

12. File Class in Java


The File class in Java is used to represent the files and directories paths but not the data of the
file. Basically, this class is used to create, delete, and rename the files and directories.

File Class constructor


The file class has below constructors to create its object.
 public File(String pathname)
 public File(String parent, String child)
 public File(File parent, String child)
 public File(URI uri)

Note:- File class object creation doesn’t not create any physical files, it only creates instance of
the File class.

Read more:- Java File Class & its Methods

Methods to Create File & Directories


In Java, we can create a file either in the current working directory or in some other location.
Similar to the file we are also able to create a directory in the current working directory or in
some other given location. Different methods to create file or directory are,

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.

It creates both parent and child directories with given names in


boolean mkdirs()
the given path.

Read more:- Create File & Directories in Java

Methods to List Files and Directories


In the java.io.File class, methods list() and listFiles() are given with their overloaded forms to list
the files and directory. We can use them in our program to get all files and directories in a
particular directory or to get all files in directory and subdirectories. We can also get them
through file extension. First, let us use those methods.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 74

Return
Method Description
Type

It returns all file and subdirectory names as String objects


String[ ] list()
using String array.

It returns all file and subdirectory names whose names are


String[ ] list(FilenameFilter filter) matched with a given filter as String objects using String
array.

It returns all file and subdirectory names as File objects


File[ ] listFiles()
using File array.

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.

It returns all file and subdirectory names whose names are


File[ ] listFiles(FileFilter filter) matched with given FileFilter 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.

It returns An array of File objects denoting the available file system


File[ ] listRoots() roots, or null if the set of roots could not be determined.
The array will be empty if there are no file system roots.

Read more:- List Files & Directories in Java

Delete Files and Directories


To delete files or directory using Java, delete() and deleteOnExit() methods are given in the
java.io.File class. Using these methods we can also delete the directory with all files. First, let us
demonstrate the method and then develop the program to delete all files in a directory.

Method to delete file or directory represented by the file object,

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 75

public boolean delete() It deletes files immediately.

public void deleteOnExit() It deletes files after JVM terminates.

Read more:- Java Delete Files & Directories

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 76

13. Collection Framework in Java


The Java collections framework provides a set of interfaces and classes to implement various
data structures and algorithms.

For example, the LinkedList class of the collections framework provides the implementation of
the doubly-linked list data structure.

Why use Java collections?


There are several benefits of using Java collections such as:-
 Reducing the effort required to write the code by providing useful data structures and
algorithms
 Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality
 Unrelated APIs can pass collection interfaces back and forth
 Decreases extra effort required to learn, use, and design new API’s
 Supports reusability of standard data structures and algorithms

A Java collection framework includes the following:-


 Classes: A class is a user-defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of one type.
 Interfaces: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
 Algorithm: Algorithm refers to the methods which are used to perform operations such
as searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can
say perform different implementations of the Java collection interface.

How are collections available?


Collections in java are avaiable as classes and interfaces. Following are few commonly used
collections in Java.
1. ArrayList: For variables size collection
2. Set: For distinct collection
3. Stack: A LIFO data structure
4. Hash Map: For Storing key-value pairs

Collection class is available in java.util package. Collection class also provides static methods
for sorting, searching, etc.

Must Learn (Very important):- Java Collection Framework Overview

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 77

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:-

Method Description

public boolean add(E e) It is used to insert an element in this


collection.

public boolean addAll(Collection<? extends E> It is used to insert the specified collection
c) elements in the invoking collection.

public boolean remove(Object element) It is used to delete an element from the


collection.

public boolean removeAll(Collection<?> c) It is used to delete all the elements of the


specified collection from 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.

public boolean retainAll(Collection<?> c) It is used to delete all the elements of


invoking collection except the specified
collection.

public int size() It returns the total number of elements in the


collection.

public void clear() It removes the total number of elements from


the collection.

public boolean contains(Object element) It is used to search an element.

public boolean containsAll(Collection<?> c) It is used to search the specified collection in


the collection.

public Iterator iterator() It returns an iterator.

public Object[ ] toArray() It converts the collection into an array.

public <T> T[ ] toArray(T[ ] a) It converts the collection into an array. Here,


the runtime type of the returned array is that
of the specified array.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 78

public boolean isEmpty() It checks if the collection is empty.

default Stream<E> parallelStream() It returns a possibly parallel Stream with the


collection as its source.

default Stream<E> stream() It returns a sequential Stream with the


collection as its source.

default Spliterator<E> spliterator() It generates a Spliterator over the specified


elements in the collection.

public boolean equals(Object element) It matches two collections.

public int hashCode() It returns the hash code number of the


collection.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 79

Java Collection Programs


1. How to Print Arraylist Without Brackets Java
2. Unique Digits Count in Java
3. Java Program for Shopping Bill
4. Remove Duplicates From ArrayList Java
5. Sort ArrayList in Java
6. Convert ArrayList to Byte Array Java
7. Anagram Program In Java Using List

String Programs with the help of Collection


1. Print Vowels & Consonants in String
2. Convert Comma Separated String to List Java
3. Convert Pipe Delimited String to List Java

Collection & Array Programs


1. Convert List Of List To 2d Array Java

Other Problems
1. City Library Fine Report in Java
2. Drivers License Exam Java Program

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 80

14. Others

14.1) Creating our own Java Documentation


Java documentation is great. It helps us get info about which method/class/entity to use when.

We can create our own package’s Documentation in Java.

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.

Tag for class or a package:-


1 @author: Adds the author name
2 @version: Adds the version
3 @since: To add when was this version written
4 @see: Adds a see also heading with a link

Tag for methods:-


1 @param: for describing parameters of a methods
2 @return: for describing about the return value
3 @throws: for describing exceptions thrown
4 @deprecated: for describing deprecation status

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
*/

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 81

14.2) Annotations in Java


Java annotations are metadata (data about data) for our program source code.

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.

Annotations start with @. Its syntax is:- @AnnotationName

Built-In Java Annotations


There are several built-in annotations in Java. Some annotations are applied to Java code and
some to other annotations.

Built-In Java Annotations used in Java code


1. @Override: Used to mark overridder elements in the child class
2. @SuppressWarnings: Used to suppress the generated ubrnings by the compiler
3. @Deprecated: Used to mark deprecated methods

Built-In Java Annotations used in other annotations


1. @Target
2. @Retention
3. @Inherited
4. @Documented

Java Custom Annotations


Java Custom annotations or Java User-defined annotations are easy to create and use. The
@interface element is used to declare an annotation. For example:-

@interface MyAnnotation{ }

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature


There are few points that should be remembered by the programmer.
1 Method should not have any throws clauses
2 Method should return one of the following: primitive data types, String, Class, enum or
array of these data types.
3 Method should not have any parameters.
4 We should attach @ just before the interface keyword to define annotation.
5 It may assign a default value to the method.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 82

Types of Annotation
There are three types of annotations.
1 Marker Annotation
2 Single-Value Annotation
3 Multi-Value Annotation

Built-in Annotations used in custom annotations in java


1. @Target
2. @Retention
3. @Inherited
4. @Documented

14.3) Java Lambda Expressions


Lambda Expressions were added in Java 8. A lambda expression is a short block of code which
takes in parameters and returns a value. Lambda expressions are similar to methods, but they
do not need a name and they can be implemented right in the body of a method.

Syntax:-

The simplest lambda expression contains a single parameter and an expression:

parameter -> expression

To use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) -> expression

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.

(parameter1, parameter2) -> { code block }

14.4) Generics in Java


The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It
makes the code stable by detecting the bugs at compile time.

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,

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 83

or method that operates on a parameterized type is a generic entity.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:-
1 Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to
store other objects.
2 Type casting is not required: There is no need to typecast the object.
3 Compile-Time Checking: It is checked at compile time so problems will not occur at
runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.

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.

Creating a generic class:


class MyGen<T>{
T obj;
void add(T obj) { this.obj=obj; }
T get(){return obj;}
}

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

14.5) File handling in Java


It is defined as reading and writing data to a file. The particular file class from the package
called java.io allows us to handle and work with different formats of files.

Why is File Handling Required


1. File Handling is an integral part of any programming language as file handling enables

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 84

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.

There are two types of streams:-


1 Input Stream
2 Output Stream

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.

Java File Operation Methods


Operation Method Package
To create file createNewFile() java.io.File
To read file read() java.io.FileReader
To write file write() java.io.FileWriter
To delete file delete() java.io.File

Must read:- Java IOStream class & methods

14.6) Web Application


A web application is computer software that can be accessed using any web browser. Usually,
the frontend of a web application is created using the scripting languages such as HTML, CSS,
and JavaScript, supported by almost all web browsers. In contrast, the backend is created by
any of the programming languages such as Java, Python, Php, etc., and databases. Unlike the
mobile application, there is no specific tool for developing web applications; we can use any of
the supported IDE for developing the web application.

How does a web- application work?


In general, web-application does not require downloading them because, as we already
discussed, the web application is a computer program that usually resides on the remote server.
Any user can access it by using one of the standard web browsers such as Google Chrome,
Safari, Microsoft Edge, etc., and most of them are available free for everyone.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 85

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.

Web Server and Client


The web server is a process that handles the client's request and responds. It processes the
request made by the client by using the related protocols. The main function of the webserver is
to store the request and respond to them with web pages. It is a medium between client and
server. For example, Apache is a leading web server.

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.

HTML and HTTP


The HTML stands for HyperText Markup Language; it is a common language for Web Server
and Web Client communication. Since both the web server and web client are two different
software components of the web, we need a language that communicates between them.

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.

Some of the integral components of an HTTP Request are as following:-

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.

A URL looks like as follows:-


http://localhost:8080/SimpleWebApplication/

Where,
 http or https: It is the starting point of the URL that specifies the protocol to be used for

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 86

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.

Why are the Servlets Useful?


Web servers are capable enough to serve static HTML requests, but they don't know how to
deal with dynamic requests and databases. So, we need a language for dynamic content; these
languages are PHP, Python, Java, Ruby on Rails, etc. In Java, there are two technologies
Servlet and JSPs, that deals with dynamic content and database. Java also provides
frameworks such as Spring, Spring Boot, Hibernate, and Struts to use the servlet and JSP
easily.

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()

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 87

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.

Some of the important work done by web container are:-

Communication Support:- Container provides easy way of communication between web


server and the servlets and JSPs. Because of the container, we don’t need to build a server
socket to listen for any request from the web server, parse the request and generate a
response. All these important and complex tasks are done by container and all we need to focus
is on our business logic for our applications.

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.

Must read:- Web Application and Examples


Also see:- Static vs Dynamic Web Pages

14.7) Java Servlets


Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the web server, process the request,
produce the response, then send a response back to the web server.

Properties of Servlets are as follows:-


 Servlets work on the server-side.
 Servlets are capable of handling complex requests obtained from the web server.

Execution of Servlets basically involves six basic steps:-


1 The clients send the request to the web server.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 88

2 The web server receives the request.


3 The web server passes the request to the corresponding servlet.
4 The servlet processes the request and generates the response in the form of output.
5 The servlet sends the response back to the web server.
6 The web server sends the response back to the client and the client browser displays it
on the screen.

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:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 89

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.

14.8) Introduction to JSPs


Java Server Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent methods for building Web-based applications. JSP has access
to the entire family of Java APIs, including the JDBC API to access enterprise databases.

JSP syntax
Syntax available in JSP are following

1. Declaration Tag:- It is used to declare variables.

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 %>

3. JSP Expression:- It evaluates and converts the expression to a string.

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 --%>

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 90

Advantages of using JSP


 It does not require advanced knowledge of JAVA
 It is capable of handling exceptions
 Easy to use and learn
 It can tags which are easy to use and understand
 Implicit objects are there which reduces the length of code
 It is suitable for both JAVA and non JAVA programmer

Disadvantages of using JSP


 Difficult to debug for errors.
 First time access leads to wastage of time
 Its output is HTML which lacks features.

The Lifecycle of a JSP Page


The JSP pages follow these phases:-
 Translation of JSP Page
 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService() method).
 Destroy ( the container invokes jspDestroy() method).

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.

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>

It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:-

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 91

1. Start the server


2. Put the JSP file in a folder and deploy on the server
3. Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

Read More:-
1. JSP vs Servlet
2. JSP in Java
3. JSP vs HTML
4. Overview to Java Server Pages (JSP)

14.9) MVC in Java


The model designs based on the MVC architecture follow MVC design pattern. The application
logic is separated from the user interface while designing the software using model designs.

The MVC pattern architecture consists of three layers:-


 Model:- Model represents an object or JAVA POJO carrying data. It can also have logic
to update controllers if its data changes.
 View:- View represents the visualization of the data that model contains.
 Controller:- Controller acts on both model and view. It controls the data flow into the
model object and updates the view whenever data changes. It keeps view and model
separate.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:-
 MVC has the feature of scalability that in turn helps the growth of applications.
 The components are easy to maintain because there is less dependency.
 A model can be reused by multiple views that provides reusability of code.
 The developers can work with the three layers (Model, View, and Controller)
simultaneously.
 Using MVC, the application becomes more understandable.
 Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
 The extending and testing of applications is easier.

Implementation of MVC using Java


To implement MVC pattern in Java, we are required to create the following three classes.
 Employee Class, will act as model layer
 EmployeeView Class, will act as a view layer
 EmployeeContoller Class, will act a controller layer

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 92

14.10) Hibernate Framework


Hibernate is a framework in Java which comes with an abstraction layer and handles the
implementations internally. The implementations include tasks like writing a query for CRUD
operations or establishing a connection with the databases, etc.

A framework is basically a software that provides abstraction on multiple technologies like


JDBC, servlet, etc.

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.

Advantages of Hibernate Framework


Following are the advantages of hibernate framework:-
1. Open Source and Lightweight
2. Fast Performance
3. Database Independent Query
4. Automatic Table Creation
5. Simplifies Complex Join
6. Provides Query Statistics and Database Status

Need of Hibernate Framework


Hibernate is used to overcome the of limitations of JDBC like:-
 JDBC code is dependent upon the Database software being used i.e. our persistence
logic is dependent, because of using JDBC. Here we are inserting a record into
Employee table but our query is Database software-dependent i.e. Here we are using
MySQL. But if we change our Database then this query won’t work.
 If working with JDBC, changing of Database in the middle of the project is very costly.
 JDBC code is not portable code across the multiple database software.
 In JDBC, Exception handling is mandatory. Here We can see that we are handling lots of
Exceptions for connection.
 While working with JDBC, There is no support for Object-level relationships.
 In JDBC, there occurs a Boilerplate problem i.e. For each and every project we have to
write the below code. That increases the code length and reduces the readability.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 93

Functionalities Supported By Hibernate


 Hibernate uses Hibernate Query Language which makes it database independent.
 It supports auto DDL operations.
 Hibernate has Auto Primary Key Generation support.
 It supports Cache memory.
 Exception handling is not mandatory for hibernate.
 The most important is hibernate is an ORM tool.

Supported Databases In Hibernate


Following are the databases supported by hibernate in Java.
 HSQL Database Engine
 MYSQL
 ORACLE
 FrontBase
 PostgreSQL
 DB2/NT
 Sybase SQL Server
 Informix Dynamic Server
 Microsoft SQL Server Database

Hibernate almost supports all the major RDBMS which makes it efficient and easy to work with.

Technologies Supported By Hibernate


Hibernate supports a variety of technologies.
 XDoclet Spring
 Maven
 Eclipse Plug-ins
 J2EE

14.11) Spring Framework


The Spring Framework provides a comprehensive programming and configuration model for
modern Java-based enterprise applications - on any kind of deployment platform.

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

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 94

Dependency Injection first.

Inversion Of Control (IOC) and Dependency Injection


These are the design patterns that are used to remove dependency from the programming
code. They make the code easier to test and maintain. Let's understand this with the following
code:-

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.

Advantage of Dependency Injection


 makes the code loosely coupled so easy to maintain
 makes the code easy to test

Aspect Oriented Programming (AOP)


One of the key components of Spring is the Aspect Oriented Programming (AOP) framework.
The functions that span multiple points of an application are called cross-cutting concerns and
these cross-cutting concerns are conceptually separate from the application's business logic.
There are various common good examples of aspects including logging, declarative
transactions, security, caching, etc.

Features of Spring Framework


 Core technologies: dependency injection, events, resources, i18n, validation, data
binding, type conversion, SpEL, AOP.

Copyright © 2022 www.knowprogram.com


www.knowprogram.com 95

 Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.


 Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.
 Spring MVC and Spring WebFlux web frameworks.
 Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache.
 Languages: Kotlin, Groovy, dynamic languages.

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:-
 Predefined Templates
 Loose Coupling
 Easy to test
 Lightweight
 Fast Development
 Powerful abstraction
 Declarative support

How Spring works


A web application (layered architecture) commonly includes three layers:-
1 Presentation/view layer (UI): This is the outermost layer which handles the
presentation of content and interaction with the user.
2 Business logic layer: The central layer that deals with the logic of a program.
3 Data access layer: The deep layer that deals with data retrieval from sources.

Copyright © 2022 www.knowprogram.com

You might also like