Oops
Oops
Java Buzzwords
It highlights the key feature and design principle of java
@cseabhisheks
Page |2
Data types:
it specifies the type of data that a variable can hold.
Variables
These are the named memory loca on they are declared with datatype and can be assign a value i.e.
int x=3;
Operator
These are the symbols that perform on variable and values.
Expression
these are the combina on of variable, literal, operators and methods calls that produce a value.
ex-2+3*4/5
@cseabhisheks
Page |3
Oops
Object-Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the so ware development and maintenance.
Paradigm
Paradigm can also be termed as method to solve some problem or do some tasks.
1. Modularity and Reusability: OOP allows breaking down complex systems into smaller,
reusable modules (objects).
2. Modeling Real-World Concepts: OOP encourages modeling of real-world en es and
rela onships, making systems easier to understand and communicate about.
3. Encapsula on:
4. Inheritance:
5. Polymorphism:
6. Abstrac on:
Class/Logical entities
Class is a user-defined data type which defines its proper es and its func ons.
It defines a data structure and behavior that can be shared by mul ple instances/objects of
that class
@cseabhisheks
Page |4
Type of class/logical en es
1. Predefined class/built-in class/standard class: A class that is provided by the programming
language or its libraries ex-scanner, console, system, string
2. User defined class: A class created by a programmer ex-car, animal, dog
Object/Run-time entity.
It is an instance of class that execute the class
It represents are real world en ty
Objects have state (a ributes or proper es) and behaviour (methods or func ons) defined
by their class.
An object can operate on both data members and member func ons.
It encapsulates both data and methods that operate on that data
Note: When an object is created using a new keyword, then space is allocated for the variable in a
heap, and the star ng address is stored in the stack memory. When an object is created without a
new keyword, then space is not allocated in the heap memory, and the object contains the null value
in the stack.
Constructor
Constructor is a special method which is invoked automa cally at the me of object crea on.
A constructor in Java is a special method used to ini alize objects.
At the me of calling the constructor, memory for the object is allocated in the memory.
A constructor cannot be inherited but can be invoked from child class using super () keyword
@cseabhisheks
Page |5
2. Constructors do not return any type while method(s) have the return type or void if does not
return any value.
3. Constructors are called only once at the me of Object crea on while method(s) can be
called any number of mes.
Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automa cally. A destructor is defined like a
constructor. It must have the same name as class, prefixed with a lde sign (~).
In Java, there are no destructors in the same sense as in languages like C++. In Java, memory
management is handled automa cally by the Java Virtual Machine (JVM) through a mechanism
called garbage collec on.
Garbage collec on: It is used to free up memory that is no longer reachable and needed by
the program.
This keyword:
‘this’ is a reference variable that refers to the current object
Uses:
It helps to dis nguish between instance variables and local variables with the same name.
It can be used to pass the current object as an argument to another method.
It can be used to return the current object from a method.
It can be used to invoke a constructor from another overloaded constructor in the same class.
Access Control
In Java, access control is primarily managed through the use of access modifiers, which define the
visibility and accessibility of classes, methods, and fields within a Java program
Member access rules : In Java, Member access rules define how fields, methods, and constructors
within a class can be accessed by other parts of the program based on their access modifiers
@cseabhisheks
Page |6
Methods:
In Java, methods are blocks of code that perform specific tasks and are defined within
classes.
These are the func on associated with in the class that define its behaviour.
They operate on the data of the class and may return value.
Method Overloading:
Method overloading refers to the prac ce of defining mul ple methods in a class with the
same name but different parameter lists.
Java dis nguishes between overloaded methods based on the number, type, and order of
their parameters.
Overloading occurs at compile me based on the reference type of the object.
Return types may or may not be the same.
Overloaded methods can have different access modifiers.
Method Overriding:
Method overriding occurs when a subclass provides a specific implementa on for a method
that is already defined in its superclass.
The method in the subclass has the same name, return type, and parameter list as the
method in the superclass.
Overriding occurs at run me
Parameter Passing
In Java, parameter passing refers to how arguments are passed to methods or constructors when
they are invoked. Java supports two types of parameters passing: pass by value and pass by
reference.
Pass by Value:
In pass by value, a copy of the actual parameter's value is passed to the method.
Changes made to the parameter within the method do not affect the original value
outside the method.
Java uses pass by value for primi ve data types (e.g., int, float, char, Boolean).
@cseabhisheks
Page |7
Type conversion
Type conversion in Java refers to the process of conver ng a value from one data type to another.
Java provides two types of type conversion
Cas ng: Explicitly conver ng a value from one data type to another using parentheses () and the
target data type. It's essen al for conver ng between incompa ble types.
Exceptional handling
Excep on handling in Java is a mechanism used to handle run me errors (excep ons) in a
program gracefully, preven ng the program from crashing and providing a way to recover
from errors.
Java uses the try, catch, finally, and throw keywords to implement excep on handling.
@cseabhisheks
Page |8
Packages:
a set of class and interfaces group together is called packages
A java packages is a group of similar type of classes interfaces and sub packages
It is of two types: user defined and built-in
(java.lang,javax.swing,java.net,java.math,java.u l,java.io,java.sql)
Ex-import java.lang.*; to call all lang packages
Crea ng packages
Choose a Package Name: Decide on a meaningful name for your package.
Create Package Directory Structure: Create directories corresponding to the package name.
Place Java Files: Put your Java source files inside the package directories and include the
package declara on at the top of each file.
Compile: Compile your Java source files.
Use Import Statements: Import classes from your package using import statements in other
Java files.
Compile and Run: Compile all Java files, including those using your package, and run your applica on.
Java I/0
Java brings various Streams with its I/O package that helps the user to perform all the input-output
opera ons.
These streams support all the types of objects, data-types, characters, files etc to fully execute the
I/O opera ons.
3. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
@cseabhisheks
Page |9
4. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
print (): This method in Java is used to display a text on the console. This text is passed as the
parameter to this method in the form of String. This method prints the text on the console
and the cursor remains at the end of the text at the console. The next prin ng takes place
from just here.
println (): This method in Java is also used to display a text on the console. It prints the text
on the console and the cursor moves to the start of the next line at the console. The next
prin ng takes place from the next line.
prin (): This is the easiest of all methods as this is similar to prin in C. Note that
System.out.print() and System.out.println() take a single argument, but prin () may take
mul ple arguments. This is used to format the output in Java.
5. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device. This stream also
uses all the 3 above-men oned func ons to output the error data: print (), println (), prin ()
Abstract class
Java abstract class is a class that can’t be ini ated by itself, it needs to be subclassed by another
class to use its proper es. An abstract class is declared using the “abstract” keyword in its class
defini on.
We give idea but don’t implement
Object class
Object class is present in java. lang package.
Every class in Java is directly or indirectly derived from the Object class.
If a class does not extend any other class, then it is a direct child class of Object and if
extends another class then it is indirectly derived.
Therefore, the Object class methods are available to all Java classes. Hence Object class acts
as a root of the inheritance hierarchy in any Java Program.
Arrays
An array is a data structure that stores a collec on of elements of the same type in con guous
memory loca ons
Type of arrays
1d-array: int[] numbers = new int[5];
Class path
Class path is a se ng that tells the Java Virtual Machine (JVM) where to find classes and resources
needed by a Java program during execu on. It includes directories, JAR files, and ZIP archives
containing necessary files.
@cseabhisheks
P a g e | 10
Class vs interface
Encapsulation
It is a mechanism of wrapping the data(variable) and code ac ng on the data (methods)together as a
single unit
Abstraction
It is the process in which we only show essen al detail/func onality to the user and the non-
essen al implementa on details are not displaced to the user.
Agents: In java objects are the agents.an agent encapsulate both data/a ributes and
func on/methods that operate on that data
Responsibility: It refers to the task or a func on that an object or agents is responsible for
carrying out.
@cseabhisheks
P a g e | 11
Messages: In java methods calls serves as messages. They are a way for object to communicate
with each other in oops. Object send messages to invoke methods or request, ac on from another
object
Methods: They are func ons or procedure associated with in an object. They define the behavior
of the object and how it responds to messages
Polymorphism
Polymorphism allows us to perform a single ac on in different ways.
In other words, polymorphism allows you to define one interface and have mul ple
implementa ons.
The word “poly” means many and “morphs” means forms, so it means many forms.
Inheritance
It is the mechanism in Java by which one class is allowed to inherit the features (fields
and methods) of another class
Inheritance allows a class (subclass or derived class) to inherit proper es and behaviors
(methods) from another class (superclass or base class). This promotes code reuse and
establishes an "IS_A" rela onship between the classes
"IS_A" rela on: the subclass is a specialized version of the superclass and possesses all the
characteris cs (proper es and behaviors) of the superclass, in addi on to its own specific
characteris cs.
This "IS_A" rela onship indicates that a Dog object, a Cat object, and a Bird object are all types of
Animal objects, but they may have addi onal characteris cs specific to their respec ve types.
@cseabhisheks
P a g e | 12
Sub/Child/Extended/Derived class: The class that inherits the other class is known
as a subclass
The subclass can add its own fields and methods in addi on to the superclass fields and
methods.
Subtype: When a child class inherits from a parent class, it establishes an "IS_A" rela onship,
meaning that instances of the child class can be treated as instances of the parent class. This
implies that the child class is a subtype of the parent class.
For example, consider a parent class Shape with child classes Circle and Rectangle. Both Circle
and Rectangle are subtypes of Shape. Instances of Circle and Rectangle can be treated as
instances of Shape because they inherit proper es and behaviors from Shape.
Forms of inheritance
1. Specializa on: Crea ng a more specific subclass that inherits from a more general superclass.
The subclass typically adds specialized features or behavior on top of what it inherits.
2. Specifica on: Defining a more detailed version of a class, o en by adding more a ributes or
methods to it. This can include defining abstract methods or interfaces that subclasses must
implement.
3. Construc on: Building complex classes by combining simpler classes. This can involve
composing classes together to create more sophis cated func onality or behavior.
4. Extension: Extending the func onality of a class by adding new features or modifying exis ng
ones. This typically involves subclassing a base class and implemen ng addi onal methods or
a ributes to meet specific requirements or customize behavior.
5. Limita on: Type coupling between classes, where changes in one class can affect others. This
can lead to ght coupling, making the codebase less flexible and more difficult to maintain.
6. Combina on: Using mul ple forms of inheritance, such as specializa on and construc on, in
a single program. This allows for greater flexibility and adaptability in designing class
hierarchies to meet specific requirements.
Benefits of inheritance
Increased reusability of code, improved modularity, and enhanced extensibility.
Costs
Increased complexity and poten al for errors, difficul es in maintenance
Type of inheritance
Mul ple inheritance is not supported by java but can be implement using interface
@cseabhisheks
P a g e | 13
Thread in Java:
Represents the path of execu on in a program.
All Java programs have at least one thread, typically the main thread that is provided
by the JVM or Java Virtual Machine at the star ng of the program’s execu on.
Thread Lifecycle:
The Life Cycle of a Thread in Java refers to the state transforma ons of a thread that begins
with its birth and ends with its death. When a thread instance is generated and executed by
calling the start() method of the Thread class, the thread enters the runnable state. When
the sleep() or wait() methods of the Thread class are called, the thread enters a non-
runnable mode. Thread returns from non-runnable state to runnable state and starts
statement execu on. The thread dies when it exits the run() process. In Java, these thread
state transforma ons are referred to as the Thread life cycle.
New State: This is the ini al state when a thread is created but the start() method
has not yet been invoked. The thread exists but has not begun execu on.
Runnable State: A er invoking the start() method, the thread enters the runnable
state. It's ready to execute but awaits processor availability. Threads in this state
are queued for execu on.
Running State: When the thread scheduler selects a runnable thread for execu on
and the processor allocates CPU me, the thread enters the running state. Here, it
directly executes its opera ons.
Blocked (Non-runnable) State: In certain situa ons, a thread may enter a blocked
state, where it's alive but not selected for execu on by the scheduler. This typically
occurs when the thread is wai ng for some resource or condi on.
Dead State: Finally, when the run() method completes execu on, the thread enters
the dead state. It is terminated or killed, and its life cycle ends. Addi onally,
invoking the stop() method will also terminate the thread, sending it to the dead
state.
@cseabhisheks
P a g e | 14
The main thread's priority is set to 5 by default, and each child thread will have the same priority as
its parent thread.
We have the ability to adjust the priority of any thread, whether it is the main thread or a user-
defined thread. It is advised to adjust the priority using the Thread class's constants, which are as
follows:
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
Thread(Runnable r): Constructs a new Thread object with the provided Runnable reference.
Thread(Runnable r, String str): Creates a new Thread object with the given Runnable
reference and name.
Daemon Threads:
Defini on: Daemon threads are background threads that run con nuously in the background,
providing services to other threads
Daemon threads are typically used for tasks that don't require ongoing maintenance or interac on
with the user interface.
Termina on: Daemon threads are automa cally terminated when all non-daemon threads have
finished execu ng
Event sources generate events. Examples include GUI components like bu ons, text
fields, etc
Event listeners handle specific types of events. s. For example, Ac onListener is used
to handle ac on events, MouseListener is used to handle mouse events, etc
Delega on: When an event occurs, the event source delegates the responsibility of
handling the event to the registered event listener.
The Delega on Event Model in Java is a design pa ern used for event handling,
where an event listener is registered with an event source to handle events
generated by that source.
Adapter Classes:
@cseabhisheks
P a g e | 16
Package
Main Func on Folders/Packagess
Packages
Errors in JAVA
@cseabhisheks
P a g e | 17
Excep on handling:
Excep on handling helps deal with unexpected problems that might pop up while a program
is running, like trying to read from a file that doesn't exist or dividing by zero.
Instead of crashing the program when it encounters a problem, excep on handling lets you
catch these issues and deal with them in a controlled way.
Benefits:
It stops the program from abruptly shu ng down, keeping it running smoothly.
Helps find and fix bugs: When something goes wrong, excep on handling gives you
clues about what happened, making it easier to fix.
Makes code easier to understand: By separa ng error-handling code from the main
program logic, it keeps things neat and dy, making the code easier to read and
maintain.
How it works: When an unexpected problem occurs, Java "throws" an excep on. Your code
can "catch" these excep ons and decide what to do next, whether it's trying again, showing
an error message, or something else.
try block: This is where you enclose the code that might cause an excep on
catch block: If an excep on occurs within the try block, the code inside the
corresponding catch block is executed. This is where you deal with the excep on
gracefully, like displaying an error message or trying an alterna ve approach.
throw: It is used to explicitly throw an excep on within a method or block of code.
throws: It is used in the method declara on to indicate that the method might throw
certain types of excep ons.
finally
@cseabhisheks
P a g e | 18
throws keyword
Built in Excep on
Built-in excep ons in Java are predefined classes provided by the language to handle common errors
and excep onal situa ons. Ex-
Operator Overloading
@cseabhisheks
P a g e | 19
String Handling
It refers to opera on perform on string object such as comparison substring extrac on
String Class: Represented by the String class, provides methods for string manipula on like
comparison and substring extrac on.
String: Strings are immutable in Java, meaning their values cannot be changed a er crea on.
StringBuffer and StringBuilder: Java provides mutable alterna ves to String for efficient
string manipula on. StringBuffer is thread-safe but StringBuilder is not. These classes are
preferred for frequent string modifica ons.
Exploring java.u l:
Java.u l is a package in Java that contains u lity classes and interfaces for various data
structures such as collec ons, date and me manipula on, and random number genera on.
Ex-
The Collec ons Framework in Java provides a unified architecture for represen ng and
manipula ng collec ons of objects. It includes interfaces along with their implementa ons in the
Java u l package."
@cseabhisheks