JAVA - MCA 2024 - UNIT 1-Student
JAVA - MCA 2024 - UNIT 1-Student
UNIT I 15 hours
Java Buzzwords – Class Fundamentals – Declaring Objects – Introducing
Methods – Constructors – This keyword – Garbage Collection –
Overloading Methods – Argument Passing – Recursion – Access Control
Understanding static – final. Inheritance Basics – Using super – Method
overriding – Dynamic Method Dispatch – Using Abstract Classes – * Final
with Inheritance * – Object class.
An overview of Java or History of Java
1. Java is an object-oriented programming language developed by Sun Microsystems in 1991.
2. It was created by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan as part of a
research initiative known as the Green project.
3. Initially, James Gosling referred to it as "Greentalk."
4. The original design was intended for small, embedded systems in electronic devices like TVs, VCRs, freezers, and
washing machines.
5. However, this idea was abandoned due to technical challenges.
6. The language was later renamed "Oak" after the robust oak tree.
7. In 1995, Oak was renamed "Java" because "Oak" was already trademarked by Oak Technologies.
8. James Gosling named it "Java" after the Indonesian island known for its coffee, while he was drinking coffee near
his office.
9. Java is just a name and does not stand for anything.
10. The internet and the World Wide Web started to gain global popularity in 1995.
11. Sun Microsystems promoted Java as the internet programming language.
12. Java became popular as a web technology that adds dynamic functionality to web pages.
13. In January 2010, Oracle acquired Sun Microsystems, and since then, Oracle has been responsible for
maintaining and distributing Java.
The Evolution of Java or Java’s Lineage
✓ B → C → C++ → Java
Features of Java or JAVA BUZZ WORDS
Sun described Java as
"A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable,
high-performance, multi-threaded and dynamic language.“
1. Simple
2. Object-oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-neutral
8. Portable
9. High performance
10. Multithreaded
11. Dynamic
1.Simple
✓ Java was designed such that it is easy for the programmer to learn and use.
✓ It inherits syntax from C and OOPs concept from C++, so it is very easy to learn if programmer knows
C and C++.
✓ Java technology has eliminated complex features like Operator overloading, Multiple inheritance,
pointers.
2.Object Oriented
✓ Everything in Java is an object. It provides the features of abstraction, encapsulation, inheritance and
polymorphism.
✓ Anything in Java is embedded into a class.
✓ Almost all data types are objects.
3. Distributed
✓ Distributed applications run on multiple computers and communicate over a network.
✓ Java supports creating such applications, allowing programs on one machine to easily access
resources (files, Java objects, etc.) on another machine over the internet.
✓ Java offers a comprehensive set of libraries for network programming, including support for
Remote Method Invocation (RMI) and protocols like TCP/IP and UDP.
4.Compiled and Interpreted
✓ Java is compiled as well as interpreted programming language.
✓ Java source code is compiled into bytecode, which is a low-level, platform-independent
representation of the code.
✓ The bytecode is machine-independent and can run on any machine that has a Java interpreter,
which is part of the Java Virtual Machine (JVM).
5.Robust
✓ Robustness refers to reliability.
✓ Java is considered robust because it employs strong memory management with automatic
garbage collection.
✓ It features an exception handling mechanism to manage errors and unexpected situations
gracefully.
✓ Java includes built-in type checking that verifies code both at compile time and runtime.
6.Secure
Java implements various security mechanisms to protect your system from harmful
programs.
✓ It is secure because it has eliminated the concept of pointers.
✓ Java includes a dedicated security manager in the JVM to handle application security
needs.
✓ It features a Bytecode Verifier that checks code fragments for illegal code.
✓ Java's security mechanisms are designed to be difficult to breach.
7.Architecture-neutral/Platform Independent
✓ Java is designed to be independent of specific hardware or operating systems.
✓ It achieves this through the concept of bytecode.
✓ Bytecode allows a Java application to run on any hardware and operating system.
✓ This platform independence enables Java to follow the WORA (Write Once, Run
Anywhere) principle.
✓ Essentially, Java's .class files can execute seamlessly across various operating
systems.
8.Portable
✓ Portability in programming means a program compiled on one machine can run on
any machine worldwide without changes.
✓ Java programs exemplify portability because they can move between different
architectures, hardware configurations, operating systems, and system setups
seamlessly.
✓ This inherent portability makes Java an ideal choice for applications that need to run
across diverse environments without requiring modifications.
9.High Performance
✓ Java code is compiled into bytecode for the JVM.
✓ The JVM dynamically translates frequently used bytecode into machine code using JIT
compilation, improving performance.
✓ Java efficiently executes code with the help of bytecode and JIT compilation.
✓ Standard libraries in Java provide optimized data structures and algorithms, further
enhancing performance.
✓ The JIT compiler, part of the JVM by Sun Microsystems, speeds up Java program
interpretation by compiling bytecode on-the-fly.
✓ It stores optimized machine code for future execution without requiring recompilation.
✓ Sun's Java HotSpot Performance Engine includes a compiler that optimizes frequently
used code segments, significantly boosting overall Java program performance.
10.Multithreaded
✓ Multithreading allows multiple threads to run concurrently within the same process.
✓ Each thread operates independently and can share memory with other threads.
✓ It facilitates parallel execution of different parts of a program, optimizing CPU usage.
✓ Java applications can perform multiple tasks simultaneously using separate threads,
avoiding the need to wait for one task to finish before starting another.
✓ For example, applications like Microsoft Word utilize multithreading for tasks such as
typing, spell check, grammar check, auto-save, and autocomplete, enhancing user
productivity and efficiency.
11. Dynamic
✓ Java compiles source code into .class files.
✓ These .class files are dynamically loaded into memory at runtime.
✓ Java applications utilize runtime libraries and resources during execution.
✓ Java can leverage efficient functions from C/C++.
✓ Installing a new version of a library automatically updates all programs that use it.
Types of Java programs
1. An application program is a software program that is designed to perform specific tasks on a local
computer, such as processing data, reading and writing files, or solving equations
2. An applet is a small Java program that is designed to run within a web browser and add
interactivity to web pages. It runs in a web browser and works on the client-side
Note: Oracle has announced that Applets are deprecated in JDK 9 and will be removed from the JDK
in the future.
3. A servlet is a Java program that runs on a web server and works on the server-side to process HTTP
requests and generate dynamic web content.
Note:
✓ Application Program –Executed by the Java interpreter.
✓ Applet- Java enabled web browser.
✓ Servlet- web server
How a Java application program works
1. Write Java code: Java application programs are written using a text editor or an integrated
development environment (IDE) such as Eclipse, NetBeans etc.
2. Compile Java code: The Java source code is compiled into bytecode using the Java compiler called
“javac”
3. Run the Java application: The compiled program can now be executed by the JVM using the "java"
command followed by the name of the main class in the program.
Hardware and
Programmer
Operating System
2. Running: Use the JVM (java command) to execute the compiled bytecode.
Example: To run the compiled MyFile.class, use:
java MyFile
✓ There are no restrictions on the number of classes in the file.
Starting with Java 11, you can run a single-file source code program
without needing to compile it first.
This feature simplifies the development process, especially for small
programs
Writing a Single-File Source Code Program
1. Create a Java file: Write your Java code in a file with a .java
extension.
2. Run the Java file: Use the java command followed by the
filename(with the .java extension) to run the program.
✓ For example, to run a file named "Hello.java", we would run the
command "java Hello.java“
Note: In Java 11, you can still use the traditional method of compiling
with javac and running with java:
Execute Java single file program Without Compilation – Example:
class Welcome {
public static void main(String[] args) {
System.out.println(" Welcome to Java" );
System.out.println(" This code runs without needing to be compiled beforehand");
System.out.println(" Java version is " + System.getProperty("java.version"));
}
}
I:\Java11>java Welcome.java
Welcome to Java
This code runs without needing to be compiled beforehand
Java version is 16.0.1
Example 2
// Define a class named HelloWorld
class HelloWorld {
// Define a method named greet
public void greet() {
System.out.println("Hello, World!");
}
// Define the main method in the same class
public static void main(String[] args) {
// Create an object of the HelloWorld class
HelloWorld obj = new HelloWorld();
// Call the greet method using the object
obj.greet();
}
}
Output
I:\Java11>java HelloWorld.java
Hello, World!
Console Input or Keyboard Input (interactive input)
• In Java, input from the keyboard is obtained via the standard input
stream, represented by System.in.
• Java provides classes in the java.io package for input/output operations
and exception handling.
We may also give values to variables interactively through the keyboard using the read() or
readLine() method.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
Byte b=Byte.parseByte(br.readLine());
short s= Short.parseShort(br.readLine());
int i=Integer.parseInt(br.readLine());
long l=Long.parseLong(br.readLine());
float f=Float.parseFloat(br.readLine());
double d=Double.parseDouble(br.readLine());
char c = (char) br.read();
Reading Characters Reading Strings
To read string we have to use readLine()
read() method is used with BufferedReader
function with BufferedReader class's object.
object to read characters. As this function
returns integer type value has we need to
Example 2. Read a String
use typecasting to convert it into char
// Program to get & display your name
type.
// Illustrates Interactive input
Example 1. Read a Character import java.io.*;
import java.io.*; class dispname
class readchar{ {
public static void main(String args[ ]) throws public static void main(String args[])
IOException { throws IOException
{ BufferedReader br = new
char c; BufferedReader( new
BufferedReader br=new BufferedReader(new InputStreamReader(System.in) );
InputStreamReader(System.in)); System.out.println("Enter your name :");
c = (char) br.read(); //Reading character String name = br.readLine();
System.out.println(c); System.out.println("\nYour name is " +
name);
}
}
} }
Example 3:Conversion of strings to numbers
// Program to add two numbers
// Illustrates Conversion of strings to numbers
import java.io.*;
class Add
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br = new BufferedReader( new
InputStreamReader(System.in) );
System.out.print("Enter the first number ");
a = Integer.parseInt( br.readLine() );
System.out.print("Enter the second number ");
b = Integer.parseInt(br.readLine());
c = a+b;
System.out.println("Result of addition = " + c);
}
}
2.Using Scanner Class
✓ Prior to Java 1.5, obtaining input from the console involved several steps.
✓ However, with the introduction of the Scanner class in Java 1.5, this process has been greatly simplified.
✓ The java.util package provides the Scanner class, which facilitates reading input from various sources, including the
keyboard.
✓ To utilize the Scanner class in a Java program, it needs to be imported:
import java.util.Scanner;
Next, create an instance of the Scanner class to read input from the standard input stream (i.e., the console).
The basic syntax for this is:
Scanner sc = new Scanner(System.in);
✓ This creates a new Scanner object called "sc" that reads input from the standard input stream (i.e. the console).
✓ This line initializes a new Scanner object named sc, which reads input from the console.
The Scanner class offers methods to read different types of input, such as strings, integers, doubles, and booleans,
making it a versatile tool for handling user input in Java applications.
Example:
Scanner sc = new Scanner (System.in);
int i = sc.nextInt();
System.out.println("You entered " + i);
✓ This example reads a single int from System.in and outputs it to System.out. It does not check that the user actually
entered an int.
commonly used Methods of the Scanner class
Method Description
Note: The import java.io.*; statement is not necessary for using the Scanner class for input operations.
Only import java.util.Scanner; is required.
Scanner class example
The Scanner Class can be used as an alternative to the Buffered Reader, used in traditional Java.
//finding area and perimeter of the circle
import java.util.Scanner;
class Find {
public static void main(String[] args) {
double area, perimeter, radius;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Radius: ");
radius = sc.nextDouble();
perimeter = 2 * Math.PI * radius;
area = Math.PI * Math.pow(radius, 2);
System.out.printf("Perimeter\t: %f\n", perimeter);
System.out.printf("Area\t\t: %f\n", area);
sc.close();
}
}
Enter the Radius: 23
Perimeter : 144.513262
Area : 1661.902514
3.Using Command Line Arguments
✓ Command line arguments in Java are values or data passed to a Java program during its execution
from the command line.
✓ These arguments are stored in a string array, args, which is passed to the program's main() method.
✓ This array is declared as a parameter in the main() method.
✓ Command line arguments allow input data to be supplied at runtime, rather than being hardcoded
into the program.
✓ A Java application can accept any number of arguments(Stings) from the command line.
✓ Users enter these arguments after the class name when invoking the application.
✓ The args.length property returns the number of command line arguments provided.
Program1 Program2
public class Num1 {
// Display all command-line arguments. public static void main(String[] args) {
class CommandLine { if (args.length < 2) {
public static void main(String[] args) { System.out.println("Please enter two numbers as command line
for (int i = 0; i < args.length; i++) { arguments.");
return;
System.out.println("args[" + i + "]: " + }
args[i]); int a = Integer.parseInt(args[0]);
} int b = Integer.parseInt(args[1]);
} System.out.println("Entered numbers are: " + a + " " + b);
}
// Swap the numbers without using a third variable
a = a + b;
b = a - b;
Output a = a - b;
java CommandLine.java jama mohamed System.out.println("Numbers after exchange: " + a + " " + b);
college trichy }
args[0]: jama }
args[1]: mohamed java Num1.java 25 45
args[2]: college Entered numbers are: 25 45
args[3]: trichy
Numbers after exchange: 45 25
console output or screen output
1.System.out.print(); This method prints the specified text to
✓ In Java, output to the standard output (screen) is managed
the console without a newline character at the end.
through System.out, an instance of the PrintStream class that
represents the standard output stream. Syntax: System.out.print("text");
✓ This functionality is provided by the System class within the Example:
java.lang package. System.out.print("Hello, ");
System Class: Within java.lang, the System class includes a System.out.print("world!");
static variable out, which is of type PrintStream. Output: Hello, world!
Accessing System.out: Because out is static, it can be accessed 2.System.out.println(); This method prints the specified text to
directly using System.out. the console with a newline character at the end
Output Methods: Methods like print(), println(), and printf() Syntax: System.out.println("text");
from the PrintStream class facilitate printing data to the console, Example1:
supporting both plain and formatted output.
System.out.println("Hello, ");
1. System.out.println("text"): Prints the text followed by a
System.out.println("world!");
newline character.
Hello, world!
2. System.out.print("text"): Prints the text without appending
a newline character.
3. Formatting Output: Use System.out.printf() for 2.System.out.println(); // Write a blank line
formatted output using format specifiers (%s, %d, %f, etc.).
3.System.out.printf(); public class PrintfExample {
public static void main(String[] args) {
✓ The printf() method in Java, introduced in JDK 5.0, is
String name = "Raja";
indeed similar to the printf() function in C.
int age = 30;
✓ The printf() method in Java enhances the capabilities
double salary = 2500.75;
of standard output, providing a powerful tool for
// Using printf to format output
formatted text output, similar to its counterpart in
System.out.printf("Name: %s, Age: %d, Salary: %.2f\n",
the C programming language.
name, age, salary);
Syntax: System.out.printf("format", arg1, arg2, ...); // More examples
The format string can contain placeholders that start with int number = 123456789;
%. The placeholders are replaced with the corresponding System.out.printf("Formatted number with commas: %,d\n",
arguments. number);
output double pi = Math.PI;
java PrintfExample.java System.out.printf("Pi value: %.4f\n", pi);
Name: Raja, Age: 30, Salary: 2500.75 // Formatting dates
Formatted number with commas: 123,456,789 int day = 4, month = 7, year = 2024;
System.out.printf("Date: %02d-%02d-%d\n", day, month,
Pi value: 3.1416
year);
Date: 04-07-2024 }
}
Formatting Numeric Output using the System.out.printf( ) Method
Here are some of the most commonly used format specifiers in System.out.printf():
1. %d - Format as a decimal integers such as byte, int, short, long.
2. %f - Format as a floating-point number
3. %s - Format as a string
4. %c - Format as a character
5. %b - Format as a Boolean value (true or false)
6. %t - Format as a date/time value
7. %e - Format as a scientific notation
8. %x - Format as a hexadecimal integer
9. %o - Format as an octal integer
Note:
1. The output of a printf statement is right-justified by default.
2. To force the output to be left-justified, you can use the format specifier flag. If flag is set to ‘-’
(negative), then the output of the result is left justified.
3. System.out.printf( ) does not print a newline character by default – it is similar to System.out.print( ). Include %n
in the format string to do this.
Example: double pi = Math.PI;
System.out.printf("Pi value: %.4f%n", pi);
Introducing Classes
Class Fundamentals
✓ A class in Java defines a new data type. For example, a class like Box introduces a new
type named Box.
✓ A class consists of data variables (properties) and methods (code) that manipulate those
data.
✓ It serves as a blueprint or template for creating objects.
✓ An object is a specific instance of a class.
✓ When creating an object, a specific instance of that class is generated with its unique set
of values for properties.
✓ The purpose of a class is to describe an object.
✓ (ie) A class is a description of an object, and an object is an instance of a class.
✓ Classes form the foundation of object-oriented programming (OOP).
✓ In Java, classes are fundamental; every program must use at least one class.
✓ A java program is defined by using one or more classes
class classname {
The General Form of a Class
type instance-variable1; ✓Variables defined within a class are called instance variables.
type instance-variable2; ✓The code within a class is contained within methods, which
// ... define its behavior.
type instance-variableN;
✓Variables defined within a class are called instance variables
type methodname1(parameter-list)
{
because each instance of the class (that is, each object of the
// body of method class ) contains its own copy of these variables.
} ✓Collectively, the methods and variables defined within a class
type methodname2(parameter-list) are called members of a class
{ ✓The words Object and Instance are often used interchangeably.
// body of method
} Attributes And Behavior
// ... ✓A Java class consists of two types of information: attributes and
type methodnameN(parameter-list) behavior
{ ✓A class defines the properties and behaviors for the objects.
// body of method
Attributes: These are properties defined by variables in the class.
}
}
Behavior: Also known as operations, these are defined using
methods in the class.
Introducing Methods
Classes usually consist of two things:
•instance variables and
•Methods.
A Java method is sequence of statements that carry out specific task
General form of a method definition:
datatype methodname (parameter-list) Example:
{ double volume(double w, double h,
// method body double d)
{ return w*h*d;
}
}
✓ datatype specifies the type of data returned by the method. This can be any valid types
including class types. If method does not return any value, return type is void.
✓ methodname must be a legal identifier other than those already declared for other items
within the current scope.
✓ paramter-list is the sequence of type and identifier pairs separated by commas. If no
parameters are present, paramter-list can be empty.
✓ Methods having return type other than void, must have a return statement to return a value.
Example 1:
Examples Example 3
class Box { class Account
double width; {
double height; double balance;
void deposit( double amount )
double depth;
{
// display volume of a box balance += amount;
void volume() { }
System.out.print("Volume is ");
System.out.println(width * height * depth); double withdraw( double amount )
} {
} if (balance >= amount)
{
Note: A class defines a new type of data. In this case, the balance -= amount;
new type is called Box.
return amount;
Example 2: }
class Rectangle else
{ int length, width; return 0.0;
}
int area() double getbalance()
{ {
return length *width; return balance;
} }
}
int perimeter()
{ return 2*(lenth+width);
}
}
Creating Objects in Java
✓ Objects in Java are created dynamically using the new operator.
✓ This process is known as instantiation.
Syntax:
ClassName objectName; // Declare a reference variable of type ClassName
objectName = new ClassName(); // Allocate memory and create an object of ClassName
// OR
ClassName objectName = new ClassName(); // Combine declaration and instantiation
Explanation
ClassName: Replace ClassName with the actual name of the class you want to instantiate.
objectName: This is the name of the reference variable that will refer to the object.
new: The new keyword dynamically allocates memory for an object of ClassName.
(); Parentheses after ClassName can include arguments if the class has a constructor that accepts
parameters.
Creating Objects
Example:
Box myBox = new Box(); creates a new object of the Box class and assigns it to
the reference variable myBox.
Box: This is the class name from which a new object is being created.
myBox: This is the reference variable that will hold the memory address of the
newly created Box object.
new: This keyword is used to allocate memory and create a new instance (object)
of the Box class.
Box(): This is the constructor of the Box class. It initializes the new object. In this
case, with no arguments provided (()), it invokes a default constructor that
initializes a default Box object.
Accessing Object Members
✓ In Java, we can access the members (variables and methods) of an object using the dot (.) operator.
Objectname.varibale name;
Objectname.methodname (parameter – list)
• Ex:
1) Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
vol = mybox1.volume( );
Constructors Methods
1. A constructor is used to initialize the instance 1. A method is used for any general purpose
variables of a class. processing or calculations.
2. A constructor’s name and class name should 2. A method has a unique name that identifies
be same. behavior
3. A constructor is called at the time of creating 3. A method can be called after creating the object.
object. 4. A method can be called several times on the
4. A constructor is called only once per object. object.
Complete Examples
// Class definition //Main class – A class contains the main() method
String getAccountNumber() {
account.withdraw(200.0);
return accountNumber;
System.out.println("New balance after withdrawal: " +
} account.getBalance());
double getBalance() { }
return balance; }
} output
void deposit(double amount) { I:\Java11>java MainBank
balance += amount; Account number: 123456789
} Balance: 1000.0
void withdraw(double amount) { New balance after deposit: 1500.0
balance -= amount; New balance after withdrawal: 1300.0
}
}
The this keyword
✓ In Java, the this keyword is a reference variable that refers to the current object
✓ The this keyword in Java is particularly useful within methods and constructors to refer to
and access the object's own members, such as fields (variables) and methods.
To Refer to Instance Variables: When a method parameter has the same name as an instance
variable, this helps differentiate between them.
Instance Variable Hiding:
✓ The this keyword in Java is commonly used to distinguish between instance variables (fields
of a class) and formal variables (parameters declared in methods) when they share the same
name.
Note: Static methods, or class methods, do not have a this reference
//Example 1: instance and formal variables are different
class Box {
double w = 5, h = 5, d = 5; // instance variables
// Constructor with formal parameters w1, h1, d1
Box(double w1, double h1, double d1) {
// Assigning values from formal parameters to instance variables
w = w1;
h = h1;
d = d1;
}
// Method to calculate volume based on instance variables w, h, d
double volume() {
return w * h * d;
} Output:
}
class BoxTest1 {
Volume is:6.0
public static void main(String args[]) {
// Creating an instance of Box with dimensions 1x2x3
Box b = new Box(1, 2, 3);
// Printing the calculated volume
System.out.println("Volume is: " + b.volume());
}
}
// Example 2: instance and formal variables are same
class Box{
double w=5,h=5,d=5; // instance variables with default values
// Constructor with parameters having the same names as instance variables
Box(double w,double h,double d){
w=w; When a formal variable has the
h=h;
d=d; same name as an instance variable,
} the formal variable hides the
double volume(){ instance variable.
return w*h*d;
} Output:
}
class BoxTest2{
Volume is:125.0
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
//Example 3: ’this’ hides the instance variables
class Box{
double w=5,h=5,d=5; // instance variables with default values
// Constructor with parameters having the same names as instance variables
Box(double w,double h,double d){
this.w=w;
this.h=h; this can be used to resolve any name
this.d=d; collisions that might occur between
}
instance variables and formal variables.
double volume(){
return w*h*d;
} Output:
}
class BoxTest2{
Volume is:6.0
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Garbage Collection
✓ Garbage in Java refers to objects that are no longer reachable or used by the program.
✓ Garbage collection is the automatic process where the Java Virtual Machine (JVM) reclaims memory
occupied by unreferenced objects, making it available for new objects.
✓ Unlike languages such as C++, where dynamically allocated memory must be manually released using delete,
Java automatically handles memory deallocation through its garbage collector.
✓ Objects in Java are automatically destroyed by the garbage collector when they are no longer referenced by
any variable in the program, eliminating the need for explicit destruction as in C++.
✓ The garbage collector is an integral part of the Java Runtime Environment (JRE), ensuring efficient memory
management.
✓ Garbage collection occurs periodically during the execution of a Java program to optimize memory usage
and performance. It is triggered primarily when the JVM detects a shortage of available memory.
✓ Although Java provides System.gc() as a method to suggest garbage collection, its actual invocation and
timing are JVM-specific and do not guarantee immediate destruction of unreferenced objects.
In java, there are three ways in which the references to an object can be released to make it eligible for Garbage Collection.
(ie) Objects can be unreferenced in three different ways
1. By anonymous object: Anonymous Object: Anonymous objects in Java are created without assigning them to any
reference variable. They are typically used for immediate method invocation or initialization without retaining access to
the object afterward.
new Student(); // Creates an anonymous Student object
After creation, an anonymous object cannot be accessed again because it lacks a reference variable. Despite this, it
occupies memory until eligible for garbage collection.
2. Null Reference: When a reference variable is assigned null, it releases its association with the object it previously
referenced. This action marks the object as unreferenced and available for garbage collection.
Student s = new Student();
s = null; // Releases the reference to the Student object
Here, s no longer points to any object (null), allowing the previously referenced Student object to be considered for
garbage collection.
3.Assigning a Reference to Another Object: When one reference variable is assigned to another, the original object
referenced by the first variable becomes unreachable if no other references exist to it.
Student s1 = new Student();
Student s2 = new Student();
s1 = s2;
After s1 = s2;, the original object referenced by s1 becomes unreachable and can be considered for garbage collection if no
other references exist to it.
Examples
1. class GarbageCollectionDemo {
public static void main(String args[]) {
Integer i = new Integer(5); 2. class GarbageCollectionExample {
System.out.println(i); public static void main(String[] args) {
i = new Integer(6); // Create two objects
System.out.println("Integer(5) can be recycled."); String s1 = new String("Hello");
System.out.println(i); String s2 = new String("World");
} // Set s1 to null
} s1 = null;
//s1 to null to indicate that we are no longer using this object.
J:\>java GarbageCollectionDemo // Call garbage collector
5 System.gc();
Integer(5) can be recycled. // Print the value of s2
6 System.out.println("s2 value: " + s2);
Note: }
The Integer object created with a value of 5 can be }
garbage collected because it is no longer referenced by
any active part of the program after the i reference
variable is reassigned to a new Integer object with a
value of 6.
finalize( ) method
✓ In Java, garbage collection automatically frees memory used by objects but does not manage non-Java resources
such as files, network connections, or database connections.
✓ To clean up such resources before an object is destroyed, you can define a finalize() method in the object's class.
✓ This method is called by the JVM before garbage collection to perform cleanup tasks.
✓ Finalize() is a method of the object class that can be invoked/called every time before the object is garbage
collected and the purpose of finalize() method is to perform cleanup processing.
1. protected is a specifier in Java that restricts access to the finalize() method only within its class or subclasses
2. Programmers have no control over when or if the finalize() method will be invoked by the garbage collector
3. The finalize() method can lead to significant performance penalties. Due to these issues, it has been deprecated
since Java 9 and should be used cautiously when necessary.
4. Instead of relying on finalize(), Java developers are advised to use try-with-resources statements or implement the
AutoCloseable interface to properly manage resources. These modern approaches offer more predictable and efficient
resource cleanup mechanisms.
Overloading Methods
✓In Java, it's possible to define multiple methods within the same class that share the same
name but have different parameter declarations.
✓This practice is called method overloading and is a way Java implements polymorphism.
✓When methods are overloaded, Java determines which version to execute based on the
type and/or number of arguments provided during the method call.
✓Unlike the return type, which can vary between overloaded methods, Java solely relies on
the arguments to differentiate between them.
✓When invoking an overloaded method, Java selects the version whose parameters match
the arguments passed in the call.
✓This flexibility allows developers to create methods with the same name that operate
differently based on the inputs provided, enhancing code versatility and readability.
// Class FunctionOverload demonstrating method overloading
Example
class FunctionOverload {
// Main class Overloading to demonstrate method overloading
// Method to add two integers
class Overloading {
void add(int a, int b) {
public static void main(String args[]) {
int sum = a + b;
// Creating an instance of FunctionOverload class
System.out.println("Sum of a + b is " + sum);
FunctionOverload obj = new FunctionOverload();
}
// Method to add three integers
// Calling different overloaded methods with various
void add(int a, int b, int c) {
arguments
int sum = a + b + c;
obj.add(1, 2); // Calls add(int a, int b)
System.out.println("Sum of a + b + c is " + sum);
obj.add(45, 22, 33); // Calls add(int a, int b, int c)
}
obj.add(11.5, 22.5); // Calls add(double a, double b)
// Method to add two double variables
obj.add("Welcome", " to Java"); // Calls add(String s1,
void add(double a, double b) { String s2)
double sum = a + b; }
System.out.println("Sum of a + b is " + sum); }
} I:\javaprogram 2024>javac Overloading.java
// Method to concatenate two strings I:\javaprogram 2024>java Overloading
Sum of a + b is 3
void add(String s1, String s2) { Sum of a + b + c is 100
String s = s1 + s2; Sum of a + b is 34.0
System.out.println("Concatenation of two strings: " + s); Concatenation of two strings: Welcome to Java
Constructor overloading
System.out.println("Before call: " + ob.a + " " + ob.b); I:\javaprogram 2024>java Test2.java
// Call the method, which modifies the object Before call: 14 20
ob.set(ob); Within the method: 28 10
System.out.println("After call: " + ob.a + " " + ob.b); After call: 28 10
}
}
class Recursion
{
public static void main(String args[])
{
int number = 5;
Factorial f = new Factorial();
System.out.println("Factorial of number "+number+" is : "+ f. factorial(5) );
}
} In this program, once the main method calls
the factorial(5), it calls factorial(4) and it goes
Output on until factorial(0) is called which returns 1 to
F:\>javac Recursion.java factorial(1) which further returns it's result to
F:\>java Recursion factorial(2) and so on until factorial(5) is
Factorial of number 5 is : 120 reached which evaluates the final result and
returns to main method.
Access Control Modifiers
✓ In Java, access control modifiers are keywords that define the visibility and accessibility of classes,
methods, and fields (variables)within a program.
✓ There are four access control modifiers in Java
1. public: is an access modifier in Java that allows classes, methods, and variables to be accessible
from anywhere in the program.
2. private: A private method, or variable is only accessible within the same class.
3. protected: A protected method or variable can be accessed by classes and subclasses in the
same package, as well as by subclasses in a different package
4. default or package: A class, method, or variable with no access control modifier specified (i.e.,
no public, private, or protected keyword) is only accessible within the same package.
✓ A Top level class can use just two of the four access control levels (default or public), members can use all four
✓ Nested Classes and Class Members: Can use private, default, protected, and public.
Access Control Modifiers
1.Public Access Modifier
✓ A member is declared public using public keyword.
✓ This modifier doesn't put any restriction, it can be accessed anywhere.
✓ A public member is accessible everywhere, no matter whether it's in same package or in different package.
✓ Any member can be declared with public modifier whether it's a variable, method, constructor, class, interface or
anything else.
2.Private Access Modifier
✓ A member is declared private using private keyword.
✓ This is the most restrictive access modifier in java.
✓ A private member is accessible within it's own class only.
✓ Variables, methods and constructors can be declared as private.
✓ Top level classes and interfaces can not be declared as private.
3.Protected Access Modifier
✓ A member is declared protected using protected keyword.
✓ A protected member can be accessed within it's own package as well as by a subclass in another package.
✓ This access modifier can be used with variable, method and constructors.
✓ Top level classes and interfaces can not be declared as protected.
4.Default Access Modifier
✓ When a member is declared without any access modifier, it is called default modifier.
✓ A default member is accessible within the package only, that is why it is also known as package modifier.
✓ Any member can be declared with no modifier whether it's a variable, method, constructor, class, interface or
anything else.
Table of access modifier scope
Subclass in
Access Within
Within Class different Everywhere
Modifier package
package
private Yes No No No
A nested class
This class has access to all the members of its outrer class
No class other than the outer class “knows” of the existence of this class
85
Advantages of Inheritance
1. Code Reusability: Inheritance allows subclasses to inherit methods and behaviors from their superclass,
avoiding code duplication and promoting reuse across multiple subclasses.
2. Extensibility: Subclasses can add new methods from the superclass, enhancing functionality without
altering the original code.
3. Maintenance: Changes made to the superclass automatically apply to all subclasses, reducing redundancy
and ensuring consistent behavior across related classes.
4. Overriding (Run time Polymorphism): Subclasses can have methods with the same name and parameters
as those in their superclass. These methods in the subclass provide specific functionalities that may differ
from those in the superclass.
5. Data Hiding: Base class can hide some of its data and code by making them private.
Types of inheritance
F:\>javac variableoverride.java
F:\>java variableoverride
Value num in the sub class 110
Value num in the super class 100
2. super can be used to invoke immediate super class method
Method Overriding
✓ Method overriding in Java refers to the process of writing a method in a subclass with
the same signature (name, parameters, and return type) as a method in its superclass.
✓ When an overridden method is called from within a subclass, it always refers to the
version of that method defined by the subclass.
✓ This means the version of the method defined by the superclass is hidden or
overridden.
✓ If you need to access the superclass version of an overridden method, you can use the
super keyword.
✓ This allows you to explicitly invoke the superclass's method implementation.
✓ Method overriding occurs only when the names and the type signatures (parameters
and return type) of the methods are identical in both the superclass and subclass.
✓ If these criteria are not met, the methods are considered overloaded, not overridden.
✓ In overriding parent class method is called overridden method and Child class method
is called overriding method
Note: We cannot override the method declared as final and static.
// Parent class
Example – Method overriding
class Parentclass {
// Method in the parent class
void display() {
System.out.println("Parent class method");
}
}
// Subclass extending Parentclass
class Subclass extends Parentclass {
// Overriding method from Parentclass
void display() {
System.out.println("Child class method");
}
// Method to demonstrate method calls
void printMsg() {
display(); // Calls the overridden display() method in Subclass
super.display(); // Calls the display() method in Parentclass using
super
}
}
// Main class F:\>javac Methoverride.java
class Methoverride {
public static void main(String args[]) {
Subclass obj = new Subclass(); F:\>java Methoverride
obj.printMsg(); // Calls printMsg() in Subclass Child class method
} Parent class method
}
3.super() can be used to invoke immediate super class constructor.
✓ Subclass constructor is used to initialize the instance variables of the subclass as well
as in the super class
✓ Super is a keyword used to call the super class constructor from sub class
constructor.
The general form is super(argument list);
Rules to be followed
i) super keyword is used only within a subclass constructor.
ii) Super() must be the first statement executed inside a subclass constructor
iii) The arguments in the super() must match the arguments in the constructor defined
in the superclass.
//Using super to call superclass constructors class SBAccount extends Account {
class Account { double rate;
int accountNumber, balance; // Constructor to initialize accountNumber, balance, and rate
// Calls the superclass constructor to initialize accountNumber and balance
SBAccount(int accountNumber, int balance, double rate) {
// Constructor to initialize accountNumber
super(accountNumber, balance); // Call the superclass constructor
and balance
this.rate = rate;
Account(int accountNumber, int balance) { }
this.accountNumber = accountNumber; // Method to display the interest rate
this.balance = balance; void displayInterestRate() {
} System.out.println("Interest Rate = " + rate);
}
// Method to credit amount to the balance }
void credit(int amount) { class AccountDemo {
balance = balance + amount; public static void main(String[] args) {
} // Create an SBAccount object with accountNumber 1001, balance 5000, and
interest rate 6.5
// Method to debit amount from the balance SBAccount obj1 = new SBAccount(1001, 5000, 6.5);
void debit(int amount) { obj1.credit(2000);
balance = balance - amount; obj1.debit(1000);
obj1.displayBalance();
}
// Display the interest rate
obj1.displayInterestRate();
// Method to display the current balance }
void displayBalance() { }
System.out.println("Balance = " + balance); OUTPUT:
}
} Balance =6000
Interest Rate =6.5
Differences between method overloading and method overriding.
✓ Dynamic method dispatch or run time polymorphism is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
✓ Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.
✓ Runtime polymorphism is the ability of a single method call to behave differently based on the
actual object type that invokes the method.
✓ In java, a superclass reference can refer to objects of its class or any of its subclasses(also
known as upcasting).
✓ Java uses this fact to resolve calls to overridden methods at run time.
✓ That is, an overridden method is called through the reference variable of a super class.
✓ When an overridden method is called using a superclass reference, the actual method that
gets executed is determined at runtime based on the object being referred to, not the
reference variable's type.
✓ This means that the Java Virtual Machine (JVM) looks at the actual object type and calls the
corresponding method of that object's class.
Example: class Dyanamic {
class Bank { public static void main(String[] args) {
double getInterestRate() { Bank bank; // Reference variable of a super class Bank
return 0.0; // Assigning the reference variable to a SavingsAccount object
} bank = new SavingsAccount();
} // Calls the getInterestRate method of SavingsAccount
System.out.println("Savings Account Interest Rate: " + bank.getInterestRate() + "%");
class SavingsAccount extends Bank {
//Overriding // Assigning the reference variable to a FixedDeposit object
double getInterestRate() {
bank = new FixedDeposit();
return 4.0;
// Calls the getInterestRate method of FixedDeposit
}
System.out.println("Fixed Deposit Interest Rate: " + bank.getInterestRate() + "%");
}
class FixedDeposit extends Bank { // Assigning the reference variable to a RecurringDeposit object
//Overriding bank = new RecurringDeposit();
double getInterestRate() { // Calls the getInterestRate method of RecurringDeposit
return 6.5; System.out.println("Recurring Deposit Interest Rate: " + bank.getInterestRate() + "%");
} }
} }
class RecurringDeposit extends Bank {
//Overriding I:\javaprogram 2024>java Dyanamic
double getInterestRate() { Savings Account Interest Rate: 4.0%
return 5.0; Fixed Deposit Interest Rate: 6.5%
} Recurring Deposit Interest Rate: 5.0%
}
class Triangle extends Figure {
// Using run-time polymorphism. Triangle(double a, double b) {
class Figure {
super(a, b);
double dim1;
double dim2; }
Figure(double a, double b) { // override area for right triangle
dim1 = a; double area() {
dim2 = b; System.out.println("Inside Area for Triangle.");
} return dim1 * dim2 / 2;
double area() { }
System.out.println("Area for Figure is
undefined."); }
return 0;
} class FindAreas {
} public static void main(String args[]) {
class Rectangle extends Figure { Figure f = new Figure(10, 10);
Rectangle(double a, double b) { Rectangle r = new Rectangle(9, 5);
super(a,b);
}
Triangle t = new Triangle(10, 8);
// override area for rectangle Figure figref;
double area() { figref = r;
System.out.println("Inside Area for System.out.println("Area is " + figref.area());
Rectangle."); figref = t;
return dim1 * dim2;
System.out.println("Area is " + figref.area());
}
} figref = f;
System.out.println("Area is " + figref.area());
Inside Area for Rectangle. }
Area is 45 }
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
Abstract Methods &Abstract Classes
✓ Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
✓ In Java, abstraction is achieved through abstract classes or interfaces
✓ In Java, a superclass can define a general form shared by all subclasses, with each subclass
providing its specific implementation.
✓ In Java, an abstract class defines methods that subclasses must implement.
Abstract methods
In Java, an abstract method is a method that is declared but not implemented in an abstract
class.
Abstract methods are used to define the structure or contract that subclasses must follow.
Syntax:
abstract type name (parameter-list);
class FinalDemo{
public static void main(String args[]){
final int i=20;
System em.out.println(i);
//i=i+1; can’t assign a value to final variable i
//System.out.println(i); cannot assign a value to final variable i
}
}
To prevent overriding
✓ A method declared with the final keyword cannot be overridden by subclasses.
✓ This is useful when you want to ensure that the implementation of a method remains unchanged in any subclass.
✓ (ie) A final method cannot be overridden by subclasses.
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}