Java Programming Basics and History
Java Programming Basics and History
Agenda
Introduction
Installation and Directory Structure
OOP Concepts
Hello world Program
Execution Flow
main() variations
Console input and output
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
Java SE 6 - December 11, 2006
Prepared By : Rohan Paramane 1/6
Day01_Help.MD Sunbeam Infotech 2024-09-23
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.
[Link]
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.
|- [Link]: Contains Java source code for the JDK (not always included in all
distributions).
[Link]
Object Oriented
Prepared By : Rohan Paramane 3/6
Day01_Help.MD Sunbeam Infotech 2024-09-23
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[]){
[Link]("Hello World");
}
}
main()
[Link]()
javac [Link]
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.
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
Language Fundamentals
Class Object and Reference
Widening and Narrowing
Wrapper classes
Boxing & UnBoxing
Command Line Arguments
Packages
Access Modifiers
this reference
types of methods
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
28. native - Specifies that a method is implemented with native (platform-specific) code
29. new - Creates new objects
30. null - This indicates that a reference does not refer to anything
31. package - Declares a Java package
32. private - An access specifier indicating that a method or variable may be accessed only in the class it’s
declared in
33. protected - An access specifier indicating that a method or variable may only be accessed in the class
it’s declared in (or a subclass of the class it’s declared in or other classes in the same package)
34. public - An access specifier used for classes, interfaces, methods, and variables indicating that an item is
accessible throughout the application (or where the class that defines it is accessible)
35. return - Sends control and possibly a return value back from a called method
36. short - A data type that can hold a 16-bit integer 37 static - Indicates that a variable or method is a
class method (rather than being limited to one particular object)
37. strictfp - A Java keyword is used to restrict the precision and rounding of floating-point calculations to
ensure portability.
38. super - Refers to a class’s base class (used in a method or class constructor)
39. switch - A statement that executes code based on a test value
40. synchronized - Specifies critical sections or methods in multithreaded code
41. this - Refers to the current object in a method or constructor
42. throw - Creates an exception
43. throws - Indicates what exceptions may be thrown by a method
44. transient - Specifies that a variable is not part of an object’s persistent state
45. try - Starts a block of code that will be tested for exceptions
46. void - Specifies that a method does not have a return value
47. volatile - This indicates that a variable may change asynchronously
48. while - Starts a while loop
49. goto, const - Unused keywords
50. true, false, null - Literals (Reserved words)
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:
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.
Non-static/Instance field: Within a class - Accessed using object.
Static field: Within a class - Accessed using class-name.
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: [Link], [Link].
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 [Link] 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
Packages
Prepared By : Rohan Paramane 10 / 13
Day02_Help.MD Sunbeam Infotech 2024-09-24
g
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 [Link]
export CLASSPATH=../bin
java [Link]
// if without setting classpath we want to execute the java code use below command
java -cp ../bin [Link]
java [Link]
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.
Agenda
this reference
Method Overloading
Types of Methods
Constructor Chaning
Array
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
Prepared By : Rohan Paramane 1/3
Day03_Help.MD Sunbeam Infotech 2024-09-25
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.
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
Method Overloading
Defining methods with same name but differnt arguments(signature) is called as method overloading
Arguments can differ in one of the following ways
type of parameter
Order or parameters
Agenda
Array
Variable Arity/Argument Method
final Keyword
static Keyword
Singleton Design Pattern
BuzzWords
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
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:
[Link](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
Singleton Design Pattern
Association
Inheritance
super keyword
Types of inheritance
Method Overriding
Upcasting & Downcasting
Object class
Methods of object class
toString();
equals();
Final Method & Class
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 I1{
}
interface I2{
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".
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.
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".
Agenda
instanceof
Final Method & Class
Object class
Methods of object class
toString()
equals()
Abstract class/method
Interfaces
Marker interfaces
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.
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
[Link] (and all wrapper classes)
[Link]
[Link]
Object class
Non final and non-abstract class declared in [Link] package.
In java, all the classes (not interfaces) are directly or indirectly extended from Object class.
Prepared By : Rohan Paramane 1/3
Day06_Help.MD Sunbeam Infotech 2024-09-28
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
It is non final method of object class
To compare the object contents/state, programmer should override equals() method.
This equals() must have following properties:
Reflexive: for any non-null reference value x, [Link](x) should return true.
Symmetric: for any non-null reference values x and y, [Link](y) should return true if and only if
[Link](x) returns true.
Transitive: for any non-null reference values x, y, and z, if [Link](y) returns true and [Link](z)
returns true, then [Link](z) should return true.
Consistent: for any non-null reference values x and y, multiple invocations of [Link](y)
consistently return true or consistently return false, provided no information used in equals
comparisons on the objects is modified.
For any non-null reference value x, [Link](null) should return false.
It is recommended to override hashcode method along when equals method is overriden.
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:
[Link]
[Link]
Agenda
Interfaces
Marker interfaces
Exception Handling
Exceptions
Errors
Exception Chaning
Custom Exceptions
Date/LocalDate/Calender
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
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.
[Link] -- Allows JVM to convert object state into sequence of bytes.
[Link] -- Allows JVM to create copy of the class object.
Cloneable interface
Enable creating copy/clone of the object.
If a class is Cloneable, [Link]() method creates a shallow copy of the object.
If class is not Cloneable, [Link]() throws CloneNotSupportedException.
A class should implement Cloneable and override clone() to create a deep/shallow copy of the object.
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
- NoSuchElementException
- InputMismatchException
- NullPointerException
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.
Agenda
Exception Chaning
Custom Exceptions
Date/LocalDate/Calender
clone()
Strings
String
StringBuffer
StringBuilder
Garbage Collector
Java BuzzWords
Enum
JVM Architecture
Arrays class
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.
// [Link]
Date d = new Date();
[Link]("Timestamp: " + [Link]());
// number of milliseconds since 1-1-1970 00:00.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
[Link]("Date: " + [Link](d));
// [Link]
String str = "28-09-1983";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = [Link](str);
[Link]([Link]());
// [Link]
Calendar c = [Link]();
[Link]([Link]());
[Link]("Current Year: " + [Link]([Link]));
[Link]("Current Month: " + [Link]([Link]));
[Link]("Current Date: " + [Link]([Link]));
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
Strings
[Link] is wrapper class that represents char.
In Java, each char is 2 bytes because it follows unicode encoding.
String is sequence of characters.
1. [Link]: "Immutable" character sequence
2. [Link]: Mutable character sequence (Thread-safe)
3. [Link]: Mutable character sequence (Not Thread-safe)
String helpers
1. [Link]: 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 [Link]
boolean hasMoreTokens()
String nextToken()
String nextToken(String delim)
Clone method
The clone() method is used to create a copy of an object in Java. - It's defined in the [Link]
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 [Link]() 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.
Garbage Collector
```JAVA
class Test {
Scanner sc = new Scanner([Link]);
@Override
protected void finalize() throws Throwable {
[Link]();
}
}
1. [Link]();
2. [Link]().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: [Link]
Java BuzzWords
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.
Agenda
Generics
Generic class
Generic method
Generic Limitations
Generic Interfaces
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 [Link] class -- Non typesafe
2. using Generics -- Typesafe
class Box {
private Object obj;
public void set(Object obj) {
[Link] = obj;
}
public Object get() {
return [Link];
}
}
Generic classes
Implementing a generic class
class Box<TYPE> {
private TYPE obj;
s
public void set(TYPE obj) {
[Link] = obj;
}
public TYPE get() {
return [Link];
}
}
Box<> b3 = new Box<>(); // error -- type must be given while creating generic
class reference, as reference cannot be auto-detected
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 [Link];
}
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) {
// [Link](element);
// }
// }
// Type-safe
public static <Type> void printArray(Type[] arr) {
for (Type element : arr) {
Prepared By : Rohan Paramane 5/9
Day09_Help.MD Sunbeam Infotech 2024-10-02
[Link](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.
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 = [Link](p2);
if(diff == 0)
[Link]("Both are same");
else if(diff > 0)
[Link]("p1 is greater than p2");
else //if(diff < 0)
[Link]("p1 is less than p2");
diff = [Link]("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 = [Link](p2);
if(diff == 0)
[Link]("Both are same");
else if(diff > 0)
[Link]("p1 is greater than p2");
else //if(diff < 0)
[Link]("p1 is less than p2");
diff = [Link]("Superman"); // compiler error
}
}
Comparable<>
Standard for comparing the current object to the other object.
Comparator<>
Standard for comparing two (other) objects.
Has single abstract method int compare(T obj1, T obj2);
In [Link] package.
Used by various methods like [Link](T[], comparator), ...
Agenda
Collection FrameWork
Traversal
FailSafe and FailFast Iterator
List
Queue
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 [Link] 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()
Iterable interface
To traverse any collection it provides an Iterator.
Enable use of for-each loop.
In [Link] 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()
Enumeration
Since Java 1.0
Methods
boolean hasMoreElements()
E nextElement()
Collections class
Helper/utility class that provides several static helper methods
Methods
List reverse(List list);
List shuffle(List list);
void sort(List list, Comparator cmp)
E max(Collection list, Comparator cmp);
E min(Collection list, Comparator cmp);
List synchronizedList(List list);
Collection vs Collections
1. Collection interface
2. Collections class
[Link](...);
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)
[Link](i);
// v is Vector<Integer>
Enumeration<Integer> e = [Link]();
while([Link]()) {
Integer i = [Link]();
[Link](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)
Agenda
Queue
Set
Map
hashcode()
Vector class
Internally Vector is dynamic array (can grow or shrink dynamically).
Vector is a legacy collection (since Java 1.0) that is modified to fit List interface.
Vector is synchronized (thread-safe) and hence slower.
When Vector capacity is full, it doubles its size.
Elements can be traversed using Enumeration, 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
Synchronization slow down performance in single threaded environment
Inherited from List<>.
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.
Implementations: LinkedList, ArrayDeque, PriorityQueue.
Can be accessed using iterator, but no random access.
Methods
boolean add(E e) - throw IllegalStateException if full.
E remove() - throw NoSuchElementException if empty
E element() - throw NoSuchElementException if empty
boolean offer(E e) - return false if full.
E poll() - returns null if empty
E peek() - returns null if empty
In queue, addition and deletion is done from the different ends (rear and front)
Difference between these methods is first 3 methods throws exception however next 3 methods do not
throw exception if operation fails.
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
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.
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
Prepared By : Rohan Paramane 3/5
Day11_Help.MD Sunbeam Infotech 2024-10-04
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.
Optional Assignemnt
Prepared By : Rohan Paramane 4/5
Day11_Help.MD Sunbeam Infotech 2024-10-04
p g
1. Store few books in a HashSet and display them using iterator. If any book with duplicate bookid is
added, what will happen? Books are stored in which order?
2. In above assignment use LinkedHashSet instead of HashSet. If any book with duplicate bookid is added,
what will happen? Books are stored in which order?
3. In above assignment use TreeSet instead of LinkedHashSet. Use natural ordering for the Book. If any
book with duplicate bookid is added, what will happen? Books are stored in which order?
4. In above assignment use TreeSet parameterized ctor that takes comparator. Use price of the Book for
ordering in descending order. If any book with duplicate bookid is added, what will happen? Books are
stored in which order?
Agenda
HashTable
hashcode()
Map
Enum
JVM Architecture
Java 8 Interfaces
Functional Interfaces
Annoymous Inner Classes
Lambda Expressions
Method references
Stream Programming
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).
Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable, ...
The data can be accessed as set of keys, collection of values, and/or set of key-value entries.
[Link]<K,V> is nested interface of Map<K,V>.
K getKey()
V getValue()
V setValue(V value)
Abstract methods
* boolean isEmpty()
* int size()
* V put(K key, V value)
* V get(Object key)
* Set<K> keySet()
* Collection<V> values()
* Set<[Link]<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 [Link] abstract class (it is Obsolete).
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 [Link] 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.
// 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);
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
Prepared By : Rohan Paramane 5/7
Day12_Help.MD Sunbeam Infotech 2024-10-05
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
Java 8 Interfaces
Functional Interfaces
Annoymous Inner Classes
Lambda Expressions
Method references
Local and Nested classes
Stream Programming
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;
}
}
However default methods will lead to ambiguity errors as well, if same default method is available from
multiple interfaces. Error: Duplicate method while declaring class.
Superclass same method get higher priority. But super-interfaces same method will lead to error.
Super-class wins! Super-interfaces clash!!
interface Displayable {
default void show() {
[Link]("[Link]() called");
}
}
interface Printable {
default void show() {
[Link]("[Link]() called");
}
}
class FirstClass implements Displayable, Printable { // compiler error:
duplicate method
// ...
}
class Main {
public static void main(String[] args) {
FirstClass obj = new FirstClass();
[Link]();
}
}
interface Displayable {
default void show() {
[Link]("[Link]() called");
}
}
interface Printable {
default void show() {
[Link]("[Link]() called");
}
}
class Superclass {
public void show() {
Prepared By : Rohan Paramane 2/7
Day13_Help.MD Sunbeam Infotech 2024-10-07
[Link]("[Link]() called");
}
}
class SecondClass extends Superclass implements Displayable, Printable {
// ...
}
class Main {
public static void main(String[] args) {
SecondClass obj = new SecondClass();
[Link](); // [Link]() called
}
}
interface Displayable {
default void show() {
[Link]("[Link]() called");
}
}
interface Printable {
default void show() {
[Link]("[Link]() called");
}
}
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 {
void foo(); // SAM
public static void bar() {
/*... */
}
}
Functional interfaces forms foundation for Java lambda expressions and method references.
Along with Outer class members, it can also access (effectively) final local variables of the enclosing
method.
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 { ... }.
If lambda expression result also depends on additional variables in the context of the lambda
expression passed to it, then it is capturing.
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
lambda expression is an short-hand implementation of Single Abstract Method (Functional Interface)
Method reference is short-hand of lambda-expression
If lambda expression involves single method call, it can be shortened by using method reference.
Method references are converted into instances of functional interfaces.
Method reference can be used for class static method, class non-static method, object non-static
method or constructor.
Agenda
Stream Programming
File IO
Java 8 Streams
Java 8 Stream is NOT IO streams.
[Link] 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) [Link](e);
collect(), toArray()
count(), max(), min()
Stream operations are higher order functions (take functional interfaces as arg).
Stream creation
Collection interface: stream() or parallelStream()
Arrays class: [Link]()
Stream interface: static of() method
Prepared By : Rohan Paramane 1/7
Day14_Help.MD Sunbeam Infotech 2024-10-08
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
[Link](names)
.forEach(s -> [Link](s));
[Link](names)
.filter(s -> [Link]("a"))
.forEach(s -> [Link](s));
[Link](names)
.map(s -> [Link]())
.forEach(s -> [Link](s));
[Link](names)
.sorted()
.forEach(s -> [Link](s));
[Link](names)
.sorted((x,y) -> [Link](x))
Prepared By : Rohan Paramane 3/7
Day14_Help.MD Sunbeam Infotech 2024-10-08
skip() & limit() -- leave first 2 names and print next 4 names
[Link](names)
.skip(2)
.limit(4)
.forEach(s -> [Link](s));
[Link](names)
.distinct()
.forEach(s -> [Link](s));
collect() -- collects all stream elements into an collection (list, set, or map)
.limit(5)
.reduce(0, (x,y) -> x + y);
Java IO framework
Input/Output functionality in Java is provided under package [Link] and [Link] 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
Java IO
Java File IO is done with Java IO streams.
Java IO Streams are completly different from [Link]. 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
Each IO stream object performs a specific task.
FileOutputStream -- Write the given bytes into the file (on disk).
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).
Prepared By : Rohan Paramane 6/7
Day14_Help.MD Sunbeam Infotech 2024-10-08
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()
Serializable interface
Object can be serialized only if class is inherited from Serializable interface; otherwise writeObject()
throws NotSerializableException.
Serializable is a marker interface.
Agenda
Stream API
collect
reduce
File IO
JDBC
Optional<> type
Few stream operations yield Optional<> value.
opt = [Link]("A")
opt = [Link]() -> cretes an optional with no value
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
[Link] class
A path (of file or directory) in file system is represented by "File" object.
Used to access/manipulate metadata of the file/directory.
Provides FileSystem APIs
String[] list() -- return contents of the directory
File[] listFiles() -- return contents of the directory
boolean exists() -- check if given path exists
boolean mkdir() -- create directory
boolean mkdirs() -- create directories (child + parents)
boolean createNewFile() -- create empty file
boolean delete() -- delete file/directory
boolean renameTo(File dest) -- rename file/directory
String getAbsolutePath() -- returns full path (drive:/folder/folder/...)
String getPath() -- return path
File getParentFile() -- returns parent directory of the file
String getParent() -- returns parent directory path of the file
String getName() -- return name of the file/directory
static File[] listRoots() -- returns all drives in the systems.
long getTotalSpace() -- returns total space of current drive
long getFreeSpace() -- returns free space of current drive
long getUsableSpace() -- returns usable space of current drive
boolean isDirectory() -- return true if it is a directory
boolean isFile() -- return true if it is a file
boolean isHidden() -- return true if the file is hidden
boolean canExecute()
boolean canRead()
boolean canWrite()
boolean setExecutable(boolean executable) -- make the file executable
boolean setReadable(boolean readable) -- make the file readable
transient fields
writeObject() serialize all non-static fields of the class. If fields are objects, then they are also serialized.
If any field is intended not to serialize, then it should be marked as "transient".
The transient and static fields (except serialVersionUID) are not serialized.
serialVersionUID field
Each serializable class is associated with a version number, called a serialVersionUID.
It is recommended that programmer should define it as a static final long field (with any access
specifier). Any change in class fields expected to modify this serialVersionUID.
During deserialization, this number is verified by the runtime to check if right version of the class is
loaded in the JVM. If this number mismatched, then InvalidClassException will be thrown.
If a serializable class does not explicitly declare a serialVersionUID, then the runtime will calculate a
default serialVersionUID value for that class (based on various aspects of the class described in the
Java(TM) Object Serialization specification).
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().
[Link] and [Link] are objects of PrintStream class.
It is used only to write the formatted data in to the file.
Scanner class
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.
[Link]
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.
Writer class -- write operation
void close() -- close the stream
void flush() -- writes data (in memory) to underlying stream/device.
void write(char[] b) -- writes char array to underlying stream/device.
void write(int b) -- writes a char to underlying stream/device.
Writer Sub-classes
FileWriter, OutputStreamWriter, PrintWriter, BufferedWriter, etc.
Reader class -- read operation
void close() -- close the stream
int read(char[] b) -- reads char array from underlying stream/device
int read() -- reads a char from the underlying device/stream. Returns -1
Reader Sub-classes
FileReader, InputStreamReader, BufferedReader, etc.
Java NIO
Java NIO (New IO) is an alternative IO API for Java.
Java NIO offers a different IO programming model than the traditional IO APIs.
Since Java 7.
Java NIO enables you to do non-blocking (not fully) IO.
Java NIO consist of the following core components:
Channels e.g. FileChannel, ...
Buffers e.g. ByteBuffer, ...
Selectors
Java NIO also provides "helper" classes Paths & Files.
exists()
...
Files class (Files) provides several static methods for manipulating files in the file system.
NIO Channels
Java NIO Channels are similar to IO streams with a few differences:
You can both read and write to a Channels. Streams are typically one-way (read or write).
Channels can be read and written asynchronously (non-blocking).
Channels always read to, or write from, a Buffer.
Channel Examples
FileChannel
NIO Buffers
A buffer is essentially a block of memory into which you can write data, which you can then later read
again. This memory block is wrapped in a NIO Buffer object, which provides a set of methods that
makes it easier to work with the memory block.
Using a Buffer to read and write data typically follows this 4-step process:
Write data into the Buffer
Call [Link]()
Read data out of the Buffer
Call [Link]() or [Link]()
Buffer Examples
ByteBuffer
CharBuffer
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
while([Link]()){
[Link]((char) [Link]()); // read data from the buffer
}
RandomAccessFile
RandomAccessFile class from [Link] package.
Capable of reading and writing into a file (on a storage device).
Internally maintains file read/write position/cursor.
Prepared By : Rohan Paramane 6 / 11
Day15_Help.MD Sunbeam Infotech 2024-10-09
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
4. Type IV
Prepared By : Rohan Paramane 7 / 11
Day15_Help.MD Sunbeam Infotech 2024-10-09
[Link]("[Link]");
// for Oracle: Use driver class [Link]
// db url = jdbc:dbname://db-server:port/database
Connection con =
[Link]("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.
[Link]();
[Link]();
SQL Injection
Building queries by string concatenation is inefficient as well as insecure.
Example:
dno = [Link]();
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.
[Link](1, name);
ResultSet rs = [Link]();
while([Link]()) {
int roll = [Link]("roll");
String name = [Link]("name");
double marks = [Link]("marks");
[Link]("%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
[Link]
[Link]
[Link]
Since query built using string concatenation, it may cause SQL injection.
[Link]
ResultSet rs = [Link]();
// OR
int count = [Link]();
[Link]
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).
JDBC
Annotation
Reflection
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:
// in main()
try(StudentDao dao = new StudentDao()) {
[Link]("Enter roll to be updated: ");
int roll = [Link]();
[Link]("Enter new name: ");
String name = [Link]();
[Link]("Enter new marks: ");
double marks = [Link]();
Student s = new Student(roll, name, marks);
Example 2:
// POJO (Entity)
class Emp {
private int empno;
private String ename;
private Date hire;
// ...
}
class DbUtil {
public static final String DB_DRIVER = "[Link]";
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 {
[Link](DB_DRIVER);
} catch (ClassNotFoundException e) {
[Link]();
[Link](0);
}
}
public static Connection getConnection() throws Exception {
return [Link](DB_URL, DB_USER, DB_PASSSWD);
}
}
[Link](1, [Link]());
[Link] uDate = [Link]();
[Link] sDate = new [Link]([Link]());
[Link](2, sDate);
[Link](3, [Link]());
int cnt = [Link]();
return cnt;
} // [Link]();
}
// ...
}
// in main()
try(EmpDao dao = new EmpDao()) {
Emp e = new Emp();
// input emp data from end user (Scanner)
/*
String dateStr = [Link](); // dd-MM-yyyy
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
[Link] uDate = [Link](dateStr);
[Link](uDate);
*/
int cnt = [Link](e);
[Link]("Emps updated: " + cnt);
} // [Link]();
catch(Exception ex) {
[Link]();
}
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 ;
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.
Reflection
It is a technique to read the metadata and work with that data.
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 = [Link](className);
Class<?> c = [Link];
Class<?> c = [Link]();
Field[] fields = [Link](); // all fields accessible (of class & its
super class)
Method[] methods = [Link](); // all methods accessible (of class & its
super class)
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"), ...
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 [Link] package.
@Retention
[Link]
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, ...
[Link]
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, ...
[Link]
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.
@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 [Link]() method.
Custom Annotation
Annotation to associate developer information with the class and its members.
@Inherited
@Retention([Link]) // the def attribute is considered as
"value" = @Retention(value = [Link] )
@Taget({TYPE, CONSTRUCTOR, FIELD, METHOD}) // { } represents array
@interface Developer {
String firstName();
String lastName();
String company() default "Sunbeam";
String value() default "Software Engg";
}
@Repeatable
@Retention([Link])
@Taget({TYPE})
@interface CodeType {
String[] value();
}
}
@Developer(firstName="Shubham", lastName="Borle", company="Sunbeam Karad
")
public void myMethod() {
@Developer(firstName="James", lastName="Bond") // compiler error
int localVar = 1;
}
}
// @Developer is inherited
@CodeType("frontEnd")
@CodeType("businessLogic") // allowed because @CodeType is @Repeatable
class YourClass extends MyClass {
// ...
}
//anns = [Link]();
anns = [Link]();
for (Annotation ann : anns)
[Link]([Link]());
[Link]();
Agenda
Multi-Threading
Nested classes
Platform Independence
Java is architecture neutral i.e. can work on various CPU architectures like x86, ARM, SPARC, PPC, etc (if
JVM is available on those architectures).
Java is NOT fully platform independent. It can work on various platforms like Windows, Linux, Mac,
UNIX, etc (if JVM is available on those platforms).
Few features of Java remains platform dependent.
Multi-threading (Scheduling, Priority)
File IO (Performance, File types, Paths)
AWT GUI (Look & Feel)
Networking (Socket connection)
Program
Program is set of instructions given to the computer.
Executable file is a program.
Executable file contains text, data, rodata, symbol table, exe header.
Process
Process is program in execution.
Program (executable file) is loaded in RAM (from disk) for execution. Also OS keep information required
for execution of the program in a struct called PCB (Process Control Block).
Process contains text, data, rodata, stack, and heap section.
Thread
Threads are used to do multiple tasks concurrently within a single process.
Thread is a lightweight process.
When a new thread is created, a new TCB is created along with a new stack. Remaining sections are
shared with parent process.
Process vs Thread
Process is a container that holds resources required for execution and thread is unit of
execution/scheduling.
Each process have one thread created by default -- called as main thread.
Runtime rt = [Link]();
The process is created using exec() method, which returns the Process object. This object represents the
OS process and its waitFor() method wait for the process termination (and returns exit status).
Multi-threading (Java)
Java applications are always multi-threaded.
When any java application is executed, JVM creates (at least) two threads.
main thread -- executes the application main()
GC thread -- does garbage collection (release unreferenced objects)
Programmer may create additional threads, if required.
Thread creation
To create a thread
step 1: Implement a thread function (task to be done by the thread)
step 2: Create a thread (with above function)
Method 1: extends Thread
}
}
Java doesn't support multiple inheritance. If your class is already inherited from a super class, you
cannot extend it from Thread class. Prefer Runnable in this case; otherwise you may choose any
method.
start() vs run()
run():
start():
Thread methods
static Thread currentThread()
Causes the currently executing thread to sleep (temporarily cease execution) for the specified
number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
A hint to the scheduler that the current thread is willing to yield its current use of a processor.
[Link] getState()
void run()
If this thread was constructed using a separate Runnable run object, then that Runnable object's
run method is called. If thread class extends from Thread class, this method should be
overridden. The default implementation is empty.
void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this
thread.
void join()
boolean isAlive()
Marks this thread as either a daemon thread (true) or a user thread (false).
boolean isDaemon()
long getId()
String getName()
int getPriority()
ThreadGroup getThreadGroup()
void interrupt()
boolean isInterrupted()
Daemon threads
By default all threads are non-daemon threads (including main thread).
We can make a thread as daemon by calling its setDaemon(true) method -- before starting the thread.
Daemon threads are also called as background threads and they support/help the non-daemon
threads.
When all non-daemon threads are terminated, the Daemon threads get automatically terminated.
Synchronization
When multiple threads try to access same resource at the same time, it is called as Race condition.
Example: Same bank account undergo deposit() and withdraw() operations simultaneously.
Java synchronization internally use the Monitor object associated with any object. It provides
lock/unlock mechanism.
It acquires lock on associated object at the start of block/method and release at the end. If lock is
already acquired by other thread, the current thread is blocked (until lock is released by the locking
Prepared By : Rohan Paramane 5 / 11
Day17_Help.MD Sunbeam Infotech 2024-10-11
thread).
"synchronized" non-static method acquires lock on the current object i.e. "this". Example:
class Account {
// ...
public synchronized void deposit(double amount) {
double newBalance = [Link] + amount;
[Link] = newBalance;
}
public synchronized void withdraw(double amount) {
double newBalance = [Link] - amount;
[Link] = newBalance;
}
}
"synchronized" static method acquires lock on metadata object of the class i.e. [Link]. Example:
class MyClass {
private static int field = 0;
// called by incThread
public synchronized static void incMethod() {
field++;
}
// called by decThread
public synchronized static void decMethod() {
field--;
}
}
// thread1
synchronized(acc) {
[Link](1000.0);
}
// thread2
synchronized(acc) {
[Link](1000.0);
}
Alternatively lock can be acquired using RentrantLock since Java 5.0. Example code:
class Example {
private final ReentrantLock rl = new ReentrantLock();
public void method() {
[Link]();
try {
// ...
}
finally {
[Link]();
}
}
}
Synchronized collections
Synchronized collections (e.g. Vector, Hashtable, ...) use synchronized keyword (block/method) to
handle race conditions.
Inter-thread communication
wait()
Causes the current thread to wait until another thread invokes the notify() method or the
notifyAll() method for this object.
The current thread must own this object's monitor i.e. wait() must be called within synchronized
block/method.
The thread releases ownership of this monitor and waits until another thread notifies.
The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
notify()
Wakes up a single thread that is waiting on this object's monitor.
If multiple threads are waiting on this object, one of them is chosen to be awakened arbitrarily.
The awakened thread will not be able to proceed until the current thread relinquishes the lock on
this object.
This method should only be called by a thread that is the owner of this object's monitor.
notifyAll()
Wakes up all threads that are waiting on this object's monitor.
The awakened threads will not be able to proceed until the current thread relinquishes the lock
on this object.
This method should only be called by a thread that is the owner of this object's monitor.
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 --
Annoymous Inner class --
Prepared By : Rohan Paramane 7 / 11
Day17_Help.MD Sunbeam Infotech 2024-10-11
When .java file is compiled, separate .class file created for outer class as well as inner class.
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() {
[Link]("[Link] = " + nonStaticField);
// ok-10
[Link]("[Link] = " + staticField); // ok-
20
}
}
}
public class Main {
public static void main(String[] args) {
//[Link] obj = new [Link](); // compiler error
// create object of inner class
//Outer outObj = new Outer();
//[Link] obj = [Link] Inner();
[Link] obj = new Outer().new Inner();
[Link]();
}
}
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 [Link].
// 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) {
[Link]([Link]);
trav = [Link];
}
}
}
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 10 / 11
Day17_Help.MD Sunbeam Infotech 2024-10-11