Module - 1 Introduction To OOP in Java
Module - 1 Introduction To OOP in Java
It’s not talking to a smart machine—it’s teaching the machine to become smart.
When you write a line of code, you’re training your assistant: 'This is how to
think.’
Over time, your assistant gets smarter—not with magic, but with logic.
3
But here’s the twist—
Intelligence doesn’t live in the machine alone.
It lives in two places:
In you—the one who imagines, questions, and decides what should happen.
And in the machine—which only acts because you taught it how.
4
Programming is the art of
turning human thought into
machine logic.
5
• OOP concepts: Objects, class,
Module 1- Encapsulation, Abstraction,
Inheritance, Polymorphism,
Introduction to message passing. Branching and
looping. Class, object, data
OOP in Java members, member functions
Constructors, types, static
members and functions Method
overloading Input and output
functions in Java, Buffered
reader class, scanner class,
Packages in java, types, user
defined packages.
6
7
8
Why Learn Java in 2025?
Timeless Power
25+ years strong — still a top choice for modern development.
Java Powers 20+ Domains
o Mobile Apps – Android, Kotlin (Spotify, Uber)
o Web Apps – JSP, Spring (Amazon, LinkedIn)
o Enterprise – Java EE, APIs (Banks, Salesforce)
o Cloud – Scalable services (Netflix, Dropbox)
o Big Data – Hadoop, Spark (Facebook, Airbnb)
o Blockchain – Hyperledger, secure DLT (IBM, Mastercard)
o IoT & Embedded – Java ME, real-time (Bosch, Sony)
o Games – jMonkey, LibGDX (Minecraft, EA)
o Education – E-learning platforms (Coursera, Khan)
9
History of Java
11
JAVA
(WORA)
12
What is Java?
• A programming language.
• As defined by Gosling in the Java Language Specification
• A platform
• A virtual machine (JVM) definition.
• Runtime environments in diverse hardware.
• A class library
• Standard APIs for GUI, data storage, processing, I/O, and networking.
13
Java Technology
• Development Tools
– The main tools you'll be using are the javac compiler, the java launcher (java),
and the javadoc documentation tool.
14
Java Technology, cont…
• Integration Libraries
– Application Programming Interface (API)
– Java RMI, and Java Remote Method Invocation over Internet Inter-ORB
Protocol Technology (Java RMI-IIOP Technology) enable database access.
15
Java Version History
• There are many java versions that has been released. Java SE 14.0. 2 is the latest release of Java
SE Platform.
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
• Java SE 9 (21st Sep, 2017)
• Java SE 10 (20th March, 2018)
21
The Java Virtual Machine
22
Compile-time Environment
▪ Java Source (.java): Human-written Java code.
23
Run-time Environment
● Bytecode Verifier: Validates bytecode security and structure.
● Runtime Data Areas: Memory areas for code execution (heap, stack,
etc.).
24
Java Development Kit
25
Java IDE Tools in 2025
26
Structure of a Java Program
27
Structure of a Java Program
28
Structure with Example
29
Java Editions & Components
Java SE / EE / ME
Java SE (Standard Edition): Core libraries for desktop/console apps
Java EE (Enterprise Edition): Server-side (Servlets, JSP)
Java ME (Micro Edition): Mobile/embedded devices
Component Description
JDK Java Development Kit – includes compiler, tools, and JRE
JRE Java Runtime Environment – runs Java programs (JVM + libraries)
JVM Java Virtual Machine – Executes bytecode on any platform
javac Java Compiler – Converts .java to .class (bytecode)
30
Java Code Execution Flow
•Write code in IDE
•Compile using javac
•Run on JVM via java command
31
Small Quiz
What does JDK stand for?
a) Java Development Kit
b) Java Deployment Kit
c) Java Debug Kernel
d) Java Data Kit
32
Small Quiz
Which part of Java executes
bytecode?
a) JDK
b) JRE
c) JVM
d) Compiler
Answer: JVM
33
Object Oriented Concept
• Object
• Class
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
34
Object Oriented Concept
Wikipedia defines OOP as a
“programming paradigm based on the concept of
objects, which may contain data, in the form of
fields, often known as attributes; and code, in the
form of procedures, often known as methods.”
The main idea behind OOP is to represent the data
and logic with objects instead of actions or
functions.
35
36
Class in Java
• A class in Java or any other Object-oriented Language is a blueprint for objects to
follow a specific schema defined in the class.
• Classes define the behavior for objects of its type. It represents a collection of
properties (data and functions) for all its objects.
• It supports a template for creating objects which bind code and data.
37
Object in Java
● An Object is the most fundamental entity in Java or any other Object-Oriented
Language.
● Objects represent real-life entities because each of them could have specific
behavior, identity, and data (attributes).
● In Java, the object is an offspring of its class. The class has properties to
reflect the object state and methods to represent the behavior.
● For example – A car, its state are – name, model no, shade,
manufacturer and its behavior can be – moving, blinking the headlights,
honking, etc. 38
Object in Java
For example – A car, its state are – name, model no, shade,
manufacturer and its behavior can be – moving, blinking the
headlights,honking, etc.
39
Class Declaration
Syntax: Example:
class classname class Circle
{ {
double radius = 1.0;//variable
//variables declaration
// Methods declaration double findArea() //method
{
} return radius * radius *
3.14159;
}
}
A class is a collection of fields (data) and methods (procedure or function)
that operate on that data.
40
Declaring/Creating Objects in a Single Step
Syntax: Example:
ClassName objectReference = new Circle myCircle = new Circle();
ClassName();
41
Prg1 : Example – Calculate Tax on some amount
class TaxCalc
{ float amt = 100.0;
float taxRate = 10.5;
void calculate()
{
float tax = amt * taxRate / 100;
S.o.p.(“The taxed amount is : ” + tax);
}
p.s.v.m.( )
{
TaxCalc t = new TaxCalc();
t . calculate();
}
}
42
Encapsulation
• Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed of several medicines.
• We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to set
and get the data in it.
43
Abstraction
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
44
Inheritance
● Inheritance is the OOP ability that allows Java classes to be derived
from other classes.
● The parent class is called a superclass and the derivatives are called
subclasses. Subclasses inherit fields and methods from their
superclasses.
45
Polymorphism
• Polymorphism in Java allows subclasses of a class to define their own unique
behaviours and yet share some of the same functionality of the parent class.
• In Greek language, Poly means many and morphs means forms.Therefore
Polymorphismtranslates to many forms.
• There are two kinds of polymorphism:
• Overloading
• Two or more methods with different signatures
• Overriding
• Replacing an inherited method with another having the same signature
46
Small Quiz :true / false
Encapsulation ensures that the
internal
details of a class are hidden from
outside.
Answer: True
47
Small Quiz :true / false
A car class having different drive()
methods
based on speed and terrain is an
example
of abstraction.
48
Program : Area of Circle
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
C:\Demo\>java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
49
Main method()
50
Before you start
• Install the Java SE Development Kit 6 (JDK 6).
• Install the Textpad editor which we will use to develop our applications.
51
Modifying the Path Environment variable
Windows Vista:
1.From the desktop, right click the My Computer icon.
2.Choose Properties from the context menu.
3.Click the Advanced tab (Advanced system settings link in Vista).
4.Click Environment Variables.
In the section System Variables,
find the PATH environment variable and select it.
Click Edit. If the PATH environment variable does not exist, click New.
5.In the Edit System Variable (or New System Variable) window,
specify the value of the PATH environment variable.
Click OK. Close all remaining windows by clicking OK.
52
Java Life Cycle
• Java programs normally undergo four phases
• Edit
• Programmer writes program (and stores program on disk)
• Compile
• Compiler creates bytecodes from program (.class)
• Load
• Class loader stores bytecodes in memory
• Execute
• Interpreter: translates bytecodes into machine language
53
Java Life Cycle
54
Hello world
To begin you need a text editor.
– Notepad, TextPad, …
– Create a new directory on C: name it JavaProjects.
• Open new file, save it as HelloWorld.java in new directory HelloWorld inside the JavaProjects
Directory.
class HelloWorld {
/*simple java application*/
public static void main(String args[]) {
System.out.println(“Hello World”); //displays a string }
}
• Note: the file name should have the same name as the class
55
Compiling and running
Assuming the HelloWorld.java is saved in the c:\JavaProjects\HelloWorld directory:
• Note: Type all code, commands, and file names exactly as shown. Both the
compiler (javac) and launcher (java) are case-sensitive
56
Closer Look
Three primary components: source code comments, the HelloWorld class definition, and
the main method.
• Comments are ignored by the compiler but are useful to other programmers.
– // text The compiler ignores everything from // to the end of the line.
• This is the string array that will contains the command line arrguments.
– The main method is the entry point for your application and will subsequently invoke all the other
methods required by your program.
• System.out.println("Hello World!");
– uses the System class from the API to print the "Hello World!" message to standard output.
58
Example, Prints.java
import java.lang.System;
Import java.lang.*;
class Prints
{
public static void main(String[] args)
{
System.out.print(":Haya ");
System.out.println("This Text in one line");
System.out.printf("\nFormated text;\n%s\t%s\n%s\t%d\n%s\t%d\n","Student","Mark","Ahmad",3,"Sami",5);
System.out.printf(" %x\n",15); // f
System.out.printf(" %o\n",15); // 17
}
}
>javac Prints.java
>java Prints
• %o for octal, %x for hexadicemal, %f for floating point representations.
59
Example, Prints.java
• Formatted output in Java : printf()
• This is the easiest of all methods as this is similar to printf() in C.
• Note that System.out.print() and System.out.println() take a single
argument, but printf() may take multiple arguments.
60
Example
• Name of class called identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
61
62
Different ways of taking Input from User
Now in the addition of two numbers program I want to take
values of a and b from user.
63
Command Line Argument
• Data entered by user at runtime will be stored in argument
array and this is known as command line argument.
• Data is accepted as string then converted into required data
type.
• There 2 ways of converting a string into primitive data type
1. Using static method of Integer class called parseInt()
2. Using non static method of Interger class called intValue( )
64
Example:Command Line Argument
class Largest
{
public static void main(String args[])
{
int a= Integer.parseInt (args[0]);
int b= Integer.parseInt (args[1]);
int c= Integer.parseInt (args[2]);
if((a>b) && (a>c))
System.out.println("Larget is ="+ a);
if((b>a) && (b>c))
System.out.println("Larget is ="+ b);
if((c>a) && (c>b))
System.out.println("Larget is ="+ c);
}
}
65
Output:Command Line Argument
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>javac Largest.java
66
Input Stream Reader/BufferedReader class
• An InputStreamReader is a bridge from byte streams to character
stream .
• It reads bytes and decodes them into characters using a specified
charset.
• The charset that it uses may be specified by name or may be given
explicitly, or the platform’s default charset may be accepted.
67
Input Stream Reader/BufferedReader class
• BufferedReader is a Java class that reads text from the input stream.
• It inherits the reader class and makes the code efficient since we can
read the data line-by-line with the readLine() method.
String readLine()
68
Input Stream Reader/BufferedReader class
• ➢points we have to keep in mind while working with
BufferedReader class in Java.
• Provides methods for reading byte, short, int,long, float, double, and
String data types from the Java console
• Scanner is in the java.util package
• Scanner parses (separates) input into sequences of characters called
tokens.
• By default, tokens are separated by standard white space characters
(tab, space, newline, etc.)
71
Scanner Class
72
import java.util.*;
import java.io.*;
class input
{
public static void main(String arg[])throws Exception
{
DataInputStream i=new DataInputStream(System.in);
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(ir);
try
{
System.out.println("Enter your surname:");
String name=in.readLine();
System.out.println("Enter your name:");
String n=i.readLine();
System.out.println("Welcome "+name);
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno:");
int r=sc.nextInt();
System.out.println("Your roll no is:"+r);
int x,y;
x=Integer.parseInt(arg[0]);
y=Integer.parseInt(arg[1]);
System.out.println("x="+x+"\ny="+y);
}
catch(Exception e){}
}
}
73
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>javac input.java
C:\Program Files (x86)\Java\jdk1.8.0_60\bin>java input 4 8
Enter your surname:
ansari
Enter your name:
fatima
Welcome ansari
Enter your rollno:
34
Your roll no is:34
x=4
y=8
74
Wrapper Classes
Wrapper classes define an instance variable of that primitive data type and also
provide useful constants and methods for converting between the objects and
the primitive data types
75
Java Control Structures
76
Control Structure Quest – “Choose Your
Codeventure”
Scenario 1: Traffic Light System
77
Control Structure Quest – “Choose Your
Codeventure”
Scenario 2: School Attendance
Correct answers: B
78
Control Structure Quest – “Choose Your
Codeventure”
Scenario 3: Amusement Park Entry
79
80
Constructors in Java
• All objects that are created must be given initial values.
• There are 2 approaches to assign values to an object
1. Using dot operator (tedious approach as to initialize all the
variables of all the objects)
2. Using method like getData() to initialize each object individually.
• It would be more concise to initialize an object when it is first created.
• Solution-------------Java Constructor
81
Constructors in Java
• A constructor is a special block of code that is called
when an object is created.
• Its main job is to initialize the object, to set up its
internal state, or to assign default values to its
attributes.
• This process happens automatically when we use the
"new" keyword to create an object.
82
Rules for writing Constructor
• Constructor(s) of a class must has same name as the class name
in which it resides.
• There are no “return value” statements in constructor.
• A constructor in Java can not be abstract, final, static and
Synchronized.
• Access modifiers can be used in constructor declaration to
control its
access i.e which other class can call the constructor.
83
Types of Java Constructors
•Default Constructor:
• A constructor is called "Default Constructor" when it doesn't have any
parameter.
• If we don’t define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class. And if we
write a constructor with arguments or no-argument then compiler does
not create default constructor.
• Default constructor provides the default values to the object like 0, null
etc. depending on the type.
84
Types of Java Constructors
•Parameterized Constructor:
• A constructor is called “Parameterized Constructor" when it takes
parameter.
• Arguments can be passed to constructors ,in order to initialize the
instance variables of an object.
85
Default Constructor (Example
import java.io.*;
class Student {
int num;
String name;
Student() // this would be invoked while object of that class created.
{ System.out.println ("Constructor is called"); }
}
Class MyClass {
public static void main (String[] args) {
Student obj= new Student(); // this would invoke default constructor.
System.out.println(obj.name);
System.out.println(obj.num); }
}
86
Parameterized Constructor (Example)
class Student{
int id; String name;
Student(int i, String n){
id = i; name = n; }
void display() {
System.out.println(id+" "+name);
} public static void main(String args[])
{ Student s1 = new Student(100,“Varun");
Student s2 = new Student(101,"Alia");
s1.display();
s2.display(); }
}
87
Method Overlaoding
• If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
• If we have to perform only one operation, having same
name of the methods increases the readability of the
program.
88
Method Overlaoding
• There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
89
1. Method Overloading by changing the no. of
arguments
lass Calculation
{
void sum(int a , int b) {
System.out.println(a+b); }
void sum(int a, int b, int c) {
System.out.println(a+b+c); }
public static void main(String args[]) { Output:
30
Calculation obj=new Calculation(); 40
obj.sum(10,10,10);
90
obj.sum(20,20);}
2) Method Overloading by changing data type of
argument
class Calculation{
void sum(int a,int b){
System.out.println(a+b);}
void sum(double a,double b){
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20); } } Output:
21.0
40
91
Why Method Overloading is not possible by
changing the return type of method?
class Calculation {
int sum(int a,int b) {
System.out.println(a+b); }
double sum(int a,int b) {
public static void main(String args[]){
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error
/* Here how can java determine which sum() method should be called
*/ } }
92
Can we overload main() method?
class Simple{
public static void main(int a){
System.out.println(a); }
public static void main(String args[]){
System.out.println("main()method invoked");
main(5); }
Output:
main() method invoked
5
93
Can we overload Constuctor
?
94
Constructor Overloading
95
Constructor Overloading (Example)
import java.io.*;
class Student{
Student(String name) // constructor with one argument
{ System.out.println("Constructor with one argument - String : " + name); }
Student(long id) // Constructor with one argument but with different type than previous..
{ System.out.println("Constructor with one argument :Long : " + id);}
class MyClass{
public static void main(String[] args) {
Student obj1= new Student(“SACHIN"); // Invoke the constructor with one argument of type 'String'.
Student obj2= new Student(“SOURAV", 36); // Invoke the constructor with two arguments
Student obj3= new Student(23 ); // Invoke the constructor with one argument of type 'Long'.
96
}}
Static Variables and Methods
The static keyword is used when a member variable of a class has to be
shared between all the instances of the class.
All static variables and methods belong to the class and not to any instance
of the class
97
Static Variables and Methods
When can we access static variable?
When a class is loaded by the virtual machine all the static variables and
methods are available for use.
Hence we don’t need to create any instance of the class for using the static
variables or methods.
Variables which don’t have static keyword in the definition are implicitly
non static.
98
Static Variables and Methods
You want to create a class member that will be used independently of any object
of the class
Also called class variables
One copy of a static variable is created per class
static variables are not associated with an object
static constants are often declared as public
To define a static variable, include the keyword static in its definition:
Syntax:
accessSpecifier static dataType variableName;
Example:
public static int countAutos = 0;
99
Static Variables and Methods
Also called class methods
Often defined to access and change static variables
static methods cannot access instance variables:
static methods are associated with the class, not with any object.
static methods can be called before any object is instantiated, so it is possible that
there will be no instance variables to access.
100
Static Variables and Methods
static Non-static Method
Method
Access instance variables? no yes
101
Example: Static Variables and Methods
class staticDemo{
public static int a = 100; /* All instances of staticDemo have this variable as a common `
variable*/
public int b =2 ;
public static showA(){
System.out.println(“A is “ + a);
}
}
class StaticClass{
public static void main(String args[]){
staticDemo.showA();
staticDemo.a = 35; /* when we use the class name, the class is loaded, direct access to a static variable without any instance*/
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after creating an instance.
staticDemo.showA();
}
}Output: ??
102
Packages in Java
◻ Packages enable grouping of functionally related classes
◻ Package names are dot separated, e.g., java.lang.*;
◻ Package names have a correspondence with the directory structure
◻ Packages Avoid name space collision. There can not be two classes
with same name in a same Package But two packages can have a
class with same name.
◻ Exact Name of the class is identifed by its package structure.
▪ << Fully Qualified Name>>
java.lang.String ;
java.util.Arrays;
java.io.BufferedReader ;
java.util.Date
103
Packages in Java
Types of Packages
• User defined package: The package we create is called
user-defined package.
104
Built in Packages in Java
105
User defined Packages in Java
package <package name>;
106
User defined Packages in Java
◻To Compile:
javac -d directory javafilename.java
◻To Run:
java packagename.classname
◻The -d switch specifies the destination where to put the generated class
file
◻If you want to keep the package within the same directory, you can use .
(dot).
107
User defined Packages in Java
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package"); } }
◻To Compile: e:sources> javac -d c:classes Simple.java
◻To Run: To run this program from e:source directory, you need to set classpath of the
108