Java Day Wise
Java Day Wise
Agenda
Introduction
Installation and Directory Structure
OOP Concepts
Hello world Program
Execution Flow
main() variations
Console input and output
Language Fundamentals
Java History
In 1991, group of sun engineers led by James Gosling and Patrick Naughton decided to design a
language that could run on small devices like remote controls, cable tv boxes.
Since these devices have very small power and memory the language needs to be small.
Also differnt manufactures can choose different CPU's the language cannot be bound to single
architecture
this project was named as green.
these engineers came from UNIX background, so they used c++ as their base.
James decided to call this language as OAK, however the language with this name was already
existing, Hence it was later renamed by James to Java.
In 1992 they delivered their first product called as "*7"(a smart remote control)
Unfortunately Sun Miccrosystem was not intrested in producing this, also nor the consumer
electronic companies were intrested in it.
The team then deciced to market their technology in some other way where they worked for next 1
and half year on it.
Meanwhile world wide web (www) was growing bigger.
the key to it was browser transalating hyper text pages to the screen.
the java developers developed a browser called as HotJava browser which was based on client server
architeture and was working in real time.
the developers made the browser capable of executing java code inside the web pages called as
Applets.
Java Versions
JDK Beta - 1995
JDK 1.0 - January 23, 1996
JDK 1.1 - February 19, 1997
J2SE 1.2 - December 8, 1998
Java collections
J2SE 1.3 - May 8, 2000
J2SE 1.4 - February 6, 2002
J2SE 5.0 - September 30, 2004
enum
Generics
Annotations
Prepared By : Rohan Paramane 1/7
Day01_Help.MD Sunbeam Infotech 2024-04-01
Java Platforms
Java is not specific to any processor or operating system as it is implemented for wide variety of
hardware and operating system
1. Java Card
used to run java based applications on small devices with small memory devices like smart
cards
2. Java ME(Micro Edition)
used to develop applications for small devices with less memory, display and power capacities
like mobiles, printers
3. Java SE(Standard Edition)
It is widely used for development of portable code for desktop environment
4. Java EE(Enterprise Edition)
It is widely used in development of enterprise applications/softwares.
-also used for web application development
Java Installation
Windows and Mac:
Download .msi/.dmg file and follow installation steps.
https://adoptium.net/temurin/releases/?version=11
Ubuntu:
openjdk-11.0.22
|- bin: Contains executable binaries like java, javac, etc.
|- jmods: Contains JMOD (Java Modular Archive) files for Java modules
similar to JAR (Java Archive) (available from Java 9 onwards) .
|- lib: Contains libraries and other resources.
|- man: Contains manual pages (man pages) for Java commands.
|- src.zip: Contains Java source code for the JDK (not always included in
all distributions).
https://spring.io/tools
Object Oriented
basic principles of OOP are
1. class
2. object
class
It is a logical entity
It is a user defined datatype (same as struct in c)
It consists of field(data members) and methods(member functions)
Methods
static methods -> Accessed using classname directly
non static methods-> Accessed using object of the class
It is also called as blueprint of object/instance
Object
It is a physical entity
It is an instance of a class
one class can have multiple objects
Object is created in java using new operator
HelloWorld
class Program{
public static void main(String args[]){
System.out.println("Hello World");
}
}
main()
System.out.println()
javac Program.java
java Program
//For Windows
set CLASSPATH=..\bin
// For Linux
export CLASSPATH=../bin
java Rectangle
CLASSPATH
It is a JAVA environment variable which holds all directories seprated by ;(Windows) :(Linux)
It informs java compiler, application launcher, JVM, and other java tools about the directories in
which classes/packages are kept(location of the class files)
To display CLASSPATH variable
Windows cmd> set CLASSPATH
Linux terminal> echo $CLASSPATH
Bytecode
Bytecode is an intermediate representation of a program that is generated by a compiler and
typically executed by a virtual machine.
In the context of Java programming, bytecode refers specifically to the binary format that Java
source code is compiled into.
It enables platform independence, portability, security, and potential performance optimizations in
Java programming.
It forms a crucial part of the Java platform's architecture, allowing Java programs to run on a wide
range of devices and operating systems.
.class File
A .class file in Java contains the bytecode instructions that are executed by the Java Virtual Machine
(JVM).
When you compile Java source code using a Java compiler like javac, it translates the source code
into bytecode, which is then stored in a .class file.
Here's what a .class file typically consists of:
The file starts with a magic number 0xCAFEBABE to identify it as a valid Java class file.
This is followed by version information indicating the version of the Java bytecode format
used.
2. Constant Pool:
The constant pool is a table of structures that contains various types of constants used by the
class file, such as strings, numeric literals, class and interface names, method and field
references, and more.
It's a crucial part of the class file and provides the foundation for the bytecode instructions.
3. Access Flags:
Access flags specify the access level of the class or interface, such as whether it's public,
private, final, abstract, etc.
The .class file contains information about the class itself (its name, superclass, and interfaces it
implements).
5. Fields:
Information about the fields (variables) declared in the class, including their names, types, and
access modifiers.
6. Methods:
Information about the methods (functions) declared in the class, including their names, return
types, parameter types, and access modifiers.
7. Attributes:
Attributes provide additional metadata about various elements in the class file. For example,
they may include debugging information, annotations, runtime-visible annotations, source file
names, etc.
8. Code:
For methods that contain executable code, such as constructors or regular methods, there's a
Code attribute that contains the bytecode instructions to be executed by the JVM.
9. Exception Table:
If a method contains exception handling code (try-catch blocks), this section contains
information about how exceptions are handled.
Public class
As per Java Langauage Specification
1. Name of public class and name of java file should be same.
2. A single .java file can have only 1 public class.
3. A single .java file can have multiple non public classes.
main() Variations
In STS .class files are placed under bin directory after auto compilation
one java project can have multiple .java files.
each java file can have its own main method which can be executed seperately
the main() must be public static void main otherwise we get an error.
the entry point method must be be main(String args[]) otherwise error main not found
The main() method can be overloaded i.e. method with same name but different parameters (in
same class).
If a .java file contains multiple classes, for each class a separate .class file is created
Name of (non-public) Java class may be different than the file name.
The name of generated .class file is same as class name.
Agenda
Console input and output
Language Fundamentals
Class Object and Reference
Widening and Narrowing
Wrapper classes
Boxing & UnBoxing
Command Line Arguments
Language Fundamentals
Naming conventions
Names for variables, methods, and types should follow Java naming convention.
For example:
class EmployeeManagement{
}
Constat Fields
package names
comments
keywords
Keywords are the words whose meaning is already known to Java compiler.
These words are reserved i.e. cannot be used to declare variable, function or class.
Java 8 Keywords
DataTypes
It defines 3 things
1. Nature (type of data stored)
2. Memory (Memory required to store the data)
3. Operations (what operations we can perform)
Java is Strictly type checked language
In java, data types are classified as:
Data types
|- Primitive types (Value types)
| |- Boolean: boolean
| |- Character: char
| |- Integral: byte, short, int, long
| |- Floating-point: float, double
|
|- Non-Primitive types (Reference types)
|- class
|- interface
|- enum
|- Array
Literals
Six types of Literals: literal is a fixed value that is directly embedded into code.
Integral Literals
Floating-point Literals
Char Literals
String Literals
Boolean Literals
null Literal
Integral Literals
Floating-Point Literals
float x = 123.456f;
float y = 1.23456e+2; // 1.23456 x 10^2 = 123.456
double z = 3.142857d;
Char Literals
String Literals
String s1 = "Sunbeam";
Boolean Literals
Boolean literals allow only two values i.e. true and false. Not compatible with 1 and 0.
For example:
boolean b = true;
boolean d = false;
Null Literal
String s = null;
Object o = null;
Variable
A variable is a container which holds a value.
It represents a memory location.
A variable is declared with data type and initialized with another variable or literal.
In Java, variable can be
Local: Within a method -- Created on stack.
Java Method
A method is a block of code (definition). Executes when it is called (method call).
Method may take inputs known as parameters.
Method may yield a output known as return value.
Method is a logical set of instructions and can be called multiple times (reusability).
Functions in C/CPP are called as Method in java.
Logical entity
blueprint of an object
consists of fields and methods
it is a reference type in java
Object
physical enity
1. state
2. Behaviour
3. identity
Reference
Points to remember
Operators
Java divides the operators into the following catgories:
Arithmetic operators: +, -, *, /, %
Assignment operators: =, +=, -=, etc.
Comparison operators: ==, !=, <, >, <=, >=, instanceof
Logical operators: &&, ||, !
Combine the conditions (boolean - true/false)
Bitwise operators: &, |, ^, ~, <<, >>, >>>
Misc operators: ternary ?:, dot .
Dot operator: ClassName.member, objName.member.
converting state of primitive value of wider type into narrow type is called as Narrowing
Rules of conversion
source and destination must be compatible i.e. destination data type must be able to store
larger/equal magnitude of values than that of source data type.
Rule 1: Arithmetic operation involving byte, short automatically promoted to int.
Rule 2: Arithmetic operation involving int and long promoted to long.
Rule 3: Arithmetic operation involving float and long promoted to float.
Rule 4: Arithmetic operation involving double and any other type promoted to double.
Wrapper classes
In Java primitive types are not classes. So their variables are not objects.
Java has wrapper class corresponding to each primitive type. Their variables are objects.
All wrapper classes are final classes i.e we cannot extend it.
All wrapper classes are declared in java.lang package.
Object
|- Boolean
|- Character
|- Number
|- Byte
|- Short
|- Integer
|- Long
|- Float
|- Double
2. Convert types
4. Helper/utility methods
5. Java collections only store object types and not primitive types
Labwork
1. Scanner and (Console-> Option )demo
2. class, Object, reference
3. Data types (size, max,min)
4. widening and narrowing
5. Wrapper classes
Agenda
Packages
Access Modifiers
this reference
Types of Methods
Constructor Chaning
Array
Packages
Packages makes Java code modular. It does better organization of the code.
Package is a container that is used to group logically related classes, interfaces, enums, and other
packages.
To define a type inside package, it is mandatory write package declaration statement inside .java file.
Types inside package called as packaged types; while others (in default package) are unpackaged
types.
It is standard practice to have multi-level packages (instead of single level). Typically package name is
module name, dept/project name, website name in reverse order.
package com.sunbeaminfo.kdac
export CLASSPATH=../bin
java p1.Program
// if without setting classpath we want to execute the java code use below
command
java -cp ../bin p1.Program
java p1.Program
If the class is not kept public, the class won't be able to be accessed in other packages
Access Modifiers
For class
1. default
2. public
1. private
only within the class directly
2. default (package level private)
in same class directly
in all the classes in the same package on class object
3. protected
in same class directly
in all the classes in the same package on class object
in subclasses directly
4. public
are visible every where.
Default access restricts visibility to only classes within the same package. This allows you to
encapsulate implementation details that are not intended to be accessed by classes outside the
package.
Protected access, on the other hand, allows access by subclasses (regardless of package) and by
other classes within the same package.
If you want to hide implementation details from all classes, including subclasses, default access
provides stricter encapsulation.
this Reference
"this" is implicit reference variable that is available in every non-static method of class which is used
to store reference of current/calling instance
Whenever any non-static method is called on any object, that object is internally passed to the
method and internally collected in implicit "this"
"this" is constant within method i.e. it cannot be assigned to another object or null within the
method.
Using "this" inside method (to access members) is optional.
However, it is good practice for readability.
In a few cases using "this" is necessary.
Types of Methods
1. constructor
2. setters
3. getters
4. facilitators
Constructor
It is a special method of the class
In Java fields have default values if unitialized
Primitive types default value is usually zero
Reference type default value is null
Constructor should initialize fields to the desired values.
Types of Constructor
1. Default/Parameterless Ctor
2. Parameterized Ctor
Constructor Chaning
Constructor chaining is executing a constructor of the class from another constructor (of the same
class).
Constructor chaining (if done) must be on the very first line of the constructor.
Lab Work
1. Do the classwork of packages using STS. If comfortable then only go for command line
2. Check for the visibilty if accesss modifiers
3. class, object (Ctor, Setters, getters, facilitators)
4. Constructor chaning
5. Solve the assignment given
6. Revise the concept od Array from cpp
(1D Array of Pointers, Dynamic array)
Agenda
Array
Variable Arity/Argument Method
Method Overloading
Method Arguments
pass by value and reference
Object/Field Initializer
final
Array
Array is collection of similar data elements. Each element is accessible using indexes
It is a reference type in java
its object is created using new operator (on heap).
The array of primitive type holds values (0 if uninitialized) and array of non-primitive type holds
references (null if uninitialized).
In Java, checking array bounds is responsibility of JVM. When invalid index is accessed,
ArrayIndexOutOfBoundsException is thrown.
Array types are
1. 1-D array
2. 2-D/Multi-dimensional array
3. Ragged array
In 2D array if the second dimension of array is having differnt length then such array is
called as Ragged Array
Method Overloading
Defining methods with same name but differnt arguments(signature) is called as method
overloading
type
Order
Labwork
Array diagram and working
For Demo02 you have to write an accept method in Student class.
inside for loop you also have to cretae the object first and then call the accept() on those objects
Solve assignemnt
Agenda
Arrays class
pass by value and reference
Object/Field Initializer
final
static
Singleton Design Pattern
Hirerachy
Arrays
it is a class is java.util package
cosists of helper methods for working on Array.
eg
search
sort
equals
toString
The array must be sorted (as by the sort() method) prior to making the search call.
If it is not sorted, the results are undefined.
Method Arguments
In Java, primitive values are passed by value and objects are passed by reference.
Pass by reference stores address of the object. Changes done in called method are available in calling
method.
Pass by value -- Creates copy of the variable. Changes done in called method are not available in
calling method.
Pass by reference for value/primitive types can be simulated using array.
Object/Field Initializer
In C++/Java Fields of the class are initialized using constructor
In java, field can also be initialized using
1. field initializer
2. object initializer
3. Constructor
final
In Java, const is reserved word, but not used.
variables
fields
methods
class
if variables and fields are made final, they cannot be modified after initialization.
final fields of the class must be initialized using any of the following below
field initializer
object initializer
constructor
final methods cannot be overriden, final class cannot be extended(we will see at the time of
inheritance)
static Keyword
In OOP, static means "shared" i.e. static members belong to the class (not object) and shared by all
objects of the class.
Static members are called as "class members"; whereas non-static members are called as "instance
memebers".
In Java, static keyword is used for
1. static fields
2. static methods
3. static block
4. static import
Note that, static local variables cannot be created in Java.
1. static Fields
2. Static methods
These Methods can be called from outside the class (if not private) using class name or object name.
However, accessing via object name is misleading (avoid it).
When we need to call a method without creating object, then make such methods as static.
Since static methods are designed to be called on class name, they do not have "this" reference.
Hence, they cannot access non-static members in the static method (directly), However, we can
access them on an object reference if created inside them.
eg:
Integer.valueOf(10);
Factory Methods -> to cretae object of the class
Like Object/Instance initializer block, a class can have any number of static initialization blocks, and
they can appear anywhere in the class body.
Static initialization blocks are executed in the order their declaration in the class.
A static block is executed only once when a class is loaded in JVM.
static import
To access static members of a class in the same class, the "ClassName." is optional.
To access static members of another class, the "ClassName." is mandetory.
If need to access static members of other class frequently, use "import static" so that we can access
static members of other class direcly (without ClassName.).
Agenda
Association
Inheritance
super keyword
Types of inheritance
Method Overriding
Final Method & Class
Upcasting & Downcasting
Object class
Methods of object class
toString()
equals() & hashCode()
Association
If "has-a" relationship exist between the types, then use association.
To implement association, we should declare instance/collection of inner class as a field inside
another class.
There are two types of associations
1. Composition
2. Aggregation
Composition
Represents part-of relation i.e. tight coupling between the objects.
The inner object is essential part of outer object.
Heart is part of Human.
Engine is part of Car.
Wall is part of Room.
joining date is a part of employee
Aggegration
Represents has-a relation i.e. loose coupling between the objects.
The inner object can be added, removed, or replaced easily in outer object.
Car has a Driver.
Company has Employees.
Room has a window
Employee has a vehicle
Inheritance
If "is-a"/"kind-of" relationship exist between the types, then use inheritance.
Inheritance is process of generalization to specialization.
All members of parent class are inherited to the child class.
Parent class is also called as super class and child class is also called as sub-class.
Example:
Manager is a Employee
Mango is a Fruit
Rectangle is a Shape
In Java, inheritance is done using extends keyword.
Java doesn't support multiple implementation inheritance i.e. a class cannot be inherited from
multiple super-classes.
However Java does support multiple interface inheritance i.e. a class can be inherited from multiple
super interfaces.
Super Keyword
In sub-class, super-class members are referred using "super" keyword.
used for calling super class constructor
By default, when sub-class object is created, first super-class constructor (param-less) is executed
and then sub-class constructor is executed.
"super" keyword is used to explicitly call super-class constructor.
Super class members (non-private) are accessible in sub-class directly or using "this" reference. These
members can also be accessed using "super" keyword.
However, if sub-class method signature is same as super-class signature, it hides/shadows method of
the super class i.e. super-class method is not directly visible in sub-class.
The "super" keyword is mandetory for accessing such hidden members of the super-class.
Types of Inheritance
1. Single
class A {
}
class B extends A{
2. Multiple
class A {
}
class B {
}
class C extends A,B{ // Not Allowed
interface A{
}
interface B{
}
interface C extends A,B{ // Allowed
3. Hirerachical
class A {
}
class B extends A{
}
class C extends A{
4. Multilevel
class A {
}
class B extends A{
}
class C extends B{
Method Overriding
Redefining a super-class method in sub-class with exactly same signature is called as "Method
overriding".
2. Super-class has provided partial method implementation and sub-class needs additional
code. Here sub-class implementation may call super-class method (using super keyword).
3. Sub-class needs different implementation than that of super-class method
implementation.
If these rules are not followed, compiler raises error or compiler treats sub-class method as a new
method.
Java 5.0 added @Override annotation (on sub-class method) informs compiler that programmer is
intending to override the method from the super-class.
@Override checks if sub-class method is compatible with corresponding super-class method or not
(as per rules). If not compatible, it raise compile time error.
Note that, @Override is not compulsory to override the method. But it is good practice as it improves
readability and reduces human errors.
final Method
If implementation of a super-class method is logically complete, then the method should be declared
as final.
Such final methods cannot be overridden in sub-class. Compiler raise error, if overridden.
But final methods are inherited into sub-class i.e. The super-class final methods can be invoked in
sub-class object (if accessible).
final Class
If implementation of a super-class is logically complete, then the class should be declared as final.
The final class cannot be extended into a sub-class. Compiler raise error, if inherited.
Effectively all methods in final class are final methods.
Examples of final classes
java.lang.Integer (and all wrapper classes)
java.lang.String
java.lang.System
Agenda
upcasting
downcasting
instanceof
Object class
toString
equals
abstract method
abstract class
interface
marker interface
Upcasting
Assigning sub-class reference to a super-class reference.
Sub-class "is a" Super-class, so no explicit casting is required.
Using such super-class reference, only super-class methods inherited into sub-class can be called. This
is "Object slicing".
Using such super-class reference, super-class methods overridden into sub-class can also be called.
Downcasting
Assigning super-class reference to sub-class reference.
Every super-class is not necessarily a sub-class, so explicit casting is required.
Polymorphism
poly = Many , morphism = Forms
It has two types
1. compile time
implemented using method overloading
Compiler can identify which method to be called at compile time depending on types of
arguments. This is also referred as "Early binding".
2. Runtime - implemented using method overriding - The method to be called is decided at
runtime depending on type of object. This is also referred as "Late binding" or "Dyanmic
method dispatch".
instanceof operator
Java's instanceof operator checks if given reference points to the object of given type (or its sub-
class) or not. Its result is boolean.
Typically "instanceof" operator is used for type-checking before down-casting.
Object class
Non final and non-abstract class declared in java.lang package.
In java, all the classes (not interfaces) are directly or indirectly extended from Object class.
Object class is not inherited from any class or implement any interface.
public Object();
public native int hashCode();
public boolean equals(Object);
protected native Object clone() throws CloneNotSupportedException;
public String toString();
protected void finalize() throws Throwable;
public final native Class<?> getClass();
public final native void notify();
public final native void notifyAll();
public final void wait() throws InterruptedException;
public final native void wait(long) throws InterruptedException;
public final void wait(long, int) throws InterruptedException;
toString() method
it is a non final method of object class
To return state of Java instance in String form, programmer should override toString() method.
The result in toString() method should be a concise, informative, and human-readable.
It is recommended that all subclasses override this method.
equals() method
Prepared By : Rohan Paramane 2/3
Day07_Help.MD Sunbeam Infotech 2024-04-08
Labwork
Do the implemenation of Shape class example in c++
Agenda
Abstract class/method
Interfaces
Marker interfaces
Date/ LocalDate/ Calender
Abstract Methods
If implementation of a method in super-class is not possible/incomplete, then method is declared as
abstract.
Abstract method does not have definition/implementation.
If class contains one or more abstract methods, then class must be declared as abstract. Otherwise
compiler raise an error.
The super-class abstract methods must be overridden in sub-class; otherwise sub-class should also be
marked abstract.
The abstract methods are forced to be implemented in sub-class. It ensures that sub-class will have
corresponding functionality.
The abstract method cannot be private, final, or static.
Example: abstract methods declared in Number class are:
abstract int intValue();
abstract float floatValue();
Abstract class
If implementation of a class is logically incomplete, then the class should be declared abstract.
If class contains one or more abstract methods, then class must be declared as abstract.
An abstract class can have zero or more abstract methods.
Abstract class object cannot be created; however its reference can be created.
Abstract class can have fields, methods, and constructor.
Its constructor is called when sub-class object is created and initializes its (abstract class) fields.
Example:
java.lang.Number
java.lang.Enum
Interfaces contains only method declarations. All methods in an interface are by default abstract and
public.
They define a "contract" that is must be followed/implemented by each sub-class.
Interfaces enables loose coupling between the classes i.e. a class need not to be tied up with another
class implementation.
Interfaces cannot be instantiated, they can only be implemented by classes or extended by other
interfaces.
Java 7 interface can only contain public abstract methods and static final fields (constants).
They cannot have non-static fields, non-static methods, and constructors.
Examples:
java.io.Closeable / java.io.AutoCloseable
java.lang.Runnable
Multiple interface inheritance is allowed in Java
interface Displayable {
void display();
}
interface Acceptable {
void accept();
}
class Employee implements Displayable,Acceptable{}
If two interfaces have same method, then it is implemented only once in sub-class.
abstract class
interface
Used as contract/specification -- Inherited into sub-class and must override all methods
Can invoke overridden methods in sub-class using super-class reference -- runtime
polymorphism
Marker interfaces
Interface that doesn't contain any method declaration is called as "Marker interface".
These interfaces are used to mark or tag certain functionalities/features in implemented class.
In other words, they associate some information (metadata) with the class.
Marker interfaces are used to check if a feature is enabled/allowed for the class.
Java has a few pre-defined marker interfaces. e.g. Serializable, Cloneable, etc.
java.io.Serializable -- Allows JVM to convert object state into sequence of bytes.
java.lang.Cloneable -- Allows JVM to create copy of the class object.
// java.util.Date
Date d = new Date();
System.out.println("Timestamp: " + d.getTime());
// number of milliseconds since 1-1-1970 00:00.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println("Date: " + sdf.format(d));
// java.util.Date
String str = "28-09-1983";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(str);
System.out.println(d.toString());
// java.util.Calendar
Calendar c = Calendar.getInstance();
System.out.println(c.toString());
System.out.println("Current Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Month: " + calendar.get(Calendar.MONTH));
System.out.println("Current Date: " + calendar.get(Calendar.DATE));
Thread safety
API design and ease of understanding
ZonedDate and Time
Most commonly used java 8 onwards new classes are LocalDate, LocalTime and LocalDateTime.
LocalDate
LocalTime
LocalDateTime
Lab Work
Read the given assignment keep questions ready.
Solve the assignment
practice the exception handling and custom exception from CPP
Agenda
Exception Handling
Exceptions
Errors
Exception Chaning
Custom Exceptions
Exception Handling
Exceptions represents runtime problems
If not handled in the current method it is sent back to the calling method.
try
catch
throw
throws
finally
Exceptions need to handled otherwise the it terminates the program by throwing that exception.
we use try catch block to handle the exception. Inside try block keep all the method calls that
generate exception and handle the exception inside catch block
When exception is raised, it will be caught by nearest matching catch block. If no matching catch
block is found, the exception will be caught by JVM and it will abort the program.
when exceptions are generated if we dont to handle it program terminates,however the resources
that are in used should be closed.
the resources can be closed in finally block that can be used with a try block.
if the classes have implemented AutoCloseable interface we can also use try with resource with the
try block.
1. a catch block
2. a finally block
3. try with resource
1. Error
2. Exception
Prepared By : Rohan Paramane 1/3
Day09_Help.MD Sunbeam Infotech 2024-04-10
Errors
Errors are generated due to runtime environment.
It can be due to problems in RAM/JVM for memory management or like crashing of harddisk, etc.
We cannot recover from such errors in our program and hence such errors should not be handled.
we can write a try catch block to handle such errors but it is recommended not to handle such errors.
Exceptions
Exception class and all its sub classes except Runtime exception class are all Checked Exception
Runtime Exception and all its sub classes all unchecked exceptions
Checked exceptions are mandatory to handle.
4. "throw" statement
Throws an exception/error i.e. any object that is inherited from Throwable class.
Can throw only one exception at time.
All next statements are skipped and control jumps to matching catch block.
5. throws
Written after method declaration to specify list of exception not handled by called method
and to be handled by calling method.
Writing unhandled checked exceptions in throws clause is compulsory.
Sub-class overridden method can throw same or subset of exception from super-class method.
Exception chaining
Sometimes an exception is generated due to another exception.
For example, database SQLException may be caused due to network problem SocketException.
To represent this an exception can be chained/nested into another exception.
If method's throws clause doesn't allow throwing exception of certain type, it can be nested into
another (allowed) type and thrown.
Lab work
1. Revise the classwork of Exception Handling
2. Practice the Abstratct and interface if any pending
3. solve the assignment
4. Rapid fire round
Agenda
String
StringBuffer
StringBuilder
Enum
clone()
Garbage Collector
JVM Architecture
Java BuzzWords
Strings
java.lang.Character is wrapper class that represents char.
In Java, each char is 2 bytes because it follows unicode encoding.
String is sequence of characters.
1. java.lang.String: "Immutable" character sequence
2. java.lang.StringBuffer: Mutable character sequence (Thread-safe)
3. java.lang.StringBuilder: Mutable character sequence (Not Thread-safe)
String helpers
1. java.util.StringTokenizer: Helper class to split strings
Since strings are immutable, string constants are not allocated multiple times.
String constants/literals are stored in string pool. Multiple references may refer the same object in
the pool.
String pool is also called as String literal pool or String constant pool.
String Tokenizer
Used to break a string into multiple tokens - like split() method.
Methods of java.util.StringTokenizer
boolean hasMoreTokens()
String nextToken()
String nextToken(String delim)
Enum
In C enums were internally integers
In java, It is a keyword added in java 5 and enums are object in java.
used to make constants for code readability
mostly used for switch cases
In java, enums cannot be declared locally (within a method).
The declared enum is converted into enum class.
The enum type declared is implicitly inherited from java.lang.Enum class. So it cannot be extended
from another class, but enum may implement interfaces.
The enum constants declared in enum are public static final fields of generated class.
Enum objects cannot be created explicitly (as generated constructor is private).
The enums constants can be used in switch-case and can also be compared using == operator.
The enum may have fields and methods.
// user-defined enum
enum ArithmeticOperations {
ADDITION, SUBTRACTION, MULIPLICATION, DIVISION
}
static {
ADDITION = new ArithmeticOperations("ADDITION", 0);
SUBTRACTION = new ArithmeticOperations("SUBTRACTION", 1);
MULIPLICATION = new ArithmeticOperations("MULIPLICATION", 2);
DIVISION = new ArithmeticOperations("DIVISION", 3);
$VALUES = (new ArithmeticOperations[] {
ADDITION, SUBTRACTION, MULIPLICATION, DIVISION
});
}
}
Clone method
The clone() method is used to create a copy of an object in Java. - It's defined in the java.lang.Object
class and is inherited by all classes in Java.
It returns a shallow copy of the object on which it's called.
This means that it creates a new object with the same field values as the original object, but the
fields themselves are not cloned.
If the fields are reference types, the new object will refer to the same objects as the original object.
In order to use the clone() method, the class of the object being cloned must implement the
Cloneable interface.
This interface acts as a marker interface, indicating to the JVM that the class supports cloning.
It's recommended to override the clone() method in the class being cloned to provide proper cloning
behavior.
The overridden method should call super.clone() to create the initial shallow copy, and then perform
any necessary deep copying if required.
The clone() method throws a CloneNotSupportedException if the class being cloned does not
implement Cloneable, or if it's overridden to throw the exception explicitly.
Agenda
Generics
Generic class
Generic method
Generic Limitations
Generic Interfaces
Introduction to Comparable
Comparator
Generic Programming
Code is said to be generic if same code can be used for various (practically all) types.
Best example:
Data structure e.g. Stack, Queue, Linked List, ...
Algorithms e.g. Sorting, Searching, ...
Two ways to do Generic Programming in Java
1. using java.lang.Object class -- Non typesafe
2. using Generics -- Typesafe
class Box {
private Object obj;
public void set(Object obj) {
this.obj = obj;
}
public Object get() {
return this.obj;
}
}
Generic classes
Implementing a generic class
class Box<TYPE> {
private TYPE obj;
s
public void set(TYPE obj) {
this.obj = obj;
}
public TYPE get() {
return this.obj;
}
}
public T getObj() {
return obj;
}
The Box<> can now be used only for the classes inherited from the Number class.
class Box<T> {
private T obj;
public T get() {
return this.obj;
}
Here the upper bound is set (to Number) that means all the classes that inherits Number are allowed
Here the lower bound is set (to Integer) that means all the classes that are super classes of that
lower bound class are allowed.
Generic Methods
Generic methods are used to implement generic algorithms.
Example
// Not Type-safe
// public static void printArray(Object[] arr) {
// for (Object element : arr) {
// System.out.println(element);
// }
// }
// Type-safe
public static <Type> void printArray(Type[] arr) {
for (Type element : arr) {
Prepared By : Rohan Paramane 5/7
Day11_Help.MD Sunbeam Infotech 2024-04-12
System.out.println(element);
}
}
Generics Limitations
1. Cannot instantiate generic types with primitive Types. Only reference types are allowed.
class Box<T> {
private T obj; // okay
private static T object; // compiler error
// ...
}
if(obj instanceof T) {
newobj = (T)obj;
}
7. Cannot overload a method just by changing generic type. Because after erasing/removing the type
param, if params of two methods are same, then it is not allowed.
Type erasure
The generic type information is erased (not maintained) at runtime (in JVM). Box and Box both are
internally (JVM level) treated as Box objects.
The field "T obj" in Box class, is treated as "Object obj".
Because of this method overloading with genric type difference is not allowed.
Agenda
Comparable
Comparator
Collection FrameWork
Traversal
FailSafe and FailFast Iterator
List
Generic Interfaces
Interface is standard/specification.
comparable is a predefined interface in java
interface Comparable {
int compareTo(Object obj);
}
class Program {
public static void main(String[] args) {
Person p1 = new Person("James Bond", 50);
Person p2 = new Person("Ironman", 45);
int diff = p1.compareTo(p2);
if(diff == 0)
System.out.println("Both are same");
else if(diff > 0)
System.out.println("p1 is greater than p2");
else //if(diff < 0)
System.out.println("p1 is less than p2");
diff = p2.compareTo("Superman"); // will fail at runtime with
ClassCastException (in down-casting)
}
}
class Program {
public static void main(String[] args) {
Person p1 = new Person("James Bond", 50);
Person p2 = new Person("Ironman", 45);
int diff = p1.compareTo(p2);
if(diff == 0)
System.out.println("Both are same");
else if(diff > 0)
System.out.println("p1 is greater than p2");
else //if(diff < 0)
System.out.println("p1 is less than p2");
diff = p2.compareTo("Superman"); // compiler error
}
}
Comparable<>
Standard for comparing the current object to the other object.
Has single abstract method int compareTo(T other);
In java.lang package.
Used by various methods like Arrays.sort(Object[]), ...
It does the comparision for the natural ordering
Comparator<>
Standard for comparing two (other) objects.
Has single abstract method int compare(T obj1, T obj2);
In java.util package.
Used by various methods like Arrays.sort(T[], comparator), ...
Collection Framework
Collection framework is Library of reusable data structure classes that is used to develop application.
Main purpose of collection framework is to manage data/objects in RAM efficiently.
Collection framework was introduced in Java 1.2 and type-safe implementation is provided in 5.0
(using generics).
Collection is available in java.util package.
Java collection framework provides
Collection Hierarchy
Interfaces: Iterable, Collection, List, Queue, Set, Map, Deque, SortedSet, SortedMap, ...
Implementations: ArrayList, LinkedList, HashSet, HashMap, ...
Algorithms: sort(), reverse(), max(), min(), ... -> in Collections class static methods
Collection interface
Root interface in collection framework interface hierarchy.
Most of collection classes are inherited from this interface (indirectly).
Provides most basic/general functionality for any collection
Abstract methods
boolean add(E e)
int size()
boolean isEmpty()
void clear()
boolean contains(Object o)
boolean remove(Object o)
boolean addAll(Collection<? extends E> c)
boolean containsAll(Collection<?> c)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
Object[] toArray()
Iterator iterator() -- inherited from Iterable
Default methods
default Stream stream()
default Stream parallelStream()
default boolean removeIf(Predicate<? super E> filter)
Iterable interface
To traverse any collection it provides an Iterator.
Enable use of for-each loop.
In java.lang package
Iterable yeilds an iterator
Methods
Iterator iterator()
default Spliterator spliterator()
default void forEach(Consumer<? super T> action)
Iterator
Part of collection framework (1.2)
Methods
boolean hasNext()
E next()
void remove()
Agenda
Traversal
FailSafe and FailFast Iterator
List
Queue
Java BuzzWords
Set
hashcode()
Map
boolean hasMoreElements()
E nextElement()ss (Demo02)
Methods
Collection vs Collections
1. Collection interface
2. Collections class
Collections.methodName(...);
If iterator allows to modify the underlying collection (add/remove operation other than iterator
methods) while traversing a collection (NO ConcurrentModificationException), then iterator is said to
be Fail-safe.
If any changes are done in the collection using these iterators then the changes may not be reflected
using the same iterator however by creating the new iterator we can get the changes displayed.
Traversal
1. Using Iterator
for(Integer i:list)
System.out.println(i);
// v is Vector<Integer>
Enumeration<Integer> e = v.elements();
while(e.hasMoreElements()) {
Integer i = e.nextElement();
System.out.println(i);
}
List Interface
Ordered/sequential collection.
Implementations: ArrayList, Vector, Stack, LinkedList, etc.
List can contain duplicate elements.
List can contain multiple null elements.
Elements can be accessed sequentially (bi-directional using Iterator) or randomly (index based).
List enables searching in the list
Abstract methods
void add(int index, E element)
String toString()
E get(int index)
E set(int index, E element)
int indexOf(Object o)
int lastIndexOf(Object o)
E remove(int index)
boolean addAll(int index, Collection<? extends E> c)
ListIterator listIterator()
ListIterator listIterator(int index)
List subList(int fromIndex, int toIndex)
To store objects of user-defined types in the list, you must override equals() method for the objects.
It is mandetory while searching operations like contains(), indexOf(), lastIndexOf().
Vector class
Prepared By : Rohan Paramane 3/7
Day13_Help.MD Sunbeam Infotech 2024-04-15
ArrayList class
Internally ArrayList is dynamic array (can grow or shrink dynamically).
When ArrayList capacity is full, it grows by half of its size.
Elements can be traversed using Iterator, ListIterator, or using index.
Primary use
Random access
Add/remove elements (at the end)
Limitations
Slower add/remove in between the collection
Uses more contiguous memory
Inherited from List<>.
LinkedList class
Internally LinkedList is doubly linked list.
Elements can be traversed using Iterator, ListIterator, or using index.
Primary use
Add/remove elements (anywhere)
Less contiguous memory available
Limitations:
Slower random access
Inherited from List<>, Deque<>.
Stack
It is inherited from vector class.
Generally used to have only the stack operations like push, pop and peek opertaions.
It is recommended to use the Dequeu from the queue collection.
It is synchronized and hence gives low performanance.
Queue Interface
Represents utility data structures (like Stack, Queue, ...) data structure.
Deque interface
Represents double ended queue data structure i.e. add/delete can be done from both the ends.
Two sets of methods
Throwing exception on failure: addFirst(), addLast(), removeFirst(), removeLast(), getFirst(),
getLast().
Returning special value on failure: offerFirst(), offerLast(), pollFirst(), pollLast(), peekFirst(),
peekLast().
Can used as Queue as well as Stack.
Methods
boolean offerFirst(E e)
E pollFirst()
E peekFirst()
boolean offerLast(E e)
E pollLast()
E peekLast()
ArrayDeque class
Internally ArrayDeque is dynamically growable array.
Elements are allocated contiguously in memory.
Time Complexity to add and remove is O(1)
LinkedList class
Internally LinkedList is doubly linked list.
Time Complexity to add and remove is O(1)
PriorityQueue class
Internally PriorityQueue is a "binary heap" (Array implementation of binary Tree) data structure.
Elements with highest priority is deleted first (NOT FIFO).
Elements should have natural ordering or need to provide comparator.
Java BuzzWords
Prepared By : Rohan Paramane 5/7
Day13_Help.MD Sunbeam Infotech 2024-04-15
1. Simple
Simple for Professional Programmers if aware about OOP.
It removed the complicated fetaures like pointers and rarely used features like operator
overloading from c++
It was simple till java 1.4
the new features added made it powerful (but also complex)
2. Object Oriented
Java is a object-oriented programming language.
It supports all the pillars of OOP
3. Distributed
Java is designed to create distributed applications on networks.
Java applications can access remote objects on the Internet as easily as they can do in the local
system.
Java enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
4. Compiled and Interpreted
Usually, a computer language is either compiled or Interpreted.
Java combines both this approach and makes it a two-stage system.
Compiled: Java enables the creation of cross-platform programs by compiling them into an
intermediate representation called Java Bytecode.
Interpreted: Bytecode is then interpreted, which generates machine code that can be directly
executed by the machine/CPU.
5. Robust
It provides many features that make the program execute reliably in a variety of environments.
Java is a strictly typed language. It checks code both at compile time and runtime.
Java takes care of all memory management problems with garbage collection.
6. Secure
Java achieves this protection by confining a Java program to the Java execution environment
and not allowing it to access other parts of the computer
7. Architecture Neutral
Java language and Java Virtual Machine helped in achieving the goal of WORA - Write Once
Run Anywhere.
Java byte code is interpreted by JIT and convert into CPU machine code/native code.
So Java byte code can execute on any CPU architecture (on which JVM is available)
8. Portable
As java is Architecture Neutral it is portable.
Java is portable because of the Java Virtual Machine (JVM).
9. High Performance
Java performance is high because of the use of bytecode.
The bytecode was used so that it can be efficiently translated into native machine code by JIT
compiler (in JVM).
10. Multithreaded
Multithreaded Programs handled multiple tasks simultaneously (within a process)
Java supports multi-process/thread communication and synchronization.
When Java application executes 2 threads are started
1. main thread
Agenda
Set
Map
File IO
Set interface
Collection of unique elements (NO duplicates allowed).
Implementations: HashSet, LinkedHashSet, TreeSet.
Elements can be accessed using an Iterator.
Abstract methods (same as Collection interface)
add() returns false if element is duplicate
HashSet class
Non-ordered set (elements stored in any order)
Elements must implement equals() and hashCode()
Fast execution
Elements are duplicated in Hashset even if equals() is overriden.
Its because the hashset dosent compare elements only on the basis of equals().
Hashset considers elements equal if and only if their hashcode() is same and calling equals() to
compare them return true.
LinkedHashSet class
Ordered set (preserves order of insertion)
Elements must implement equals() and hashCode()
Slower than HashSet
Elements are duplicated in LinkedHashset even if equals() is overriden.
Its because the LinkedHashset dosent compare elements only on the basis of equals().
LinkedHashset considers elements equal if and only if their hashcode() is same and calling equals() to
compare them return true.
SortedSet interface
Use natural ordering or Comparator to keep elements in sorted order
Methods
E first()
E last()
SortedSet headSet(E toElement)
SortedSet subSet(E fromElement, E toElement)
SortedSet tailSet(E fromElement)
NavigableSet interface
Sorted set with additional methods for navigation
Methods
Prepared By : Rohan Paramane 1/7
Day14_Help.MD Sunbeam Infotech 2024-04-16
E higher(E e)
E lower(E e)
E pollFirst()
E pollLast()
NavigableSet descendingSet()
Iterator descendingIterator()
TreeSet class
Sorted navigable set (stores elements in sorted order)
Elements must implement Comparable or provide Comparator
Slower than HashSet and LinkedHashSet
It is recommended to have consistent implementation for Comparable (Natural ordering) and
equals() method i.e. equality and comparison should done on same fields.
If need to sort on other fields, use Comparator.
Hashtable stores data in key-value pairs so that for the given key, value can be searched in fastest
possible time.
Internally hash-table is a table(array), in which each slot(index) has a bucket(collection).
Load factor = Number of entries / Number of buckets.
Multiple keys can compete for the same slot which can cause the collision
To avoid the collision two techniques are used
1. Open Adderessing
2. Seperate Chaining
In Seperate Chaning mechanism to avoid the collision Key-value entries are stored in the same bucket
depending on hash code of the "key".
In java we have readymade/ built-in hashtables
1. HashMap
2. LinkedHashMap
3. TreeMap
4. HashTable (Legacy)
5. Properties (Legacy)
Here we neeed to calculate the hash value of the key using hash function(Override hashcode
method).
Examples
Key=pincode, Value=city/area
Key=Employee, Value=Manager
Key=Department, Value=list of Employees
hashCode() method
Object class has hashCode() method, that returns a unique number for each object (by converting its
address into a number).
To use any hash-based data structure hashCode() and equals() method must be implemented.
If two distinct objects yield same hashCode(), it is referred as collision. More collisions reduce
performance.
Most common technique is to multiply field values with prime numbers to get uniform distribution
and lesser collsions.
hashCode() overriding rules
hash code should be calculated on the fields that decides equality of the object.
hashCode() should return same hash code each time unless object state is modified.
If two objects are equal (by equals()), then their hash code must be same.
If two objects are not equal (by equals()), then their hash code may be same (but reduce
performance).
Map interface
Collection of key-value entries (Duplicate "keys" not allowed).
Prepared By : Rohan Paramane 3/7
Day14_Help.MD Sunbeam Infotech 2024-04-16
* boolean isEmpty()
* int size()
* V put(K key, V value)
* V get(Object key)
* Set<K> keySet()
* Collection<V> values()
* Set<Map.Entry<K,V>> entrySet()
* boolean containsValue(Object value)
* boolean containsKey(Object key)
* V remove(Object key)
* void clear()
* void putAll(Map<? extends K,? extends V> map)
Maps not considered as true collection, because it is not inherited from Collection interface.
HashMap class
Non-ordered map (entries stored in any order -- as per hash code of key)
Keys must implement equals() and hashCode()
Fast execution
Mostly used Map implementation
LinkedHashMap class
Ordered map (preserves order of insertion)
Keys must implement equals() and hashCode()
Slower than HashSet
Since Java 1.4
TreeMap class
Sorted navigable map (stores entries in sorted order of key)
Keys must implement Comparable or provide Comparator
Slower than HashMap and LinkedHashMap
Internally based on Red-Black tree.
Doesn't allow null key (allows null value though).
Hashtable class
Similar to HashMap class.
Legacy collection class (since Java 1.0), modified for collection framework (Map interface).
Synchronized collection -- Thread safe but slower performance
Inherited from java.util.Dictionary abstract class (it is Obsolete).
Java IO framework
Input/Output functionality in Java is provided under package java.io and java.nio package.
IO framework is used for File IO, Network IO, Memory IO, and more.
Two types of APIs are available file handling
FileSystem API -- Accessing/Manipulating Metadata
File IO API -- Accessing/Manipulating Contents/Data
File
File is a collection of data and information on a storage device.
File = Data + Metadata
collection of data/info on storage disk
data = contents
metadata = Information
Java IO
Java File IO is done with Java IO streams.
Java IO Streams are completly different from java.util.Stream. No relation between them
Stream generally determines flow of data
Java supports two types of IO streams.
Byte streams (binary files) -- byte by byte read/write
Character streams (text files) -- char by char read/write
Stream is abstraction of data source/sink.
Data source -- InputStream(Byte Stream) or Reader(Char Stream)
Data sink -- OutputStream(Byte Stream) or Writer(Char Stream)
All these streams are AutoCloseable (so can be used with try-with-resource construct)
Chaining IO Streams
Primitive types IO
DataInputStream & DataOutputStream -- convert primitive types from/to bytes
primitive type --> DataOutputStream --> bytes --> FileOutputStream --> file.
DataOutput interface provides methods for conversion - writeInt(), writeUTF(),
writeDouble(), ...
primitive type <-- DataInputStream <-- bytes <-- FileInputStream <-- file.
DataInput interface provides methods for conversion - readInt(), readUTF(),
readDouble(), ...
DataOutput/DataInput interface
interface DataOutput
writeUTF(String s)
writeInt(int i)
writeDouble(double d)
writeShort(short s)
...
interface DataInput
String readUTF()
int readInt()
double readDouble()
short readShort()
...
Serialization
ObjectInputStream & ObjectOutputStream -- convert java object from/to bytes
Java object --> ObjectOutputStream --> bytes --> FileOutputStream --> file.
ObjectOutput interface provides method for conversion - writeObject().
Java object <-- ObjectInputStream <-- bytes <-- FileInputStream <-- file.
ObjectInput interface provides methods for conversion - readObject().
Converting state of object into a sequence of bytes is referred as Serialization. The sequence of
bytes includes object data as well as metadata.
Serialized data can be further saved into a file (using FileOutputStream) or sent over the network
(Marshalling process).
These bytes may be received from the file (using FileInputStream) or from the network
(Unmarshalling process).
ObjectOutput/ObjectInput interface
interface ObjectOutput extends DataOutput
writeObject(obj)
interface ObjectInput extends DataInput
obj = readObject()
Agenda
Java IO FrameWork
GC
JDBC
Buffered streams
Each write() operation on FileOutputStream will cause data to be written on disk (by OS). Accessing disk
frequently will reduce overall application performance. Similar performance problems may occur during
network data transfer.
BufferedOutputStream classes hold data into a in-memory buffer before transferring it to the
underlying stream. This will result in better performance.
Java object --> ObjectOutputStream --> BufferedOutputStream --> FileOutputStream --> file on
disk.
Data is sent to underlying stream when buffer is full or flush() called explicitly.
BufferedInputStream provides a buffering while reading the file.
The buffer size can be provided while creating the respective objects.
PrintStream class
Produce formatted output (in bytes) and send to underlying stream.
Formatted output is done using methods print(), println(), and printf().
System.out and System.err are objects of PrintStream class.
It is used only to write the formatted data in to the file.
Scanner class
Added in Java 5 to get the formatted input.
It is java.util package (not part of java io framework).
Character streams
Character streams are used to interact with text file.
Java char takes 2 bytes (unicode), however char stored in disk file may take 1 or more bytes depending
on char encoding.
https://www.w3.org/International/questions/qa-what-is-encoding
The character stream does conversion from java char to byte representation and vice-versa (as per char
encoding).
The abstract base classes for the character streams are the Reader and Writer class.
Garbage Collector
Garbage collection is automatic memory management by JVM.
If a Java object is unreachable (i.e. not accessible through any reference), then it is automatically
released by the garbage collector.
An object become eligible for GC in one of the following cases:
//4. Island of isolation i.e. objects are referencing each other, but not
referenced externally.
class Test {
Test tref;
}
t1.tref = t2;
t2.tref = t1;
t1 = null;
t2 = null;
}
}
GC is a background thread in JVM that runs periodically and reclaim memory of unreferenced objects.
Before object is destroyed, its finalize() method is invoked (if present).
One should override this method if object holds any resource to be released explicitly e.g. file close,
database connection, etc.
class Test {
Scanner sc = new Scanner(System.in);
@Override
protected void finalize() throws Throwable {
sc.close();
}
}
1. System.gc();
2. Runtime.getRuntime().gc();
1. Minor GC: Unreferenced objects from young generation are reclaimed. Objects not reclaimed
here are moved to old/permanent generation.
2. Major GC: Unreferenced objects from all generations are reclaimed. This is unefficient (slower
process).
GC Internals: https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
JDBC
RDBMS understand SQL language only.
JDBC driver converts Java requests in database understandable form and database response in Java
understandable form.
JDBC drivers are of 4 types
Partially implemented in Java and partially in C/C++. Java code calls C/C++ methods via JNI.
Different driver for different RDBMS. Example: Oracle OCI driver.
Advantages:
Faster execution
Disadvantages:
Partially in Java (not truely portable)
Different driver for Different RDBMS
Class.forName("com.mysql.cj.jdbc.Driver");
// for Oracle: Use driver class oracle.jdbc.driver.OracleDriver
// db url = jdbc:dbname://db-server:port/database
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/classwork", "root",
"manager");
// for Oracle: jdbc:oracle:thin:@localhost:1521:sid
step 4: Execute the SQL query using the statement and process the result.
con.close();
stmt.close();
SQL Injection
Building queries by string concatenation is inefficient as well as insecure.
Example:
dno = sc.nextLine();
sql = "SELECT * FROM emp WHERE deptno="+dno;
If user input "10", then effective SQL will be "SELECT _ FROM emp WHERE deptno=10". This will select
all emps of deptno 10 from the RDBMS.
If user input "10 OR 1", then effective SQL will be "SELECT _ FROM emp WHERE deptno=10 OR 1". Here
"1" represent true condition and it will select all rows from the RDBMS.
In Java, it is recommeded NOT to use "Statement" and building SQL by string concatenation. Instead
use PreparedStatement.
PreparedStatement
PreparedStatement represents parameterized queries.
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
int roll = rs.getInt("roll");
String name = rs.getString("name");
double marks = rs.getDouble("marks");
System.out.printf("%d, %s, %.2f\n", roll, name, marks);
}
The same PreparedStatement can be used for executing multiple queries. There is no syntax checking
repeated. This improves the performance.
JDBC concepts
java.sql.Driver
java.sql.Connection
java.sql.Statement
Since query built using string concatenation, it may cause SQL injection.
java.sql.PreparedStatement
ResultSet rs = stmt.executeQuery();
// OR
int count = stmt.executeUpdate();
java.sql.ResultSet
ResultSet represents result of SELECT query. The result may have one/more rows and one/more columns. Can
access only the columns fetched from database in SELECT query (projection).
DAO class
In enterprise applications, there are multiple tables and frequent data transfer from database is needed.
Instead of writing a JDBC code in multiple Java files of the application (as and when needed), it is good
practice to keep all the JDBC code in a centralized place -- in a single application layer.
DAO (Data Access Object) class is standard way to implement all CRUD operations specific to a table. It
is advised to create different DAO for different table.
DAO classes makes application more readable/maintainable.
Example 1:
}
return count;
}
}
// in main()
try(StudentDao dao = new StudentDao()) {
System.out.print("Enter roll to be updated: ");
int roll = sc.nextInt();
System.out.print("Enter new name: ");
String name = sc.next();
System.out.print("Enter new marks: ");
double marks = sc.next();
Student s = new Student(roll, name, marks);
int cnt = dao.update(s);
System.out.println("Rows updated: " + cnt);
} // dao.close()
catch(Exception ex) {
ex.printStackTrace();
}
Example 2:
// POJO (Entity)
class Emp {
private int empno;
private String ename;
private Date hire;
// ...
}
class DbUtil {
public static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String DB_URL = "jdbc:mysql://localhost:3306/test";
public static final String DB_USER = "root";
public static final String DB_PASSSWD = "root";
static {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
public static Connection getConnection() throws Exception {
return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSSWD);
}
}
con = DbUtil.getConnection();
}
public void close() {
try {
if(con != null)
con.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public int update(Emp e) throws Exception {
String sql = "UPDATE emp SET ename=?, hire=? WHERE id=?";
try(PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setString(1, e.getEname());
java.util.Date uDate = e.getHire();
java.sql.Date sDate = new java.sql.Date(uDate.getTime());
stmt.setDate(2, sDate);
stmt.setInt(3, e.getEmpno());
int cnt = stmt.executeUpdate();
return cnt;
} // stmt.close();
}
// ...
}
// in main()
try(EmpDao dao = new EmpDao()) {
Emp e = new Emp();
// input emp data from end user (Scanner)
/*
String dateStr = sc.next(); // dd-MM-yyyy
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date uDate = sdf.parse(dateStr);
e.setHire(uDate);
*/
int cnt = dao.update(e);
System.out.println("Emps updated: " + cnt);
} // dao.close();
catch(Exception ex) {
ex.printStackTrace();
}
// ...
}
public void close() {
try {
// ...
if(stmtFindById != null)
stmtFindById.close();
if(con != null)
con.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public Emp findById(int empno) throws Exception {
stmtFindById.setInt(1, empno);
try(ResultSet rs = stmtFindById.executeQuery()) {
if(rs.next()) {
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
java.sql.Date sDate = rs.getDate("hire");
// ...
java.util.Date uDate = new java.util.Date( sDate.getTime() );
Emp e = new Emp(empno, ename, uDate);
return e;
}
} // rs.close();
return null;
}
}
```java
// in main()
try(EmpDao dao = new EmpDao()) {
System.out.print("Enter empno to find: ");
id = sc.nextInt();
e = dao.findById(id);
System.out.println("Found: " + e);
System.out.print("Enter empno to find: ");
id = sc.nextInt();
e = dao.findById(id);
System.out.println("Found: " + e);
System.out.print("Enter empno to find: ");
id = sc.nextInt();
e = dao.findById(id);
System.out.println("Found: " + e);
}
catch(Exception ex) {
ex.printStackTrace();
}
DELIMITER //
CREATE PROCEDURE sp_incrementvotes(IN p_id INT)
BEGIN
UPDATE candidates SET votes=votes+1 WHERE id=p_id;
END;
//
DELIMITER ;
CALL sp_incrementvotes(10);
DELIMITER //
CREATE PROCEDURE sp_getpartyvotes(IN p_party CHAR(40), OUT p_votes INT)
BEGIN
SELECT SUM(votes) INTO p_votes FROM candidates WHERE party=p_party;
END;
//
DELIMITER ;
Agenda
Transaction Management
java 8 interfaces
functional interface
lambda expression
JVM Architecture
Transaction Management
RDBMS Transactions
Transaction is set of DML operations to be executed as a single unit. Either all queries in tx should be
successful or all should be discarded.
The transactions must be atomic. They should never be partial.
catch(Exception e) {
e.printStackTrace();
con.rollback(); // rollback transaction
}
Java 8 Interface
Before Java 8 Interfaces are used to design specification/standards. It contains only declarations –
public abstract.
interface Geometry {
/*public static final*/ double PI = 3.14;
/*public abstract*/ int calcRectArea(int length, int breadth);
/*public abstract*/ int calcRectPeri(int length, int breadth);
}
As interfaces doesn't contain method implementations, multiple interface inheritance is supported (no
ambiguity error).
Interfaces are immutable. One should not modify interface once published.
Java 8 added many new features in interfaces in order to support functional programming in Java.
Many of these features also contradicts earlier Java/OOP concepts.
1. Default methods
Java 8 allows default methods in interfaces. If method is not overridden, its default implementation in
interface is considered.
This allows adding new functionalities into existing interfaces without breaking old implementations
e.g. Collection, Comparator, …
interface Emp {
double getSal();
default double calcIncentives() {
return 0.0;
}
}
class Manager implements Emp {
// ...
// calcIncentives() is overridden
double calcIncentives() {
return getSal() * 0.2;
}
}
class Clerk implements Emp {
// ...
// calcIncentives() is not overridden -- so method of interface is
considered
}
2. Functional Interfaces
If interface contains exactly one abstract method (SAM), it is said to be functional interface.
It may contain additional default & static methods. E.g. Comparator, Runnable, …
@FunctionalInterface annotation does compile time check, whether interface contains single abstract
method. If not, raise compile time error.
@FunctionalInterface // okay
interface Foo {
void foo(); // SAM
}
@FunctionalInterface // okay
interface FooBar1 {
void foo(); // SAM
default void bar() {
/*... */
}
}
@FunctionalInterface // NO -- error
interface FooBar2 {
void foo(); // AM
void bar(); // AM
}
@FunctionalInterface // NO -- error
interface FooBar3 {
default void foo() {
/*... */
}
default void bar() {
/*... */
}
}
@FunctionalInterface // okay
interface FooBar4 {
Prepared By : Rohan Paramane 3/9
Day16_Help.MD Sunbeam Infotech 2024-04-18
Functional interfaces forms foundation for Java lambda expressions and method references.
Lambda expressions
Traditionally Java uses anonymous inner classes to compact the code. For each inner class separate
.class file is created.
However code is complex to read and un-efficient to execute.
Lambda expression is short-hand way of implementing functional interface.
Its argument types may or may not be given. The types will be inferred.
Lambda expression can be single liner (expression not statement) or multi-liner block { ... }.
Here variable c is bound (captured) into lambda expression. So it can be accessed even out of scope
(effectively). Internally it is associated with the method/expression.
In some functional languages, this is known as Closures.
Method references
Prepared By : Rohan Paramane 6/9
Day16_Help.MD Sunbeam Infotech 2024-04-18
JVM Archicecture
1. Compilation
.class file is cretaed which consists of byte code
2. Byte Code
It is a machine level instructions that gets executed by the JVM
JVM converts byte code into target machine/native code
3. Execution
java is a tool used to execute the .class file.
It loads the .class file and invokes jvm for executing the file from the classpath
JVM Archiceture Overview
ClassLoader + Memory Area + Execution Engine
ClassLoader SubSystem
It loads and initialize the class
1. Loading
2. Linking
Three steps
1. Verifiaction : Bytecode verifier ensures that class is compiled by valid compiler and not
tampered
2. Preparation : Memory is allocated for static members and initialized with default values
3. Resolution : Symbolic references in constant pool are replaced by the direct references
3. Initialization
All static variables of class are assigned with their assigned values(field initializers)
all static blocks are executed if present
Memory Areas
Their are 5 memory areas
1. Method Area
2. heap Area
3. Stack Area
4. PC Registers
5. Native Method Stack Area
1. Method Area
2. Heap Area
3. Stack Area
Separate stack is created for each thread in JVM (when thread is created).
When a method is called a new FAR (stack frame) is created on its stack.
Each stack frame conatins local variable array, operand stack, and other frame data.
When method returns, the stack frame is destroyed.
4. PC Registers
Separate native method stack is created for each thread in JVM (when thread is created).
When a native method is called from the stack, a stack frame is created on its stack.
Execution Engine
The main component of JVM
Convert byte code into machine code and execute it (instruction by instruction).
It consists of
1. Interpreter
2. JIT Compiler
3. Garbage Collector
1. Interpreter
If method is called frequently, interpreting it each time slow down the execution of the program.
This limitation is overcomed by JIT (added in Java 1.1).
2. JIT compiler
3. Profiler
4. Garbage Collector
JNI
JNI acts as a bridge between Java method calls and native method implementations.
Agenda
Streams
Reflection
Annotation
Nested and Local classes
Java 8 Streams
Java 8 Stream is NOT IO streams.
java.util.stream package.
Streams follow functional programming model in Java 8.
The functional programming is based on functional interface (SAM).
Number of predefined functional interfaces added in Java 8. e.g. Consumer, Supplier, Function,
Predicate, ...
Lambda expression is short-hand way of implementing SAM -- arg types & return type are inferred.
Java streams represents pipeline of operations through which data is processed.
Stream operations are of two types
1. stateless operation
filter(), map(), flatMap(), limit(), skip()
2. stateful operation
sorted(), distinct()
reduce()
forEach()for (Employee e : arr) System.out.println(e);
collect(), toArray()
count(), max(), min()
Stream operations are higher order functions (take functional interfaces as arg).
Stream creation
Collection interface: stream() or parallelStream()
Prepared By : Rohan Paramane 1 / 14
Day17_Help.MD Sunbeam Infotech 2024-04-19
Stream creation
Collection interface: stream() or parallelStream()
generate() internally calls given Supplier in an infinite loop to produce infinite stream of
elements.
iterate() start the stream from given (arg1) "seed" and calls the given UnaryOperator in infinite
loop to produce infinite stream of elements.
Stream operations
Source of elements
Stream.of(names)
.forEach(s -> System.out.println(s));
Stream.of(names)
.filter(s -> s.endsWith("a"))
.forEach(s -> System.out.println(s));
Stream.of(names)
.map(s -> s.toUpperCase())
.forEach(s -> System.out.println(s));
Stream.of(names)
.sorted()
.forEach(s -> System.out.println(s));
Stream.of(names)
.sorted((x,y) -> y.compareTo(x))
.forEach(s -> System.out.println(s));
skip() & limit() -- leave first 2 names and print next 4 names
Stream.of(names)
.skip(2)
.limit(4)
.forEach(s -> System.out.println(s));
Stream.of(names)
.distinct()
.forEach(s -> System.out.println(s));
collect() -- collects all stream elements into an collection (list, set, or map)
Object[] toArrray()
R collect(Collector)
Collectors.toList(), Collectors.toSet(), Collectors.toCollection(), Collectors.joining()
Collectors.toMap(key, value)
Reflection
It is a technique to read the metadata and work with that data.
.class = Byte-code + Meta-data + Constant pool + ...
When class is loaded into JVM all the metadata is stored in the object of java.lang.Class (heap area).
This metadata includes class name, super class, super interfaces, fields (field name, field type, access
modifier, flags), methods (method name, method return type, access modifier, flags, method
arguments, ...), constructors (access modifier, flags, ctor arguments, ...), annotations (on class, fields,
methods, ...).
Reflection applications
Inspect the metadata (like javap)
Build IDE/tools (Intellisense)
Dynamically creating objects and invoking methods
Access the private members of the class
Class<?> c = Class.forName(className);
Class<?> c = ClassName.class;
Class<?> c = obj.getClass();
Field[] fields = c.getFields(); // all fields accessible (of class & its
super class)
Method[] methods = c.getMethods(); // all methods accessible (of class & its
super class)
```Java
public class Middleware {
public static Object invoke(String className, String methodName, Class[]
methodParamTypes, Object[] methodArgs) throws Exception {
// load the given class
Class c = Class.forName(className);
// create object of that class
Object obj = c.newInstance(); // also invokes param-less constructor
// find the desired method
Method method = c.getDeclaredMethod(methodName, methodParamTypes);
// allow to access the method (irrespective of its access specifier)
method.setAccessible(true);
// invoke the method on the created object with given args & collect the
result
Object result = method.invoke(obj, methodArgs);
// return the results
return result;
}
}
```
```Java
// invoking method statically
Date d = new Date();
String result = d.toString();
```
```Java
// invoking method dyanmically
String result = Middleware.invoke("java.util.Date", "toString", null, null);
```
Annotations
Added in Java 5.0.
Annotation is a way to associate metadata with the class and/or its members.
Annotation applications
Information to the compiler
Compile-time/Deploy-time processing
Runtime processing
Annotation Types
Marker Annotation: Annotation is not having any attributes.
@Override, @Deprecated, @FunctionalInterface ...
Single value Annotation: Annotation is having single attribute -- usually it is "value".
@SuppressWarnings("deprecation"), ...
Multi value Annotation: Annotation is having multiple attribute
@RequestMapping(method = "GET", value = "/books"), ...
Pre-defined Annotations
@Override
Ask compiler to check if corresponding method (with same signature) is present in super class.
If not present, raise compiler error.
@FunctionalInterface
Ask compiler to check if interface contains single abstract method.
If zero or multiple abstract methods, raise compiler error.
@Deprecated
Inform compiler to give a warning when the deprecated type/member is used.
@SuppressWarnings
Inform compiler not to give certain warnings: e.g. deprecation, rawtypes, unchecked, serial,
unused
@SuppressWarnings("deprecation")
@SuppressWarnings({"rawtypes", "unchecked"})
@SuppressWarnings("serial")
@SuppressWarnings("unused")
Meta-Annotations
Annotations that apply to other annotations are called meta-annotations.
Meta-annotation types defined in java.lang.annotation package.
@Retention
RetentionPolicy.SOURCE
Annotation is available only in source code and discarded by the compiler (like comments).
Not added into .class file.
Used to give information to the compiler.
e.g. @Override, ...
RetentionPolicy.CLASS
Annotation is compiled and added into .class file.
Discared while class loading and not loaded into JVM memory.
Used for utilities that process .class files.
e.g. Obfuscation utilities can be informed not to change the name of certain class/member using
@SerializedName, ...
RetentionPolicy.RUNTIME
Annotation is compiled and added into .class file. Also loaded into JVM at runtime and available
for reflective access.
Used by many Java frameworks.
e.g. @RequestMapping, @Id, @Table, @Controller, ...
@Target
Where this annotation can be used.
ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE,
TYPE_PARAMETER, TYPE_USE
If annotation is used on the other places than mentioned in @Target, then compiler raise error.
Prepared By : Rohan Paramane 8 / 14
Day17_Help.MD Sunbeam Infotech 2024-04-19
@Documented
This annotation should be documented by javadoc or similar utilities.
@Repeatable
The annotation can be repeated multiple times on the same class/target.
@Inherited
The annotation gets inherited to the sub-class and accessible using c.getAnnotation() method.
Custom Annotation
Annotation to associate developer information with the class and its members.
@Inherited
@Retention(RetentionPolicy.RUNTIME) // the def attribute is considered as
"value" = @Retention(value = RetentionPolicy.RUNTIME )
@Taget({TYPE, CONSTRUCTOR, FIELD, METHOD}) // { } represents array
@interface Developer {
String firstName();
String lastName();
String company() default "Sunbeam";
String value() default "Software Engg";
}
@Repeatable
@Retention(RetentionPolicy.RUNTIME)
@Taget({TYPE})
@interface CodeType {
String[] value();
}
}
@Developer(firstName="Rohan", lastName="Paramane", company="Sunbeam Pune
")
public void myMethod() {
Prepared By : Rohan Paramane 9 / 14
Day17_Help.MD Sunbeam Infotech 2024-04-19
// @Developer is inherited
@CodeType("frontEnd")
@CodeType("businessLogic") // allowed because @CodeType is @Repeatable
class YourClass extends MyClass {
// ...
}
//anns = YourClass.class.getDeclaredAnnotations();
anns = YourClass.class.getAnnotations();
for (Annotation ann : anns)
System.out.println(ann.toString());
System.out.println();
Member/Nested classes
By default all Java classes are top-level.
In Java, classes can be written inside another class/method. They are Member classes.
Four types of member/nested classes
Static member classes --
Non-static member class --
Local class --
Prepared By : Rohan Paramane 10 / 14
Day17_Help.MD Sunbeam Infotech 2024-04-19
Accessed using outer class (Doesn't need the object of outer class).
Static member class cannot access non-static members of outer class directly.
The outer class can access all members (including private) of inner class directly (no need of
getter/setter).
class Outer {
private int nonStaticField = 10;
private static int staticField = 20;
Can access static & non-static (private) members of the outer class directly.
The outer class can access all members (including private) of inner class directly (no need of
getter/setter).
class Outer {
private int nonStaticField = 10;
private static int staticField = 20;
public class Inner {
public void display() {
System.out.println("Outer.nonStaticField = " + nonStaticField);
// ok-10
System.out.println("Outer.staticField = " + staticField); // ok-
20
}
}
}
public class Main {
public static void main(String[] args) {
//Outer.Inner obj = new Outer.Inner(); // compiler error
// create object of inner class
//Outer outObj = new Outer();
//Outer.Inner obj = outObj.new Inner();
Outer.Inner obj = new Outer().new Inner();
obj.display();
}
}
If Inner class member has same name as of outer class member, it shadows (hides) the outer class
member. Such Outer class members can be accessed explicitly using Outer.this.
// top-level class
class LinkedList {
// static member class
static class Node {
private int data;
private Node next;
// ...
}
private Node head;
// non-static member class
class Iterator {
private Node trav;
// ...
}
// ...
public void display() {
Node trav = head;
while(trav != null) {
System.out.println(trav.data);
trav = trav.next;
}
}
}
Local class
Like local variables of a method.
The class scope is limited to the enclosing method.
If enclosed in static method, behaves like static member class. If enclosed in non-static method,
behaves like non-static member class.
Along with Outer class members, it can also access (effectively) final local variables of the enclosing
method.
We can create any number of objects of local classes within the enclosing method.
If in static context, behaves like static member class. If in non-static context, behaves like non-static
member class.
Along with Outer class members, it can also access (effectively) final local variables of the enclosing
method.
Prepared By : Rohan Paramane 13 / 14
Day17_Help.MD Sunbeam Infotech 2024-04-19