0% found this document useful (0 votes)
101 views

Programming in Java All

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Programming in Java All

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 336

Programming in Java

CSE2006
Course Type LP
Credits 3
Text Book(s):
1. Herbert Schildt, “Java The complete reference”, 11th edition, Oracle press , 2018
Reference Book(s):
1. Oracle University Reference E-Kit
2. Deitel and Deitel, “Java How to Program (Early objects)”,10thedition,Pearson, 2015
3. Cay S.Horstmann and Gary Cornell, “Core Java Vol I–
Fundamentals”,8thedition,Pearson,2011
4. Steven Holzner et al., “Java 2 Black Book”, Dreamtech press, Reprint edition 2010
Unit I –
Unit Description
• Java Introduction
• Java Hello World, Java JVM, JRE, and JDK, Difference between C
& C++, Java Variables, Java Data Types, Java Operators, Java
Input and Output, Java Expressions & Blocks, Java Comment
• Java Flow Control
• Java if...else, Java switch Statement, Java for Loop, Java for-each
Loop, Java while Loop, Java break Statement, Java continue
Statement
What is Java?

• Developed by Sun Microsystems in 1995, Java is the highly popular,


object-oriented programming language.
• This platform-independent programming language is utilized for
Android development, web development, artificial intelligence, cloud
applications, and more.
Java Features

• Object Oriented: Java is a pure object-oriented language and everything in


Java is an object. Java supports OOPS principles
like Inheritance, Encapsulation, Polymorphism, Classes , and so on. Java
itself can be extended as well being based on an object model.
• Platform Independent: Java code is platform independent. A Java code is
not compiled into machine-specific code, it is compiled into a platform-
neutral byte code. This byte code is executed by JVM which runs the code
on the underlying platform. This capability makes Java a Write Once Run
Anywhere language.
• Easy To Learn: Java inherits features from C, and C++ and developers can
easily learn Java if they know any of the C or C++ language. Even for
someone new to computer languages, java is very easy to learn from
scratch.
Java Features

• Secure: Java is secure by architecture. A developer is not required to


directly interact with underlying memory or Operating System. Java
provides automatic garbage collection so developers are not required to
worry about memory leaks, management, etc.
• Architectural-Neutral: Java byte code can be executed on any kind of
processor. JRE automatically handles the code execution on different types
of processors.
• Portable - A Java code written on a windows machine can be executed
without any code change on MacOS and vice versa. There is no need to
make any operating system-specific code changes.
• Robust - Java is a very robust language with very strong compile-time error
checks, strict type checking, and runtime exception handling.
Java Features

• Multithreading - Java provides inbuilt support for


multiprocessing and multithreading. Java provides
thread handling, monitors, deadlock handling, racing
conditions, etc.
• High Performance - Java although being interpreted, still is
very performant. JIT (Just In Time) compiler helps in
improving performance.
• Distributed - Java is designed for distributed systems and
is the most popular language for developing internet-
based applications as the internet is a distributed
environment.
Java Applications

• Enterprise solutions
• Game development
• Secured web development
• Embedded systems
• Mobile application development
• Big Data Applications, and many more.
Why to Learn Java?

• Java is Open Source which means its available free of cost.


• Java is simple and so easy to learn
• Java is much in demand and ensures high salary
• Java has a large vibrant community
• Java has powerful development tools
• Java is platform independent
Java Variables

• String - stores text, such as "Hello". String values are surrounded by


double quotes
• int - stores integers (whole numbers), without decimals, such as 123 or
-123
• float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• boolean - stores values with two states: true or false
Java Variables

• int myNum = 5;
• float myFloatNum = 5.99f;
• char myLetter = 'D';
• boolean myBool = true;
• String myText = "Hello";
Anatomy of a class
Java Control Statements

1.Decision Making statements


1. if statements
2. switch statement
2.Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3.Jump statements
1. break statement
2. continue statement
Decision-Making statements:

• If Statement:
• In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of
the If statement gives a Boolean value, either true or false. In Java, there are
four types of if-statements given below.
1.Simple if statement
2.if-else statement
3.if-else-if ladder
4.Nested if-statement
Switch Statement:

• In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
• Points to be noted about the switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7
of Java
• Cases cannot be duplicated
• Default statement is executed when any of the case doesn't match the value of the expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, the next case is executed.
• While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
Loop Statements

• In programming, sometimes we need to execute the block of code


repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a
particular condition.
• In Java, we have three types of loops that execute similarly. However,
there are differences in their syntax and condition checking time.
1.for loop
2.while loop
3.do-while loop
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
• Value of b is : 30
• Value of b is : 20
public class Test {
public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
• This is else statement
public class Test {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
}
}
}
• Value of X is 30
public class Test {
public static void main(String args[]) {
double x = 30.0;
if( x == 10.0 ) {
System.out.print("Value of X is 10.0");
}else if( x == 20.0 ) {
System.out.print("Value of X is 20.0");
}else if( x == 30.0 ) {
System.out.print("Value of X is 30.0");
}else {
System.out.print("This is else statement");
}
}
}
• Value of X is 30.0
public class Test {
public static void main(String[] args) {
int x = 10, y = 20, z = 30;
if(x >= y) {
if(x >= z)
System.out.println(x + " is the largest.");
else
System.out.println(z + " is the largest.");
} else {
if(y >= z)
System.out.println(y + " is the largest.");
else
System.out.println(z + " is the largest.");
}
}
}
• 30 is the largest.
Java switch Statement
• The Java switch statement allows a variable to be tested for equality
against a list of values.
• Each value is called a case, and the variable being switched on is
checked for each case.
• The switch statement can be used when multiple if-else statements are
required.
• It can have multiple code blocks along with the case values and
executes one of many code blocks based on the matches case value.
Syntax
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements
}
Flow Diagram
Simple if statement:

• It is the most basic statement among all control flow statements in


Java. It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.
• if(condition) {
• statement 1; //executes when condition is true
•}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
x + y is greater than 20
if-else statement

• The if-else statement is an extension to the if-statement, which uses


another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.
• Syntax:
• if(condition) {
• statement 1; //executes when condition is true
•}
• else{
• statement 2; //executes when condition is false
•}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
x + y is greater than 20
if-else-if ladder:

• The if-else-if statement contains the if-statement followed by multiple


else-if statements.
• In other words, we can say that it is the chain of if-else statements
that create a decision tree where the program may enter in the block
of code where the condition is true.
• We can also define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Delhi
Nested if-statement
• In nested if-statements, the if statement can contain an if or if-
else statement inside another if or else-if statement.
• Syntax of Nested if-statement is given below.
• if(condition 1) {
• statement 1; //executes when condition 1 is true
• if(condition 2) {
• statement 2; //executes when condition 2 is true
• }
• else{
• statement 2; //executes when condition 2 is false
• }
• }
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
String address = "Meerut, India";
if(address.endsWith(“Bhopal")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Delhi
Switch Statement:

switch (expression){
case value1:
statement1;
break; .
. case valueN:
statementN;
break;
default:
default statement;
}
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
2
Java for loop

• for(initialization, condition, increment/decrement) {


• //block of statements
•}
public class Calculation {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
• The sum of the first 10 natural numbers is 55
Java while loop

• while(condition){
• //looping statements
•}
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• while(i<=10) {
• System.out.println(i);
• i = i + 2;
• }
• }
• }
Printing the list of first 10 even numbers

0
2
4
6
8
10
Java do-while loop

• do
•{
• //statements
• } while (condition);
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• do {
• System.out.println(i);
• i = i + 2;
• }while(i<=10);
• }
• }
• Printing the list of first 10 even numbers
•0
•2
•4
•6
•8
• 10
Java break statement
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) { 0 1 2 3 4 5 6
System.out.println(i); 0
if(i>6) {
break;
}
}
}
}
0
1
2
3
4
5
6
Java continue statement
• public class ContinueExample {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• for(int i = 0; i<= 3; i++) {
• for (int j = i; j<=5; j++) {
• if(j == 6) {
• continue; 0 1 2 3 4 5 1 2 3 4 5 2 3 4 5 3 4 5
• }
• System.out.println(j);
• }
• }
• }

• }
0
1
2
3
5
---------
1
2
3
5
---------
2
3
5
Java Object-Oriented Programming

• Java OOP (Basics)


• Java Class and Objects, Java Methods, Java Constructor, Java Strings, Java Access Modifiers,
Java this keyword, Java final keyword, Java Recursion, Java instance of Operator, Java Single
Class and Anonymous Class, Java enum Class
• Java OOP (Inheritance & Polymorphism)
• Java Inheritance, Java Method Overriding, Java super Keyword, Abstract Class & Method,
Java Interfaces, Java Polymorphism (overloading & overriding), Java Encapsulation
• Java OOP (Other types of classes)
• Nested & Inner Class, Java Static Class, Java Anonymous Class, Java Singleton, Java enum
Class, Java enum Constructor, Java enum String, Java Reflection
OOPs (Object-Oriented Programming System)

• Object means a real-world entity such as a mobile, book, table,


computer, watch, etc.
• 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.
Java OOPs (Object-Oriented Programming) Concepts

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Object

• In object-oriented programming, an object is an entity that has two


characteristics (states and behavior).
• Some of the real-world objects are book, mobile, table, computer, etc.
• An object is a variable of the type class, it is a basic component of an
object-oriented programming system.
• A class has the methods and data members (attributes), these methods
and data members are accessed through an object.
• Thus, an object is an instance of a class.
What is an Object in Java?

• An object is an entity in the real world that can be distinctly identified.


Objects have states and behaviors. In other words, they consist of
methods and properties to make a particular type of data useful.
• An object consists of:
• A unique identity: Each object has a unique identity, even if the state
is identical to that of another object.
• State/Properties/Attributes: State tells us how the object looks or
what properties it has.
• Behavior: Behavior tells us what the object does.
What is an Object in Java?

• Example 1:
• Object: car.
• State: color, brand, weight, model.
• Behavior: break, accelerate, turn, change gears.
• Example 2:
• Object: house.
• State: address, color, location.
• Behavior: open door, close door, open blinds.
Class

• In object-oriented programming, a class is a blueprint from which


individual objects are created (or, we can say a class is a data type of
an object type).
• In Java, everything is related to classes and objects. Each class has its
methods and attributes that can be accessed and manipulated through
the objects.
Inheritance

• In object-oriented programming, inheritance is a process by which we


can reuse the functionalities of existing classes to new classes.
• In the concept of inheritance, there are two terms base (parent) class
and derived (child) class.
• When a class is inherited from another class (base class), it (derived
class) obtains all the properties and behaviors of the base class.
Polymorphism

• The term "polymorphism" means "many forms".


• In object-oriented programming, polymorphism is useful when you want to create
multiple forms with the same name of a single entity.
• To implement polymorphism in Java, we use two concepts method
overloading and method overriding.
• The method overloading is performed in the same class where we have multiple
methods with the same name but different parameters, whereas, the method
overriding is performed by using the inheritance where we can have multiple
methods with the same name in parent and child classes.
Polymorphism

• If one task is performed in different ways, it is known as


polymorphism. For example: to convince the customer differently, to
draw something, for example, shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something; for example, a cat speaks
meow, dog barks woof, etc.
Abstraction

• In object-oriented programming, an abstraction is a technique of


hiding internal details and showing functionalities.
• The abstract classes and interfaces are used to achieve abstraction in
Java.
• The real-world example of an abstraction is a Car, the internal details
such as the engine, process of starting a car, process of shifting gears,
etc. are hidden from the user, and features such as the start button,
gears, display, break, etc are given to the user.
• When we perform any action on these features, the internal process
works.
Encapsulation

• In an object-oriented approach, encapsulation is a process of binding


the data members (attributes) and methods together.
• The encapsulation restricts direct access to important data.
• The best example of the encapsulation concept is making a class
where the data members are private and methods are public to access
through an object.
• In this case, only methods can access those private data.
• AD
Advantages of Java OOPs

• The implementations of OOPs concepts are easier.


• The execution of the OOPs is faster than procedural-oriented
programming.
• OOPs provide code reusability so that a programmer can reuse an
existing code.
• OOPs help us to keep the important data hidden.
1. Work as a relational operator.
// Return true if two conditions are true, return false if one of the conditions is false.
// "&" evaluates all conditions, even if the first condition is false.
e.g.
public class Main {
public static void main(String[] args){
int x = 100, y = 90, z = 60;
if ((x > y) & (x > z))
System.out.println("The value of x is " + x);
}}

// Output: The value of x is 100


2. Work as a bitwise AND
// Return 1 if two bits are 1, return 0 if one of the bits is 0.
e.g.
public class Main {
public static void main(String[] args){
int x= 4;
int y = 6;
int z = x & y;
System.out.println(x + " & " + y + " = " + z);
}
}
// Output: 4
"|" is used for bitwise Or.
// Return 1 if one of the bits is 1, return 0 if all bits are 0.
e.g.
public class Main {
public static void main(String[] args){
int x= 4;
int y = 6;
int z = x | y;
System.out.println(x + " | " + y + " = " + z);
}
}
// Output: 6
"^" is used for bitwise XOR
// if corresponding bits are different, it returns 1, else it returns 0.
e.g.
public class Main {
public static void main(String[] args){
int x= 4;
int y = 6;
int z = x ^ y;
System.out.println(x + " ^ " + y + " = " + z);
}
}
// Output: 4 ^ 6 = 2
operand << bits
// Left shift all bits according to a given number of bits .
e.g.
public class Main {
public static void main (String[] args) {
int operand = 2;
// left shift 2 bits
int n = operand << 2;
System.out.println(n);
}
}
// Output: 8
operand >> bits
// Right shift all bits according to a given number of bits.
e.g.
public class Main {
public static void main (String[] args) {
int operand = 8;
// right shift 2 bits
int n = operand >> 2;
System.out.println(n);
}
}
// Output: 2
(bool-expression) ? (if-true-do-this) : (if-false-do-this);
// Run one of the statement according to the result of the boolean expression
e.g.(1)
int a=100; int b=300;
String result1 = (a<b) ? "orange" : "pineapple";
System.out.print ( result1);
// Output: orange
e.g.(2)
int a=100; int b=300;
String result2 = (a>b) ? "orange" : "pineapple";
System.out.print ( result2 );
// Output: pineapple
str = str1 + str2;
str = str1.concat(str2);
// "+" can join two strings.
// concat() can connect two strings.
e.g.
String s1 = "Hello"; String s2 = "Friends";
System.out.print( s1 + s2); // connect two strings
System.out.print( s1.concat (s2)); // connect two strings
// Output: Hello Friends
// Output: Hello Friends
Math.abs(number)
// Returns the absolute value of a number
e.g.
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-168.88));
System.out.println(Math.abs(168.88));
}
}
// Output:
168.88
168.88
abstract class/method
// "abstract" is used in class or method
// Abstract class works as a parent class, which will be extended by its subclass. The method of the subclass will
override the abstract method of the abstract class.
// "abstract class" cannot create any object.
// "abstract method" is used in abstract class only
// "abstract method" is an empty method without a body.
e.g.
abstract class Book{ // create an abstract class
abstract void reading(); // create an abstract method
}
class eBook extends Book{ // extend the parent class
void reading(){ // override the abstract method
System.out.println("I override that abstract method.");
}}
public class AbstractDemo {
public static void main(String[] args){
eBook obj =new eBook();
obj.reading();
}}
// Output: I override that abstract method.
Math.acos(number)
// Return the arc cosine value of a number
e.g.
public class Main {
public static void main(String[] args) {
System.out.println(Math.acos(0.88));
System.out.println(Math.acos(-0.88));
System.out.println(Math.acos(0));
}}
// Output:
0.4949341263408955
2.646658527248898
1.5707963267948966
collection.add(element);
// Add an element to a collection
// Collection refers to LinkedList, ArrayList, HashSet and List.
e.g.
import java.util.HashSet;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<Integer> mySet = new HashSet<>();
//add integer values in this collection
mySet.add(10);
mySet.add(20);
mySet.add(30);
System.out.print("Collection elements : ");
System.out.println(mySet);
}}
// Output: Collection elements : [20, 10, 30]
Collections.addAll(mySet, 10, 20, 30, 40, 50);
// Add all elements to a collection
// Collection refers to LinkedList, ArrayList, HashSet, List
e.g.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class MyClass {
public static void main(String[] args) {
Set<Integer> mySet = new HashSet<>();
Collections.addAll(mySet, 10, 20, 30, 40, 50);
// add all elements to mySet
System.out.println("Collection elements : "+mySet);
}}
// Output: Collection elements : [50, 20, 40, 10, 30]
Math.addExact(num1, num2)
// Returns the sum of two numbers
e.g.
class Main {
public static void main(String[] args) {
int x = 36;
int y = 52;
System.out.println(Math.addExact(x, y));
}}
// Output: 88
Arrays.sort(array_name);
// Sort the array element, and display the result in order.
// Before using Arrays.sort(), you must "import java.util.Arrays";
e.g.
package tryPackage;
import java.util.Arrays;
public class SortArrClass{
public static void main (String [ ] args){
String arr[ ] = { "Cod", "App", "Dot", "Bay"};
Arrays.sort(arr); // sort the array
for(int n=0; n<arr.length; n++){ // run 4 times
System.out.print (arr[n]+" "); // n is a key
}}}
// Output: App Bay Cod Dot
Math.atan(number)
// Returns the arctangent value of a number between -PI/2 and PI/2 radians
e.g.
public class Main {
public static void main(String[] args) {
double x = 0.88;
double y = 0.0;
double z = 1.0;
System.out.println(Math.atan(x));
System.out.println(Math.atan(y));
System.out.println(Math.atan(z));
}}
// Output:
0.7216548508647612
0.0
0.7853981633974483
break;
// Terminate a loop or a switch block
e.g.
for (int n = 1; n < 8; n++) {
if (n == 6) {
break;
}
System.out.print(n);
}
// Output: 12345
case value:
// Marks code blocks in switch statements
e.g.
int number = 2;
switch (number) {
case 1:
System.out.println("Number 1");
break;
case 2:
System.out.println("Number 2");
break;
}
// Output: Number 2
Math.cbrt(number)
// Returns the cube root value of a number
e.g.
class Main {
public static void main(String[] args) {
double a = 125.0;
double b = -27;
double c = 0.0;
System.out.println(Math.cbrt(a));
System.out.println(Math.cbrt(b));
System.out.println(Math.cbrt(c));
}}
// Output:
5.0
-3.0
0.0
Math.ceil(number)
// Return a nearest integer that is greater than or equal to its argument.
e.g.
public class Main {
public static void main(String[] args) {
double num = 3.14;
System.out.println(Math.ceil(num));
}}
// Output: 4.0
string.charAt(index)
// Return a character at the specified index
e.g.
public class Main{
public static void main(String []args){
String str = "kindle";
char c = str.charAt(2);
System.out.println(c);
}}
// Output: n
Java Exception Handling

• Java Exceptions, Java Exception Handling, Java try...catch, Java throw


and throws, Java catch Multiple Exceptions, Java Annotations Types
Exception Handling
• The Exception Handling in Java is one of the powerful mechanisms
to handle runtime errors so that the normal flow of the application can
be maintained.
• What is an Exception in Java?
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
What is Exception in Java?

• Exception in Java is an event that interrupts the execution of program


instructions and disturbs the normal flow of program execution.
• It is an object that wraps an error event information that occurred
within a method and it is passed to the runtime system.
• In Java, exceptions are mainly used to indicate different error
conditions.
• There are two types of errors:
1.Compile time errors
2.Runtime errors
• Compile time errors can be classified into two types:
• Syntax Errors
• Semantic Errors
Error & Exception
• Error: An Error indicates a serious problem that a reasonable
application should not try to catch.
• Exception: Exception indicates conditions that a reasonable
application might try to catch.
Syntax Errors Example
• Instead of declaring int a; you mistakenly declared it as in a; for
which the compiler will throw an error.
• Example: You have declared a variable int a; and after some lines of
code you again declare an integer as int a;. All these errors are
highlighted when you compile the code.
Runtime Errors Example

• A Runtime error is called an Exceptions error. It is an event that


interrupts the normal flow of program execution.
• Examples for exceptions are arithmetic exceptions, Nullpointer
exceptions, Divide by zero exceptions, etc.
• Exceptions in Java are something that is out of developers’ control.
Why do we need Exception?

• Suppose you have coded a program to access the server. Things


worked fine while you were developing the code.
• During the actual production run, the server is down. When your
program tries to access it, an exception is raised.
How to Handle Exception

• So far we have seen, the exception is


beyond the developer’s control. But
blaming your code failure on
environmental issues is not a solution.
You need Robust Programming, which
takes care of exceptional situations.
Such code is known as Exception
Handler.
• In our example, good exception
handling would be, when the server is
down, connect to the backup server.
Try Catch Block

1.The normal code goes into a TRY block.


2.The exception handling code goes into
the CATCH block
• In our example, the TRY block will
contain the code to connect to the
server. The CATCH block will
contain the code to connect to the
backup server.
• In case the server is up, the code in
the CATCH block will be ignored. In
case the server is down, an exception
is raised, and the code in the catch
block will be executed.
Syntax for using try & catch
try{
statement(s)
}
catch (exception type name){
statement(s)
}
class JavaException {
public static void main(String args[]){
int d = 0;
int n = 20;
int fraction = n/d;
System.out.println("End of Main");
}
}
What Causes Runtime Errors in Java

• Dividing a number by zero.


• Accessing an element in an array that is out of range.
• Attempting to store an incompatible type value to a collection.
• Passing an invalid argument to a method.
• Attempting to convert an invalid string to a number.
• Insufficient space in memory for thread data.
How to Solve Runtime Errors

• Runtime errors can be handled in Java using try-catch blocks with the
following steps:
• Surround the statements that can throw a runtime error in try-catch
blocks.
• Catch the error.
• Depending on the requirements of the application, take necessary
action. For example, log the exception with an appropriate message.
Top 10 common Java compile errors and how to fix them

1. Java source file name mismatch


2. Improper casing
3. Mismatched brackets
4. Missing semicolons
5. Method is undefined
6. Variable already defined
7. Variable not initialized
8. Type mismatch: cannot convert
9. Return type required
10.Unreachable code
Compile-Time Errors Runtime-Errors
These are the syntax errors which are detected by the These are the errors which are not detected by the compiler
compiler. and produce wrong results.

They prevent the code from running as it detects some


They prevent the code from complete execution.
syntax errors.

It includes syntax errors such as missing of semicolon(;), It includes errors such as dividing a number by zero,
misspelling of keywords and identifiers etc. finding square root of a negative number etc.
Major reasons why an exception Occurs

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Hierarchy of Java Exception classes

• The java.lang.Throwable class is the root class of Java Exception


hierarchy inherited by two subclasses: Exception and Error.
Java try and catch
• The try statement allows you to define a block of code to be tested for
errors while it is being executed.
• The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
Types of Java Exceptions

• There are mainly two types of exceptions:


checked and unchecked. An error is
considered as an unchecked exception.
However, according to Oracle, there are
three types of exceptions namely:
1.Checked Exception
2.Unchecked Exception
3.Error
Java Exceptions
• All exception classes in Java extend the class ‘Throwable’.
• Throwable has two subclasses, Error and Exception
• The Error class defines the exception or the problems that are not
expected to occur under normal circumstances by our program,
example Memory error, Hardware error, JVM error, etc
• The Exception class represents the exceptions that can be handled by
our program, and our program can be recovered from this exception
using try and catch block
Java Exceptions
• A Runtime exception is a sub-class of the exception class.
• The Exception of these type represents exception that occur at the run
time and which cannot be tracked at the compile time.
• An excellent example of the same is divide by zero exception, or null
pointer exception, etc
• IO exception is generated during input and output operations
• Interrupted exceptions in Java, is generated during multiple threading.
Java Finally Block

try {
statement(s)
} catch (ExceptiontType name) {
statement(s)
} finally {
statement(s)
}
class JavaException {
public static void main(String args[]){
try{
int d = 0;
int n =20;
int fraction = n/d;
}
catch(ArithmeticException e){
System.out.println("In the catch block due to Exception = "+e);
}
finally{
System.out.println("Inside the finally block");
}
}
}
List of Runtime Exception examples
1. ArithmeticException
2. NullPointerException
3. ClassCastException
4. DateTimeException
5. ArrayIndexOutOfBoundsException
6. NegativeArraySizeException
7. ArrayStoreException
8. UnsupportedOperationException
9. NoSuchElementException
10.ConcurrentModificationException
Constructors in Java

• 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
Rules for Creating Java Constructors

• The name of the constructors must be the same as the class name.
• Java constructors do not have a return type. Even do not use void as a
return type.
• There can be multiple constructors in the same class, this concept is
known as constructor overloading.
• The access modifiers can be used with the constructors, use if you
want to change the visibility/accessibility of constructors.
• Java provides a default constructor that is invoked during the time of
object creation. If you create any type of constructor, the default
constructor (provided by Java) is not invoked
Types of Java constructors

•Default Constructor
•No-Args Constructor
•Parameterized Constructor
Default Constructor
• If you do not create any constructor in the class, Java provides a
default constructor that initializes the object.
public class Main {
int num1;
int num2;

public static void main(String[] args) {


// We didn't created any structure
// a default constructor will invoke here
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}
• num1 : 0
• num2 : 0
No-Args (No Argument) Constructor

• As the name specifies, the No-argument constructor does not accept


any argument.
• By using the No-Args constructor you can initialize the class data
members and perform various activities that you want on object
creation.
• Example: No-Args Constructor
public class Main {
int num1;
int num2;

// Creating no-args constructor


Main() {
num1 = -1;
num2 = -1;
}

public static void main(String[] args) {


// no-args constructor will invoke
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}
num1 : -1
num2 : -1
Parameterized Constructor

• A constructor with one or more arguments is called a parameterized


constructor.
• Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way that
they are added to a method, just declare them inside the parentheses
after the constructor's name.
public class Main {
int num1;
int num2;
// Creating parameterized constructor
Main(int a, int b) {
num1 = a;
num2 = b;
}
public static void main(String[] args) {
// Creating two objects by passing the values
// to initialize the attributes.
// parameterized constructor will invoke
Main obj_x = new Main(10, 20);
Main obj_y = new Main(100, 200);

// Printing the objects values


System.out.println("obj_x");
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);

System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
• obj_x
• num1 : 10
• num2 : 20
• obj_y
• num1 : 100
• num2 : 200
Constructor types:

• No-Arg Constructor - a constructor that does not accept any arguments


• Parameterized constructor - a constructor that accepts arguments
• Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but can not be overridden
Constructor
Description Example

Default constructor Automatically provided by Java if no other public MyClass()


constructor is defined.

Parameterized constructor Accepts arguments to initialize object properties public Car(String make, String model, int year)
with specific values.

Private constructor Restricts object creation from outside the class. private Employee()

Copy constructor Creates a new object by copying the state of public Person(Person other)
another object.
What is Inheritance?

• Inheritance is a mechanism in which one class acquires the property


of another class.
• For example, a child inherits the traits of his/her parents.
• With inheritance, we can reuse the fields and methods of the existing
class.
• Hence, inheritance facilitates Reusability and is an important concept
of OOPs.
Inheritance
• Inheritance is a mechanism of driving a new class from an existing
class.
• The existing (old) class is known as the base class or super class or
parent class. The new class is known as a derived class or sub class or
child class. It allows us to use the properties and behavior of one class
(parent) in another class (child).
• A class whose properties are inherited is known as parent class and a
class that inherits the properties of the parent class is known as child
class.
• Thus, it establishes a relationship between parent and child class that is
known as parent-child or Is-a relationship.
Points to Remember

• Constructor cannot be inherited in Java.


• Private members do not get inherited in Java.
• Cyclic inheritance is not permitted in Java.
• Assign parent reference to child objects.
• Constructors get executed because of super() present in the
constructor.
Types of Inheritance

• Single Inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance

• In single inheritance, a sub-class is derived from only one super class.


It inherits the properties and behavior of a single-parent class.
Sometimes it is also known as simple inheritance.


class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Multi-level Inheritance

• In multi-level inheritance, a class is derived from a class which is


also derived from another class is called multi-level inheritance.
• In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance.
• Note that the classes must be at different levels.
• Hence, there exists a single base class and single derived class but
multiple intermediate base classes.
Hierarchical Inheritance

• If a number of classes are derived from a single base class, it is


called hierarchical inheritance.
Hybrid Inheritance

• Hybrid means consist of more than one. Hybrid inheritance is the


combination of two or more types of inheritance.
Java JDK, JRE and JVM

• JVM (Java Virtual Machine) is an abstract machine that enables your


computer to run a Java program.
• When you run the Java program, Java compiler first compiles your
Java code to bytecode.
• Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).
• Java is a platform-independent language. It's because when you write
Java code, it's ultimately written for JVM but not your physical
machine (computer). Since JVM executes the Java bytecode which is
platform-independent, Java is platform-independent.
The JVM performs the following main tasks:

• Loads code
• Verifies code
• Executes code
• Provides runtime environment
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine
(JVM), and other components that are required to run Java applications.JRE is the superset of JVM.

What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in Java. When you
download JDK, JRE is also downloaded with it.
In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java Debugger, etc).
Relationship between JVM, JRE, and JDK.
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 behavior.
• A Java interface contains static constants and abstract methods.
What are Interfaces in Java?

• 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 inheritances in Java using
Interface. In other words, you can say that interfaces can only have
methods that are abstract and variables that are public, static and final
by default. It cannot have a method body. Java Interface
also represents the IS-A relationship.
• When we decide on a type of entity by its behavior and not via
attribute we should define it as an interface.
Interfaces in Java
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Uses of Interfaces in Java

• It is used to achieve total abstraction.


• Since java does not support multiple inheritances in the case of class,
by using an interface it can achieve multiple inheritances.
• Any class can extend only 1 class, but can any class implement an
infinite number of interfaces.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
Relationship Between Class and Interface

• A class can extend another class similar to this an interface can extend another
interface. But only a class can extend to another interface, and vice-versa is not
allowed.
Difference Between Class and Interface

Class Interface

In an interface, you can’t instantiate variables and create an


In class, you can instantiate variables and create an object.
object.

A class can contain concrete (with implementation) methods The interface cannot contain concrete (with implementation) methods.

The access specifiers used with classes are private, protected, and public. In Interface only one specifier is used- Public.
EXAMPLE 1: SWAP TWO NUMBERS IN JAVA USING A TEMPORARY VARIABLE
public class swap {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swapping logic using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
EXAMPLE 2: SWAP TWO NUMBERS IN JAVA WITHOUT USING A TEMPORARY VARIABLE
public class swap {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;

System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);

num1 = num1 + num2;


num2 = num1 - num2;
num1 = num1 - num2;

System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
class Sem1 class Sem2 extends Sem1
{ {
int m11,m12,m13,m14,avg1;
int m21,m22,m23,m24,avg2;
Sem1() Sem2()
{ {
m11=95; m21=89;
m12=93; m22=98;
m13=88; m23=97;
m14=90; m24=79;
avg1=(m11+m12+m13+m14)/4; avg2=(m21+m22+m23+m24)/4;
} }
} }
class Sem4 extends Sem3
class Sem3 extends Sem2 {
{
int m41,m42,m43,m44,avg4;
int m31,m32,m33,m34,avg3; Sem4()
Sem3() {
{ m41=79;
m31=87; m42=90;
m32=78; m43=77;
m33=88; m44=96;avg4=(m41+m42+m43+m44)/4;
m34=96; }
int totatavg()
avg3=(m31+m32+m33+m34)/4; {
return (avg1+avg2+avg3+avg4)/4;
} }
} }
class MultipleInheritanceExample2
{
public static void main(String args[])
{

Sem4 s4=new Sem4();


System.out.println("semester 1 avg"+s4.avg1);
System.out.println("semester 2 avg"+s4.avg2);
System.out.println("semester 3 avg"+s4.avg3);
System.out.println("semester 4 avg"+s4.avg4);

System.out.println("total average "+s4.totatavg());


}
}

semester 1 avg 91
semester 2 avg 90
semester 3 avg 87
semester 4 avg 85
total average 88
• Multithreading
• Introduction, Thread Creations, Thread Life Cycle, Life
Cycle Methods, Java Synchronization methods, User-defined
packages
What is a Thread in Java?

• A thread is the smallest segment of an entire process.


• A thread is an independent, virtual, and sequential control flow within a process.
• In-process execution, involves a collection of threads, and each thread shares the
same memory.
• Each thread performs the job independently of another thread.
•New − A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread. It is also referred to as a born thread.
•Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
•Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to
perform a task. A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing.
•Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or when the event
it is waiting for occurs.
•Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
• There are various stages of the life cycle of thread
1.New
2.Runnable
3.Running
4.Waiting
5.Dead
• New
• The first stage is "New". This stage is where it initiates the thread.
After that, every thread remains in the new state until the thread gets
assigned to a new task.
• Runnable
• The next stage is the runnable stage. Here, a thread gets assigned to
the task and sets itself for running it.
• Running
• The third stage is the execution stage.
• Here, the thread gets triggered as control enters the thread, and the thread performs
a task and continues the execution until it finishes the job.
• Waiting
• At times, there is a possibility that one process as a whole might depend on
another.
• During such an encounter, the thread might halt for an intermediate result because
of its dependency on a different process.
• This stage is called the Waiting Stage.
• Dead
• The final stage of the process execution with Multithreading in Java is
thread termination.
• After it terminates the process, the JVM automatically declares the
thread dead and terminates the thread.
• This stage is known as the dead thread stage.
What is Multiprocessing?

• A multiprocessing system has more than two processors.


• The CPUs are added to the system which helps to increase the computing speed of
the system.
• Every CPU has its own set of registers and main memory.
• However, because each CPU is separate, it may happen that one CPU may not
have anything to process.
• One processor may sit idle, and the other may be overloaded with the specific
processes.
• In such a case, the process and resources are shared dynamically among the
processors.
What is Multithreading?

• Multithreading is a program execution technique that allows a single


process to have multiple code segments (like threads).
• It also runs concurrently within the “context” of that process.
• Multi-threaded applications are applications that have two or more
threads that run concurrently.
• Therefore, it is also known as concurrency.
Characteristics of Multiprocessing

• Multiprocessing are classified according to the way their memory is


organized.
• Multiprocessing improves the reliability of the system
• Multiprocessing can improve performance by decomposing a program
into parallel executable tasks.
Characteristics of Multithreading

• In the multithreading process, each thread runs parallel to each other.


• Threads do not allow you to separate the memory area.
• Therefore it saves memory and offers a better application performance
Advantage of Multiprocessing
• The biggest advantage of a multiprocessor system is that it helps you to get more work done in a shorter
period.
• The code is usually straightforward.
• Takes advantage of multiple CPU & cores
• Helps you to avoid GIL limitations for CPython
• Remove synchronization primitives unless if you use shared memory.
• Child processes are mostly interruptible/killable
• It helps you to get work done in a shorter period.
• These types of systems should be used when very high speed is required to process a large volume of data.
• Multiprocessing systems save money compared to single processor systems as processors can share
peripherals and power supplies.
Advantage of Multithreading

• Threads share the same address space


• Threads are lightweight and have a low memory footprint
• The cost of communication between threads is low.
• Access to memory state from another context is easier
• It allows you to make responsive UIs easily
• An ideal option for I/O-bound applications
• Takes less time to switch between two threads within the shared memory and time to terminate
• Threads are faster to start than processes and also faster in task-switching.
• All Threads share a process memory pool that is very beneficial.
• It Takes less time to create a new thread in the existing process than a new process
Disadvantage of Multiprocessing

• IPC(Inter-Process Communication) a quite complicated with more


overhead
• Has a larger memory footprint
Disadvantage of multithreading

• Multithreading system is not interruptible/killable


• If not following a command queue and message pump model then
manual use of synchronization is needed which becomes a necessity
• Code is usually harder to understand and increases the potential for
race conditions to increase dramatically
Difference Between Multiprocessing and Multithreading
Parameter Multiprocessing Multithreading
Multiprocessing helps you to increase Multithreading helps you to create computing threads of
Basic
computing power. a single process to increase computing power.
It allows you to execute multiple Multiple threads of a single process are executed
Execution
processes concurrently. concurrently.
In Multiprocessing, CPU has to
In multithreading, CPU has to switch between multiple
switch between multiple programs so
CPU switching threads to make it appear that all threads are running
that it looks like that multiple
simultaneously.
programs are running simultaneously.
The creation of a process is slow and The creation of a thread is economical in time and
Creation
resource-specific. resource.
Multiprocessing can be symmetric or
Classification Multithreading is not classified.
asymmetric.
Multiprocessing allocates separate Multithreading threads belonging to the same process
Memory memory and resources for each share the same memory and resources as that of the
process or program. process.
Multiprocessing relies on pickling objects in memory to
Pickling objects Multithreading avoids pickling.
send to other processes.
Multiprocessing system allows
Multithreading system executes multiple threads of the
Program executing multiple programs and
same or different processes.
tasks.
Time taken Less time is taken for job processing. A moderate amount of time is taken for job processing.
Java List & I/O Streams

• String classes, methods, operations on Strings and 1-D Arrays, 2-D and Jagged Arrays and its operations
• Java Collections Framework, Java Collection Interface, Java List Interface, Java Array List, Java Vector, Java
Stack Introduction to Byte-oriented and Character-oriented streams, Java I/O Streams, and Java Reader/Writer
Java I/O Streams

• An input stream is used to read data from the source. And, an output
stream is used to write data to the destination.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
• For example, in our first Hello World example, we have used System.out to print a
string. Here, the System.out is a type of output stream.
Types of Streams

• Depending upon the data a stream holds, it can be classified into:


• Byte Stream
• Character Stream
Byte Stream & Character Stream

• Byte stream reads and writes a single byte (8 bits) of data.


• All byte stream classes are derived from base abstract classes
called InputStream and OutputStream.
• Character Stream
• Character stream is used to read and write a single character of data.
• All the character stream classes are derived from base abstract classes
Reader and Writer.
Java Collections Framework

• 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.
Interfaces of Collections FrameWork

• The Java collections framework provides various interfaces. These


interfaces include several methods to perform different operations on
collections.
Java List

• In Java, the List interface is an ordered collection that allows us to


store and access elements sequentially.
• It extends the Collection interface.
Classes that Implement List

• Since List is an interface, we cannot create objects from it.


• To use the functionalities of the List interface, we can use these
classes:
• ArrayList
• LinkedList
• Vector
• Stack
How to use List?

• // ArrayList implementation of List


• List<String> list1 = new ArrayList<>();

• // LinkedList implementation of List


• List<String> list2 = new LinkedList<>();
Methods of List
Methods Description
add() adds an element to a list
addAll() adds all elements of one list to another
get() helps to randomly access elements from lists
returns iterator object that can be used to
iterator()
sequentially access elements of lists
set() changes elements of lists
remove() removes an element from the list
removeAll() removes all the elements from the list
removes all the elements from the list (more
clear()
efficient than removeAll())
size() returns the length of lists
toArray() converts a list into an array
contains() returns true if a list contains specific element
Implementing the ArrayList Class
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();
// Add elements to the list
numbers.add(1); List: [1, 2, 3]
numbers.add(2); [0,1,2]
numbers.add(3); Accessed Element: 2
System.out.println("List: " + numbers); Removed Element: 1
// Access element from the list
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
// Remove element from the list
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
import java.util.List; Implementing the LinkedList Class
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// Creating list using the LinkedList class
List<Integer> numbers = new LinkedList<>();
// Add elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3); List: [22,55,33,66]
System.out.println("List: " + numbers); [0,1,2,3]
// Access element from the list Accessed Element: 2
int number = numbers.get(2); Position of 2 is 33
System.out.println("Accessed Element: " + number); Removed Element: 1,0
// Using the indexOf() method
int index = numbers.indexOf(2);
System.out.println("Position of 3 is " + index);
// Remove element from the list
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}
Java Stack Class
• The Java collections framework has a class named Stack that provides
the functionality of the stack data structure.
• The Stack class extends the Vector class.
Stack Implementation

• In stack, elements are stored and accessed in Last In First Out


manner.
• Elements are added to the top of the stack and removed from the
top.
Creating a Stack

• // Create Integer type stack


• Stack<Integer> stacks = new Stack<>();

• // Create String type stack


• Stack<String> stacks = new Stack<>();
push() Method

import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse"); Stack: [Dog, Horse, Cat]
animals.push("Cat");

System.out.println("Stack: " + animals);


}
}
pop() Method
To remove an element from the top of the stack, we use the pop() method.

import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack Initial Stack: [Dog, Horse, Cat]


animals.push("Dog"); Removed Element: Cat
animals.push("Horse");
animals.push("Cat");
System.out.println("Initial Stack: " + animals);

// Remove element stacks


String element = animals.pop();
System.out.println("Removed Element: " + element);
}
}
peek() Method
The peek() method returns an object from the top of the stack.

import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack Stack: [Dog, Horse, Cat]


animals.push("Dog"); Element at top: Horse
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);

// Access element from the top


String element = animals.peek();
System.out.println("Element at top: " + element);

}
}
search() Method
To search for an element in the stack, we use the search() method. It returns the position of the element from the
top of the stack.

import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Stack: [Dog, Horse, Cat]
// Add elements to Stack [1 to n] rest of list
animals.push("Dog"); Array [0 to n ]
animals.push("Horse"); Position of 1: dog
animals.push("Cat");
System.out.println("Stack: " + animals);

// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
empty() Method
To check whether a stack is empty or not, we use the empty() method.

import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack Stack: [Dog, Horse, Cat]


animals.push("Dog"); Is the stack empty? false
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);

// Check if stack is empty


boolean result = animals.empty();
System.out.println("Is the stack empty? " + result);
}
}
List interface
1.java.util.ArrayList
2.java.util.LinkedList
3.java.util.Vector
4.java.util.Stack
ArrayList

• Implemented by using a re-sizable array (Dynamic array).


• It can contain duplicates.
• ArrayList is not synchronized .
• Maintain insertion order.
• Default initial capacity is very small. Once it is filled its size will be
incremented by 50%.
• It allows random access and it is fast. But Inserting and deleting is
slow.
• This uses iterator to traverse.
LinkedList

• Implemented by using doubly LinkedList


• Duplicates are allowed.
• LinkedList is not synchronized.
• Maintain insertion order.
• LinkedList allows sequential access and it slow, but inserting and
deleting is fast.
• LinkedList doesn't have initial size.
• Compare to ArrayList and Vector, LinkedLIst uses more memory.
Vector

• Vector looks same as ArrayList.


• Main difference is, Vector is synchronized.
• Accessibility is slow, because Vector is synchronized.
• Once it is filled, initial capacity is incremented by 100%.
• Vector uses Enumeration to traverse.
Stack

• This is another simple class which is extended to Vector class.


• Stack is Last In First Out (LIFO) manner collection.
• Stack is also synchronized just like Vector, then Stack is also slow.
• Stack has few special methods, push(), pop() and peek().
Hierarchy of Collection Framework
Stack (Java)
•implements List and extends Vector (Vector class is thread-safe)
Array List Vs Vector
Feature ArrayList Vector
Vector is synchronized, making it thread-
1. Synchronization ArrayList is not synchronized.
safe.
Vector doubles its array size when
2. Capacity Increment ArrayList increases capacity by 50%
exceeding capacity.
Vector is considered a legacy class,
3. Legacy Status ArrayList is not a legacy class.
introduced earlier in Java's history.
Vector is slower due to synchronization,
ArrayList is fast as it's non-
making it safer for multithreaded
4. Thread Safety synchronized, suitable for single-
environments but potentially slower for
threaded environments.
single-threaded operations.
ArrayList uses the Iterator interface for Vector can use either the Iterator
5. Element Traversal element traversal, providing flexibility interface or the older Enumeration
and compatibility. interface for element traversal.
ArrayList generally offers higher Vector may exhibit lower performance
6. Performance performance in single-threaded due to synchronization overhead in
scenarios. multithreaded scenarios.
ArrayList allows multiple threads but Vector inherently supports thread safety
7. Thread Support requires external synchronization for for operations in a multithreaded
thread safety. environment.
3 categories of classes in java.io package
• There are 3 categories of classes in java.io package:
• Input Streams.
• Output Streams.
• Error Streams.
• Java supports three streams that are automatically attached to the
console.
1.System.out: Standard output stream
2.System.in: Standard input stream
3.System.err: Standard error stream
What are Streams in Java?

• A java stream is a group of objects that can be piped together to


produce the desired result.
• Streams are used in Java to transfer data between programs and I/O
devices like a file, network connections, or consoles.
What are the different Types of Streams
in Java?
Difference between Byte Stream and Character Stream

Byte Stream Character Stream


It operates on raw binary data and data is It operates on text data and is processed character
processed byte by byte by character

Suitable for processing non-textual data such as Suitable for processing textual data such as
images, videos, etc. documents, HTML, etc.

Input and Output operations are performed using Input and Output operations are performed using
InputStream and OutputStream classes Reader and Writer classes

Suitable for high-level input and output


Suitable for low-level input and output operations
operations
Examples include FileInputStream and
Examples include FileReader and FileWriter
FileOutputStream
Byte Stream Vs Character Stream In Java

Byte Stream Character Stream


They process the data character by
They process the data byte by byte.
character.
They read/write data 8 bits maximum at They read/write data 16 bits maximum at
a time. a time.
They are most suitable to process binary They are most suitable to process text
files. files.
All byte stream classes in Java are
All character stream classes in Java are
descendants of InputStream and
descendants of Reader and Writer.
OutputStream.
Reading and Writing Files
What is Vector in Java?

• Vector is a data structure that is used to store a collection of elements.


• Elements can be of all primitive types like int, float, Object, etc.
• Vectors are dynamic in nature and accordingly, grow or shrink as per the
requirement.
• Vector Class in Java is found in the java.util package.
• Vector class is a child class of the AbstractList class and implements
the List interface.
• Therefore we can use all the methods of the List interface.
• Vectors are known to give Concurrent Modification Exception when accessed
concurrently at the time of modification
What is Vector in Java?

• When a Vector is created, it has a certain capacity to store elements


that can be defined initially.
• This capacity is dynamic in nature and can be increased or decreased.
• By definition, Vectors are synchronized, which implies that at a time,
only one thread is able to access the code while other threads have to
wait.
• Due to this, Vectors are slower in performance as they acquire a lock
on a thread.
Declaration of Vector in Java

• public class Vector<E> extends AbstractList<E> implements List<E>,


RandomAccess, Cloneable, Serializable
• Here, E denotes the Element Type
• Vector Class extends AbstractList and implements multiple interfaces
like Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAcces
s interfaces.
• The directly known subclass is Stack.
Important points regarding the Increment of
vector capacity
• In each allocation cycle, Vector will expand in accordance with the
increment if one is supplied. However, if the increment is left
unspecified, each allocation cycle doubles the vector's capacity. Three
protected data members are defined by Vector:
• int capacityIncreament: Contains the value of the increment.
• int elementCount: Number of elements that are currently stored in
the vector.
• Object elementData[]: The vector is kept in an array that is stored in
it
Common Errors in the Declaration of Vectors

• If the InitialSize of the vector defined is negative, Vector throws an


IllegalArgumentException.
• It throws a NullPointerException if the specified collection is null.
Constructors in Vectors

• Vector(): A default vector of capacity 10 gets created while calling this


constructor.
• Vector<E> defaultVector = new Vector<E>(); //Here E represents Element Type.
• Vector(int size): A vector is created with the given size as its capacity.
• Vector<E> initialCapacityVector = new Vector<E>(int size);
• Vector(int size, int increment): A vector is created with the given size as its
initial capacity, and whenever the capacity needs to be increased, it is increased by
the given increment count.
• Vector<E> incrementalVector = new Vector<E>(int size, int increment);
import java.io.*; v.add(i);
import java.util.*;
// Printing elements
// Main class System.out.println(v);
class Academy {
// Remove element at index 3
// Main driver method v.remove(3);
public static void main(String[] args)
{ // Displaying the vector
// Size of the Vector // after deletion
int n = 5; System.out.println(v);
// Declaring the Vector with // iterating over vector elements
// initial size n // using for loop
Vector<Integer> v = new for (int i = 0; i < v.size(); i++)
Vector<Integer>(n);
// Printing elements one by one
// Appending new elements at System.out.print(v.get(i) + " ");
// the end of the vector }
for (int i = 1; i <= n; i++) }
• [1, 2, 3, 4, 5]
• [1, 2, 3, 5]
•1235
Operations in Java Vectors

• Adding elements to the vector.


• Iterating over the elements we added in the vector.
• Replacing elements at certain indexes in the vector.
• Removing elements from the vector.
Java Arrays

• Arrays in Java are non-primitive data types that store elements of a


similar data type in the memory.
• Arrays in Java can store both primitive and non-primitive types of data
in it.
• There are two types of arrays, single-dimensional arrays have only
one dimension, while multi-dimensional have 2D, 3D, and nD
dimensions.
Java Arrays

• An array is a homogenous non-primitive data type used to save


multiple elements (having the same data type) in a particular variable.
• Arrays in Java can hold primitive data types (Integer, Character, Float,
etc.) and non-primitive data types(Object).
• The values of primitive data types are stored in a memory location,
whereas in the case of objects, it's stored in heap memory.
Example
• Assume we have to write a code that takes the marks of five students.
Instead of creating five different variables, we can just create an array
of lengths of five.
• As a result, it is so easy to store and access data from only one
place, and also, it is memory efficient.
How do Arrays in Java work?

• An array is a data structure or container that stores the same typed


elements in a sequential format.
• int mark1 = 78;
• int mark2 = 84;
• int mark3 = 63;
• int mark4 = 91;
• int mark5 = 75;
• But what if we store all these five variables in one single variable?
• marks[0] = 78;
• marks[1] = 84;
• marks[2] = 63;
• marks[3] = 91;
• marks[4] = 75;
• All above mentioned five variables could
be accessed by the index given in the
square bracket, which is known as index-
based variables.
• The index always starts from 0 by
default. So, if we have an array of 5
elements, it will have an index range
from 0 to 4 by default.
• In the above example, the first element is
stored at index 0 and the last one at the
4th index. The below-mentioned diagram
shows how the array got placed in
computer memory.
How to Create and Initialize Array in Java?

• In every program, to use an array, we need to create it before it is used.


We require two things to create an array in Java - data type and length.
• As we know, an array is a homogenous container that can only store
the same type of data. Hence, it's required to specify the data type
while creating it. Moreover, we also need to put the number of
elements the array will store.
Syntax:

• Unlike other programming languages, while declaring an array in java,


we can put [] both before and after the variable name.
• The new keyword is crucial to creating an array. Without using it, we
cannot make array reference variables.
• datatype[] arrayName = new datatype[length]; OR
• datatype arrayName[] = new datatype[length];
• //[length] = Length of the array
Example

• // Both will create an int array with a length of 5.

• int[] myArray = new int[5];


• int myArray1[] = new int[5];
We can Initialize Arrays in Java in two
Different ways -
• Initialize using index - Once an array is created successfully, we can
assign the value to any specific element using its index.
• Un-assigned elements automatically take the default value of the
array's data type.
• In this case, 0 for the integer data type.
• On the other hand, if we try to enter more values than the size of the
array, it will raise an ArrayIndexOutOfBoundsException.
Initialize using index
• int[] myArray = new int[5]; // array declared
• myArray[0] = 10; // assigned 10 at index 0
• myArray[2] = 37; // assigned 37 at index 0

• Array will be -
• 10 0 37 0 0
Initialize while declaring
• We can also initialize the whole array while declaring it just by using
curly brackets {}. The string must be in quotes, whereas int, float, etc.,
do not require that.
• int[] myArray = {1, 2, 3, 4, 5}; // For integer type
• String[] myArray1 = {"A", "B", "C", "D"}; // For string type
How to Change an Array Element?

• To change a value at a specific position in Java arrays, refer to an index.


• By providing index value, we tell the Java compiler where we want to change the
value.
• For this, we need to use a Square bracket [] with an index number inside it.
• If somehow we entered the index number bigger than the array length, then an
exception ocurs of type ArrayIndexOutOfBoundsException .
• int myArray[] = {1, 2, 3, 4, 5};
• myArray[1] = 5;
• // change the value 2 to 5 at index 1
public class Demo {
public static void main(String[] args) {
// declaring and initializing an array
int[] myArray = { 2, 3, 4, 5, 6 };
// print array element at index 0
System.out.println("Before change myArray[0]: " + myArray[0]);
// changing the array element
myArray[0] = 1;
// print array element at index 0
System.out.println("After change myArray[0]: " + myArray[0]);
}
}

Before change myArray[0]: 2


After change myArray[0]: 1
Types of Array in Java

• In Java, there are two types of arrays:


• Single-Dimensional Array
• Multi-Dimensional Array
Single Dimensional Array

• An array that has only one subscript or one dimension is known as a


single-dimensional array. It is just a list of the same data type
variables.
• One dimensional array can be of either one row and multiple columns
or multiple rows and one column. For instance, a student's marks in
five subjects indicate a single-dimensional array.
Example:
• int marks[] = {56, 98, 77, 89, 99};
public class Demo {
public static void main (String[] args) {
// declaring and initializing an array
String strArray[] = {"Python", "Java", "C++", "C", "PHP"};

// using a for-each loop for printing the array


for(String i : strArray) {
System.out.print(i + " ");
}

// find the length of an array


System.out.println("\nLength of array: "+strArray.length);

}
}

Python Java C++ C PHP


Length of array: 5
Multi-Dimensional Array

• In not all cases, we implement a single-dimensional array. Sometimes,


we are required to create an array within an array.
• Suppose we need to write a program that stores five different subjects and the
marks of sixty students.
• In this case, we just need to implement 60 one-dimensional arrays with a
length of five and then implement all these arrays in one array.
• Hence, we can make the 2D array with five columns and 60 rows.
• A multi-dimensional array is just an array of arrays that represents multiple
rows and columns.
• These arrays include 2D, 3D, and nD types. 2D data like tables and matrices
can be represented using this type of array.
• To implement a multi-dimensional array, one needs to add two square brackets
instead of one.
int marks[][] = {
{77,85,68,99,87},
{98,56,79,90,92},
{78,88,56,70,99}
};
OR
int marks[][] = new int[3][5];

// both will create a 2D array with 3 rows and 5 columns.


If we want to change any specific value, we need to use two square brackets, the first representing the rows and the
second representing the columns.

marks[1][2] = 84 // change value at 1st row and 2nd column from 79 to 84

//array will look like this -


77,85,68,99,87
98,56,84,90,92
78,88,56,70,99
// Printing Array2 in matrix format
System.out.println("Array2 -");
public class Demo { for(int i=0;i<3;i++) { // for-loop for number of rows
public static void main (String[] args) { for(int j=0;j<3;j++) { // for-loop for number of columns
// declaring and initializing arrays System.out.print(arr2[i][j] + " ");
int arr1[][] = {{1,2,3},{4,5,6},{7,8,9}}; }
int arr2[][] = {{2,2,2},{2,2,2},{2,2,2}}; System.out.println();
}
// Printing Array1 in matrix format // creating another array with the same dimensions to store
System.out.println("Array1 -"); the result
for(int i=0;i<3;i++) { // for-loop for number of rows int arr3[][] = new int[3][3];
for(int j=0;j<3;j++) { // for-loop for number of columns // Multiplying arr1 and arr2, storing results in arr3
System.out.print(arr1[i][j] + " "); System.out.println("Multiplication of Array1 and Array2 -
} ");
System.out.println(); for(int i=0;i<arr1.length;i++) {
} for(int j=0;j<arr2.length;j++) {
arr3[i][j] = 0;
for(int k=0;k<arr3.length;k++) {
arr3[i][j] += arr1[i][k] * arr2[k][j];
}
System.out.print(arr3[i][j] + " ");
}
System.out.println();
}
Array1 -
123
456
789
Array2 -
222
222
222
Multiplication of Array1 and Array2 -
12 12 12
30 30 30
48 48 48
ArrayIndexOutOfBoundsException

• JVM throws the runtime exception


of ArrayIndexOutOfBoundsExceptio
n, which points to an array accessed by
an illegal index.
public class Test {
public static void main (String[] args) {
// declaring and initializing an array
int myArray[] = new int[5];
myArray[0] = 3;
myArray[2] = 6;
myArray[4] = 9;
myArray[6] = 12; // index 6 not exists
for(int i : myArray) {
System.out.println(i);
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
at Test.main(Test.java:9)
Advantages and Disadvantages of Arrays in Java

• Advantages
• Can access an array element value randomly just by using the index indicated
by the array.
• At a time, we can store lots of values in arrays.
• It becomes easier to create and work with the multi-dimensional arrays.
• Disadvantages
• Arrays in Java do not have in-built remove or add methods.
• In Java arrays, we need to specify the size of the array. So there might be a change
of memory wastage. So, it is recommended to use ArrayList.
• Arrays in Java are strongly typed.
UNIT 5
• Database Applications with JDBC
• Database Applications with JDBC: Defining the layout of the JDBC
API - Connecting to a database by using a JDBC driver – Submitting
queries and getting results from the database - Specifying JDBC driver
information externally.
Java Database Connectivity
• JDBC stands for Java Database Connectivity is a Java API(Application
Programming Interface) used to interact with databases.
• JDBC is a specification from Sun Microsystems and it is used by Java
applications to communicate with relational databases.
• We can use JDBC to execute queries on various databases and perform operations
like SELECT, INSERT, UPDATE and DELETE.
• JDBC API helps Java applications interact with different databases like
MSSQL, ORACLE, MYSQL, etc.
• It consists of classes and interfaces of JDBC that allow the applications to access
databases and send requests made by users to the specified database.
Purpose of JDBC

• Java programming language is used to develop enterprise applications.


• These applications are developed with intention of solving real-life
problems and need to interact with databases to store required data and
perform operations on it.
• Hence, to interact with databases there is a need for efficient database
connectivity, ODBC(Open Database Connectivity) driver is used for
the same.
Purpose of JDBC
• ODBC is an API introduced by Microsoft and used to interact with
databases.
• It can be used by only the windows platform and can be used for any
language like C, C++, Java, etc.
• ODBC is procedural.
• JDBC is an API with classes and interfaces used to interact with
databases.
• It is used only for Java languages and can be used for any platform.
• JDBC is highly recommended for Java applications as there are no
performance or platform dependency problems.
Components of JDBC

• JDBC has four main components that are used to connect with a
database as follows:
1.JDBC API
2.JDBC Driver Manager
3.JDBC Test Suite
4.JDBC-ODBC Bridge Drivers
JDBC API

• JDBC API is a collection of various classes, methods, and interfaces


for easy communication with a database. JDBC API provides two
different packages to connect with different databases.
• java.sql.*;
• javax.sql.*;
• JDBC Driver Manager
• JDBC DriverManager is a class in JDBC API that loads a database-
specific driver in Java application and establishes a connection with a
database. DriverManager makes a call to a specific database to process
the user request.
• JDBC Test Suite
• JDBC Test Suite is used to test operations being performed on
databases using JDBC drivers. JDBC Test Suite tests operations such
as insertion, updating, and deletion.
JDBC-ODBC Bridge Drivers

• As the name suggests JDBC-ODBC Bridge Drivers are used to translate JDBC
methods to ODBC function calls.
• JDBC-ODBC Bridge Drivers are used to connect database drivers to the database.
Even after using JDBC for Java Enterprise Applications, we need an ODBC
connection for connecting with databases.
• JDBC-ODBC Bridge Drivers are used to bridge the same gap between JDBC and
ODBC drivers.
• The bridge translates the object-oriented JDBC method call to the procedural
ODBC function call.
• It makes use of the sun.jdbc.odbc package. This package includes a native library
to access ODBC characteristics.
Architecture of JDBC
The major components of JDBC architecture
1.Application
2.The JDBC API
3.DriverManager
4.JDBC Drivers
5.Data Sources
• Application
• Applications in JDBC architecture are java applications like applets or
servlet that communicates with databases.
• JDBC API
• The JDBC API is an Application Programming Interface used
to create Databases. JDBC API uses classes and interfaces to connect
with databases. Some of the important classes and interfaces defined
in JDBC architecture in java are the DriverManager class, Connection
Interface, etc.
• DriverManager
• DriverManager class in the JDBC architecture is used to establish a
connection between Java applications and databases.
• Using the getConnection method of this class a connection is established between
the Java application and data sources.
• JDBC Drivers
• JDBC drivers are used to connecting with data sources.
• All databases like Oracle, MSSQL, MYSQL, etc. have their drivers, to connect
with these databases we need to load their specific drivers.
• Class is a java class used to load drivers. Class.forName() method is used to load
drivers in JDBC architecture.
Data Sources

• Data Sources in the JDBC architecture are the databases that we can
connect using this API.
• These are the sources where data is stored and used by Java
applications.
• JDBC API helps to connect various databases like Oracle, MYSQL,
MSSQL, PostgreSQL, etc.
Types of JDBC Architecture

• The JDBC Architecture can be of two types based on the processing


models it uses. These models are
1.2-tier model
2.3-tier model
2 Tier Model
2 Tier Model
• 2-tier JDBC architecture model is a basic model.
• In this model, a java application communicates directly to the data sources. JDBC
driver is used to establish a connection between the application and the data
source.
• When an application needs to interact with a database, a query is directly executed
on the data source and the output of the queries is sent back to the user in form of
results.
• In this model, the data source can be located on a different machine connected to
the same network the user is connected to.
• This model is also known as a client/server configuration. Here user's machine
acts as a client and the machine on which the database is located acts as a server.
3 Tier Model
3 Tier Model

• 3-tier model is a complex and more secure model of JDBC architecture in java.
• In this model the user queries are sent to the middle tier and then they are executed
on the data source.
• Here, the java application is considered as one tier connected to the data
source(3rd tier) using middle-tier services.
• In this model user queries are sent to the data source using middle-tier services,
from where the commands are again sent to databases for execution.
• The results obtained on the database are again sent to the middle-tier and then to
the user/application.
Interfaces of JDBC API

• Driver interface - The JDBC Driver interface provided implementations of the


abstract classes such as java.sql.Connection, Statement, PreparedStatement,
Driver, etc. provided by the JDBC API.
• Connection interface - The connection interface is used to create a connection
with the database. getConnection() method of DriverManager class of the
Connection interface is used to get a Connection object.
• Statement interface - The Statement interface provides methods to execute SQL
queries on the database. executeQuery(), executeUpdate() methods of the
Statement interface are used to run SQL queries on the database.
Interfaces of JDBC API
• ResultSet interface - ResultSet interface is used to store and display
the result obtained by executing a SQL query on the
database. executeQuery() method of statement interface returns a
resultset object.
• RowSet interface - RowSet interface is a component of Java Bean. It
is a wrapper of ResultSet and is used to keep data in tabular form.
• ResultSetMetaData interface - Metadata means data about data.
ResultSetMetaData interface is used to get information about the
resultset interface. The object of the ResultSetMetaData interface
provides metadata of resultset like number of columns, column name,
total records, etc.
• DatabaseMetaData interface - DatabaseMetaData interface is used
to get information about the database vendor being used.
• It provides metadata like database product name, database product
version, total tables/views in the database, the driver used to connect
to the database, etc.
Classes of JDBC API

• DriverManager class - DriverManager class is a member of the java.sql package.


It is used to establish a connection between the database and its driver.
• Blob class - A java.sql.Blob is a binary large object that can store large amounts of
binary data, such as images or other types of files. Fields defined as TEXT also
hold large amounts of data.
• Clob class - The java.sql.Clob interface of the JDBC API represents the CLOB
datatype. Since the Clob object in JDBC is implemented using an SQL locator, it
holds a logical pointer to the SQL CLOB (not the data).
• Types class - Type class defined and store constants that are used to identify
generic SQL types also known as JDBC types
Working of JDBC

• Java applications need to be programmed for interacting with data


sources.
• JDBC Drivers for specific databases are to be loaded in a java
application for JDBC support which can be done dynamically at run
time.
• These JDBC drivers communicate with the respective data source.
Working of JDBC

• Steps to connect a Java program using JDBC API. 1. Load Driver: Load JDBC
Driver for specific databases using forName() method of class Class.
Syntax: Class.forName("com.mysql.jdbc.Driver")
• 2. Create Connection: Create a connection with a database using DriverManager
class. Database credentials are to be passed while establishing the connection.
Syntax: DriverManager.getConnection()
• 3. Create Query: To manipulate the database we need to create a query using
commands like INSERT, UPDATE, DELETE, etc. These queries are created and
stored in string format. Syntax: String sql_query = "INSERT INTO
Student(name, roll_no) values('ABC','XYZ')"
• 4. Create Statement: The query we have created is in form of a
string. To perform the operations in the string on a database we need to
fire that query on the database. To achieve this we need to convert a
string object into SQL statements. This can be done
using createStatement() and prepareStatement() interfaces.
Syntax: Statement St = con.createStatement();
• 5. Execute Statement: To execute SQL statements on the database we can use
two methods depending on which type of query we are executing.
• Execute Update: Execute update method is used to execute queries like insert,
update, delete, etc. Return type of executeUpdate() method is int. Syntax: int
check = st.executeUpdate(sql);
• Execute Query: Execute query method is used to execute queries used to display
data from the database, such as select. Return type of executeQuery() method is
result set. Syntax: Resultset = st.executeUpdate(sql);
• 6. Closing Statement: After performing operations on the database, it is better to
close every interface object to avoid further conflicts. Synatx: con.close();
Java Persistence API

• JPA architecture, ORM Components, - Performing CRUD


operations using the JDBC API. JPA installation, Java
Persistence Query language, Creating JPA entities, Advanced
mappings.
Java Persistence API

• JPA can be defined as Java Persistence API.


• It is the Java specification that can provide a standardized way to
manage the relational data in Java applications.
• JPA facilitates the management of the database operations and
mapping of the Java objects to database tables by defining the
concepts and APIs.
• It serves as the bridge between object-oriented domain models and
relational database systems.
JPA (Java Persistence API)

• The Java Persistence API (JPA) is the Java API specification that
bridges the gap between relational databases and object-oriented
programming by handling the mapping of the Java objects to the
database tables and vice-versa.
• This process is known as the Object Relational Mapping (ORM). JPA
can define the way Java classes (entities) are mapped to the database
tables and how they can interact with the database through the
EntityManager, the Persistence context, and transactions.
Key Terminologies in JPA

• Entity
• EntityManager
• Persistence Context
• Criteria API
• JPQL (Java Persistence Query Language)
• Persistence Unit
Where to use JPA?

• To reduce the burden of writing codes for relational object management, a


programmer follows the ‘JPA Provider’ framework, which allows easy interaction
with database instance. Here the required framework is taken over by JPA.
Class Level Architecture

• The following image shows the class level architecture of JPA. It


shows the core classes and interfaces of JPA.
Units Description
This is a factory class of EntityManager. It creates
EntityManagerFactory
and manages multiple EntityManager instances.

It is an Interface, it manages the persistence


EntityManager operations on objects. It works like factory for Query
instance.
Entities are the persistence objects, stores as records
Entity
in the database.

It has one-to-one relationship with EntityManager.


EntityTransaction For each EntityManager, operations are maintained
by EntityTransaction class.

This class contain static methods to obtain


Persistence
EntityManagerFactory instance.

This interface is implemented by each JPA vendor to


Query
obtain relational objects that meet the criteria.
JPA Class Relationships
Types of Mapping

• One-to-one - This association is represented by @OneToOne annotation. Here,


instance of each entity is related to a single instance of another entity.
• One-to-many - This association is represented by @OneToMany annotation. In
this relationship, an instance of one entity can be related to more than one instance
of another entity.
• Many-to-one - This mapping is defined by @ManyToOne annotation. In this
relationship, multiple instances of an entity can be related to single instance of
another entity.
• Many-to-many - This association is represented by @ManyToMany annotation.
Here, multiple instances of an entity can be related to multiple instances of another
entity. In this mapping, any side can be the owing side.
JPA – CRUD

• JPA in Java can be called Java Persistence API (JPA) which can
simplify the process of working with the database by providing object
relationship mapping structure CRUD operations (Create, Read,
Update, Delete) are actions especially if it contains database abuse.
JPA CRUD operation

• JPA is a Java specification for Object-Relational Mapping (ORM).


• It provides a standard way to move Java objects to a related database
table.
• CRUD operations are basic operations used to interact with data in a
database. In JPA, these operations are performed on entities that are
Java objects that represent data stored in the database.
Create Operation

• The Create operation involves inserting new records into the database.
In JPA, this is achieved by the persisting new entity instances.
• Steps to implement the create operation:
• Create a new instance of the entity class
• Set the values for its attributes.
• Use the EntityManagers persist() method to make entity managed and
persistent.
Example:
• EntityManager em = entityManagerFactory.createEntityManager();
• EntityTransaction transaction = em.getTransaction();
• transaction.begin();
• //create the instance of the entity
• Employee employee = new Employee();
• //set the attributes
• employee.setName("John");
• employee.setSalary(50000);
• em.persist(employee);
• transaction.commit();
Read Operation

• The read operation involves the retrieving the existing records from
the database. In JPA, this is the typically done using primary keys of
the entity.
• Steps to implement :
• Use the EntityManagers find() method to the retrieve the entity by its
primary key.
• Example:
• Employee employee = em.find(Employee.class, 1L);
Update Operation

• The update operation involves modifying the existing records in the database. In
JPA, this is the accomplished by the updating managed by the entity instances.
• Steps to implement:
• Retrieve the entity using Entitymanagers find() method or the query.
• Modify the arrtibutes of the entity.
• Use the EntityManagers merge() method to the update the entity in database.
• Example:
• Employee employee = em.find(Employee.class, 1L);
• employee.setSalary(55000);
• em.merge(employee);
Delete Operation

• The delete operation involves removing records from the database. In JPA, this
can be done by removing the managed entity instances.
• Steps to implement:
• Retrieve the entity using the EntityManagers find() method or the query.
• Use the EntityManagers remove() method to the delete entity from the database.
• Example:
• Employee employee = em.find(Employee.class, 1L);
• em.remove(employee);
What Is an ORM Tool?

• Designing and deploying information systems nowadays can be truly a


hard task.
• In most cases, we must know multiple programming languages and
frameworks.
• Every application layer has its own tech stack. And, while some
evolve very fast, others use decades-old technology.
• For instance, in most corporations’ old-school relational databases are
the data persistence standard still, and rightly so.
• Well, relational databases are solid, reliable, and fast enough for most commercial
applications. Hence, their use is quite widespread, and they have strong support communities.
• In this architecture, logical entities are listed in tables that hold each instance’s attributes on their
columns.
• Also, the tables can relate to others to model the logical relation between the entities. They also use
a standardized way to add, access, update and delete data, the Structured Query Language (SQL).
• An Object-Relational Mapping tool, ORM, is a framework that can help and simplify the
translation between the two paradigms: objects and relational database tables.
• It can use class definitions (models) to create, maintain and provide full access to objects’ data and
their database persistence.
Access Modifiers in Java

• Access modifiers help to restrict the scope of a class, constructor,


variable, method, or data member.
• It provides security, accessibility, etc to the user depending upon the
access modifier used with the element.
Types of Access Modifiers in Java

• There are four types of access modifiers available in Java:


1.Default – No keyword required
2.Private
3.Protected
4.Public
Types of Access Modifiers in Java
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.
Modifier Description

declarations are visible only within the package


Default
(package private)

Private declarations are visible within the class only

declarations are visible within the package or all


Protected
subclasses

Public declarations are visible everywhere


Access Modifiers Summarized in one figure
Understanding Java Access Modifiers

Difference Different
Same package Same package
Access Modifier Same class Package package non-
subclass non-subclass
subclass subclass

Default Yes Yes Yes No No

Private Yes No No No No

Protected Yes Yes Yes Yes No

Public Yes Yes Yes Yes Yes


What are 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.
class Animal {
public void method1() {...}
private void method2() {...}
}
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.
Default Access Modifier

• If we do not explicitly specify any access modifier for classes,


methods, variables, etc, then by default the default access modifier is
considered. For example,
Default Access Modifier
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
• Here, the Logger class has the default access modifier. And the class is
visible to all the classes that belong to the defaultPackage package.
However, if we try to use the Logger class in another class outside of
defaultPackage, we will get a compilation error.
Private Access Modifier

• When variables and methods are declared private, they cannot be


accessed outside of the class. For example,
class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


d.name = “VIT";
}
}
Protected Access Modifier

• When methods and data members are declared protected, we can


access them within the same package as well as from subclasses. For
example,
class vit1 {
// protected method
protected void display() {
System.out.println(“VIT");
}
}
class vit extends college {
public static void main(String[] args) {
// create an object of vit class
VIT vit = new vit();
// access protected method
vit.display();
}
}

Output:

VIT
Public Access Modifier

• When methods, variables, classes, and so on are declared public, then


we can access them from anywhere.
• The public access modifier has no scope restriction. For example,
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java I am an animal.
public class Main { I have 4 legs.
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}
• JDBC program to insert information of a student (rollno, name, marks,
grade) and display the inserted information
//program to get student details
import java.util.Scanner;
public class GetStudentDetails{
public static void main(String args[]) {
String name;
int roll, math, phy, eng;
Scanner SC=new Scanner(System.in);
System.out.print("Enter Name: ");
name=SC.nextLine();
System.out.print("Enter Roll Number: ");
roll=SC.nextInt();
System.out.print("Enter marks in Maths, Physics and English: ");
math=SC.nextInt();
phy=SC.nextInt();
eng=SC.nextInt();
int total=math+eng+phy;
float perc=(float)total/300*100;
System.out.println("Roll Number:" + roll +"\tName: "+name);
System.out.println("Marks (Maths, Physics, English): " +math+","+phy+","+eng);
System.out.println("Total: "+total +"\tPercentage: "+perc);
}
}
• Enter Name: Mike
• Enter Roll Number: 101
• Enter marks in Maths, Physics and English: 88 77 99
• Roll Number:101
• Name: Mike
• Marks (Maths, Physics, English): 88,77,99
• Total: 264
• Percentage: 88.0
import java.sql.*; // Using 'Connection', 'Statement' and 'ResultSet' classes in java.sql package

public class JdbcSelectTest { // Save as "JdbcSelectTest.java"


public static void main(String[] args) {
try (
// Step 1: Connect to the database via a 'Connection' object called 'conn'
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"myuser", "xxxx"); // For MySQL only
// The format is: "jdbc:mysql://hostname:port/databaseName", "username", "password"

// Step 2: Construct a 'Statement' object called 'stmt' inside the Connection created
Statement stmt = conn.createStatement();
){
// Step 3: Write a SQL query string. Execute the SQL query via the 'Statement'.
// The query result is returned in a 'ResultSet' object called 'rset'.
String strSelect = "select title, price, qty from books";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging

ResultSet rset = stmt.executeQuery(strSelect);


// Step 4: Process the 'ResultSet' by scrolling the cursor forward via next().
// For each row, retrieve the contents of the cells with getXxx(columnName).
System.out.println("The records selected are:");
int rowCount = 0;
// Row-cursor initially positioned before the first row of the 'ResultSet'.
// rset.next() inside the whole-loop repeatedly moves the cursor to the next row.
// It returns false if no more rows.
while(rset.next()) { // Repeatedly process each row
String title = rset.getString("title"); // retrieve a 'String'-cell in the row
double price = rset.getDouble("price"); // retrieve a 'double'-cell in the row
int qty = rset.getInt("qty"); // retrieve a 'int'-cell in the row
System.out.println(title + ", " + price + ", " + qty);
++rowCount;
}
System.out.println("Total number of records = " + rowCount);

} catch(SQLException ex) {
ex.printStackTrace();
} // Step 5: Close conn and stmt - Done automatically by try-with-resources (JDK 7)
}
}
Synchronization in Java

• Java Synchronization is used to make sure by some synchronization


method that only one thread can access the resource at a given point in
time.
Java Synchronized Blocks

• Java provides a way of creating threads and synchronizing their tasks


using synchronized blocks.
• A synchronized block in Java is synchronized on some object.
• All synchronized blocks synchronize on the same object and can only
have one thread executed inside them at a time.
• All other threads attempting to enter the synchronized block are
blocked until the thread inside the synchronized block exits the block.
General Form of Synchronized Block

• // Only one thread can execute at a time.


• // sync_object is a reference to an object
• // whose lock associates with the monitor.
• // The code is said to be synchronized on
• // the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
Types of Synchronization

• There are two synchronizations in Java mentioned below:


1.Process Synchronization
2.Thread Synchronization
1. Process Synchronization in Java
Process Synchronization is a technique used to coordinate the execution of multiple processes. It ensures that the
shared resources are safe and in order.
2. Thread Synchronization in Java
Thread Synchronization is used to coordinate and ordering of the execution of the threads in a multi-threaded program.
There are two types of thread synchronization are mentioned below:
•Mutual Exclusive
•Cooperation (Inter-thread communication in Java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. There are three types of
Mutual Exclusive mentioned below:
•Synchronized method.
•Synchronized block.
•Static synchronization.
// Class for send a message using Threads
Example of Synchronization class ThreadedSend extends Thread {
private String msg;
// A Java program to demonstrate working of
Sender sender;
// synchronized.
// Receives a message object and a string
import java.io.*;
// message to be sent
import java.util.*;
ThreadedSend(String m, Sender obj)
{
// A Class used to send a message
msg = m;
class Sender {
sender = obj;
public void send(String msg)
}
{
System.out.println("Sending\t" + msg);
public void run()
try {
{
Thread.sleep(1000);
// Only one thread can send a message
}
// at a time.
catch (Exception e) {
synchronized (sender)
System.out.println("Thread interrupted.");
{
}
// synchronizing the send object
System.out.println("\n" + msg + "Sent");
sender.send(msg);
}
}
}
}
}
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
Output
// Start two threads of ThreadedSend type
Sending Hi
S1.start();
S2.start();
Hi Sent
Sending Bye
// wait for threads to end
try {
Bye Sent
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}

You might also like