Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
140 views44 pages

OOPS Unit 1 Notes Aktu

The document provides an overview of Object-Oriented Programming (OOP) with Java, detailing its history, applications, features, and differences from C++. It explains key concepts such as classes, objects, inheritance, data types, and various Java components like JDK, JRE, and JVM. Additionally, it includes examples of Java syntax, operators, and methods for taking user input.

Uploaded by

Anil Kaushik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views44 pages

OOPS Unit 1 Notes Aktu

The document provides an overview of Object-Oriented Programming (OOP) with Java, detailing its history, applications, features, and differences from C++. It explains key concepts such as classes, objects, inheritance, data types, and various Java components like JDK, JRE, and JVM. Additionally, it includes examples of Java syntax, operators, and methods for taking user input.

Uploaded by

Anil Kaushik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

OOPS With Java

Unit: - 1

 Introduction
In 1991, James Gosling, Mike Sheridan, and Patrick Naughton
started the "Green Project" at Sun Microsystems to develop a
platform-independent language.

Initially, the language was called Oak.


Later, it was renamed Java, inspired by Java coffee, which
Gosling and his team drank while working.

In 2010, Oracle Corporation acquired Sun Microsystems and


took control of Java.

 Application of Java
i. Java is the primary language for Android app
development.
ii. Java is extensively used in building dynamic websites
and web applications.
 Features of Java

i. Simple
Java is easy to learn and it’s syntax is quite simple and
easy to understand. The confusing concepts of C++
are either left out in java.

ii. Object Oriented


Java follows the object-oriented programming principles:
 Encapsulation – Wrapping data and code together.
 Inheritance – Acquiring properties from a parent
class.
 Polymorphism – Ability to use a method in
different forms.
 Abstraction – Hiding implementation details from
the user.

iii. Robust

 Automatic Garbage Collection to free up


memory.
 Exception handling to catch runtime errors.

iv. Platform Independent


"Write Once, Run Anywhere" (WORA)
– Code written in Java can run on Linux OS any
platform without modification.
Java code compile Byte code MacOS

Windows
OOS

v. Secure

Java programs always run in a java runtime


environment with almost null interaction with system
OS.

vi. Multi-Threading

Java multi-threading feature makes it possible to write


program that can do many tasks simultaneously (at
the same time).
 Difference between C++ and JAVA

C++ JAVA
i. It is platform i. It is platform
dependent. independent.
ii. It supports concepts ii. It does not support
of pointer and multiple concepts of pointer and
inheritance. multiple inheritance.
iii. It uses a compiler. iii. It uses a compiler and
interpreter.
iv. It supports call by iv. It supports only call
value and call by by value.
reference.
v. Runtime error v. Runtime error
detection mechanism is detection mechanism is
the responsibility of the the responsibility of the
programmer. system.
vi. Memory vi. Memory
management done management is done by
using a pointer. a system.
vii. It allows procedural vii. It allows only object -
programming as well as oriented programming.
object - oriented
programming.
 Difference between JDK, JRE & JVM

JVM
Java virtual machine is a virtual machine that provides
runtime environment to execute java byte code. The JVM
does not understand java code directly, that is why you need
to compile your *.java files to obtain *.class files that contains
the bytecode understand by the JVM.

JRE
Java runtime environment provides the libraries, java virtual
machine and other components to run applets and
applications written in java programming language.

Libraries
JAVA VIRTUAL
MACHINE +
(JVM) Other
Components.

JAVA RUNTIME ENVIRONMENT (JRE)

JDK
Java development kit is a subset of JRE, and contains
everything that is in the JRE, plus tools such as the compilers
and debuggers necessary for developing applications.

JAVA RUNTIME Tools like


ENVIRONMENT Compilers,
Debuggers etc.
(JRE)

JAVA DEVELOPMENT KIT (JDK)

 Tokens
Tokens are each individual elements of a programming
language.
Types:-
1. Keywords
Keywords are the reserved words that are specific to a
programming language.
Ex:- int, char, double, for, else, private, protected, etc.

2. Identifiers
Identifiers are names given to any function/class/variable etc.
There are some certain rules for naming identifiers:
1. The first letter of identifier must start with an alphabet and
underscore.
2. There should be no special symbol except an underscore.
3. There should not be any space between an identifier
name.
4.Keywords can’t be used as identifier name.
5.Upper case and lower case identifiers are different.

3. Literals (Constants)
Constant values assigned to variables.
Ex:- int x=25; // 25 is literal

4. Operators
Symbols used to perform operations.
Ex:- +, -, /, etc.

5. Separators
Symbols used to separate code blocks or statements.
Ex:- ; , () , {} , etc.

 Datatypes in Java
Datatypes defines the type of data a variable will store.
Ex:- int, float, char, etc.
 Variables
Variables are used to store values. Values stored in it can be
changed at any point of time as and when required.
Ex: int a;

 Increment and Decrement Operator in Java


Increment operator (++) or decrement operator (--) used to
increase the value of variable by one or decrease the value of
the variable by one respectively.
Ex
int a=4;
a++; // The value of a will become 5
int b=9;
a--; // The value of b will become 8

Prefix Increment/Decrement Operator


When ++ or -- operator is place before the variable, then it is
called prefix increment or decrement.
Prefix operator first evaluates the value and then performs
the work.
Ex
Int a=4;
System.out.println(++a); // 5
System.out.println(a); // 5

Postfix Increment/Decrement Operator


When ++ or – operator is place after the variable, then it is
called postfix increment or decrement.
Postfix operator first performs the work and then evaluates
the value.
Ex:-1
Int a=5;
System.out.println(a++); // 5
System.out.println(a); // 6
Ex:-2
int a=5;
int b=6;
int c=7;
System.out.println(++a + ++b + ++c); // 21
System.out.println(a++ + b++ + c++); // 21
System.out.println(a); // 7
System.out.println(b); // 8
System.out.println(c); // 9

Ex:-3
int a=5;
a++; // 6
++a; // 7
a; // 7

 Logical Operators
There may be some requirements where two or more
conditions have to be joined together.
In such places, Logical operators are used to combine
multiple conditions.
Three main logical operators are
1. AND Operator (&&)
This returns true if all the conditions associated with this is
true.

NOTE: 0  F
1T

X Y X&&Y
0 0 0
0 1 0
1 0 0
1 1 1

2. OR Operator (I I)
This returns true when any one condition associated with this
is true.

X Y XIIY
0 0 0
0 1 1
1 0 1
1 1 1

3. NOT Operator (!)


This reverses the condition. It is used to reverse the input.

X !X
0 1
1 0

 Structure of Java
keyword

class Hello class name

{ Keywords

public static void main(String[] args)


{
System.out.println(“Hello World “);
}
}

Class  Class is a keyword used to declare class in java.


Public  It is an access specifier. Public means this function is
visible to all.
Static  static is again a keyword used to make a function
static. To execute a static function you do not have to create
object of the class. The main() method here is call by JVM
without creating any object for class.

My First Program
Step 1: - Open Notepad and write this program in notepad.
class Hello
{
public static void main(String args[])
{
System.out.println("Hello JMS!");
}
}

Step 2: - Save this file in c drive  Program files Java jdk


version  bin and then save with the name as same as class
name hello.java
Step 3: - For run this program open cmd
cd\ (ROOT DRIVE)
cd program files
cd java
dir (for finding version)
cd jdk-23
cd bin
dir (check file hello.java)
javac hello.java (compile successfully)
java hello (Run Successfully).

Set Path in Java


First copy the path where the files are saved.
Right click on my pc  Properties  Advanced System
Settings  Environment Variables  User variable (Edit Path)
 new (Paste)  OK  OK OK.

Task
Q1 Write a program to print value of a and b the value of a
is 4 and value of b is 9.
Solution
class Demo
{
public static void main(String args[])
{
int a,b;
a=5;
b=10;
System.out.println("value of a="+a);
System.out.println("value of b="+b);
}
}

 Taking Input in Java


There are the two ways to taking input from user. The first
one is to use BufferedReader Class and another one is to use
Scanner Class.
Through BufferedReader Class
BufferedReader is a class which is found in “io” package. So in
order to use bufferedReader class we import “io” package in
our program.
In BufferedReader class there is a function “readLine()” which
is used to read input.
NOTE:- Collection Of Classes.

Through Scanner Class


Scanner is a class which is found in “util” package. So in order
to use Scanner Class we import “util” package in our
program.
There is function called next(), nextInt(), nextFloat() etc which
is used to read user input.
Ex: -
imort java.util.Scanner;
class Add
{
Public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println(“Enetr first number”);
a=sc.nextInt();
System.out.println(“Enetr Second number”);
b=sc.nextInt();
c=a+b;
System.out.println(“Addition=”+c);
}
}

Q WAP to print area of rectangle by taking input from the


user.
import java.util.Scanner;
class Demo
{
public static void main(String args[])
{
int len,br,area;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Length");
len=sc.nextInt();
System.out.println("Enter Breadth");
br=sc.nextInt();
area=len*br;
System.out.println("Area of rectangle="+area);
}
}
 Class and Object in Java
Class
A class is a blueprint or template for creating objects. It
defines the data members (variables) and methods
(functions) that the objects created from the class will have.
Object
An object is an instance of a class. It represents a specific
implementation of the class with real values.

Q WAP for adding two number using class and object.


import java.util.Scanner;
class add
{
int a,b; //class variable
void getdata()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number");
a=sc.nextInt();
System.out.println("Enter Second Number");
b=sc.nextInt();
}
void putdata()
{
System.out.println("Addition is "+ (a+b));
}
public static void main(String args[])
{
add aa=new add();
aa.getdata();
aa.putdata();
}
}

 Passing argument to a function in a class and object


import java.util.Scanner;
class reverse
{
int n;
void getdata(int i)
{
n=i;
}
void putdata()
{
int rev=0;
while(n>0)
{
rev=(rev*10)+n%10;
n=n/10;
}
System.out.println("Reverse="+rev);
}
public static void main(String args[])
{
int m;
reverse aa=new reverse();
Scanner sc=new Scanner (System.in);
System.out.println("Enter number to find reverse");
m=sc.nextInt();
aa.getdata(m);
aa.putdata();
}
}
 Static Data Members
Static data members are not the part of any object as it is the
part of the class.
Although Static members are not the part of object, instead
all the objects can use its value.
Static members are kept separately hence its value is unique
for all the objects.
Example:
class Student
{
int roll;
String name;
Static String Collegename=”JMS College”;
}

 Static Member Functions


Static member functions are not the part of any object it is
the part of class.
It can be invoked directly using the class name.
Static member functions can used only static data variables.
Example
Class Student
{
int roll;
String name;
Static String Cname=”JMS”;
Student(int x, String y)
{
roll=x;
name=y;
void display()
{
System.out.println(“Roll=”+roll + “Name=”+ name + “College
name=”+ Cname);
}
Static void change()
{
Cname=”ABC”;
}
}
Class demo
{
Public static void main(String args[])
{
Student aa = new Student(101,”Rahul”);
aa.display();
Student.change();
}
}

 Constructor in Java

A constructor in Java is a special method used to


initialize objects. It is called automatically when an
object is created using the new keyword.

Characteristics of Constructors
 Has same name as the class.
 No return type, not even void.
 Can be parameterized or non-parameterized.
 Automatically called at the time of object creation.
 Can be overloaded (multiple constructors with different
parameters).

Types of Constructors in Java

a) Default Constructor
Automatically provided by Java if no constructor is
defined.
Example
class Car {
// No constructor defined here
}

Car c = new Car(); // Default constructor is used

b) No-Argument Constructor
Defined explicitly, takes no arguments.
Example
class Car {
Car() {
System.out.println("No-argument constructor");
}
}

c) Parameterized Constructor
Takes arguments to initialize the object with values.
Example
class Car {
String model;
int year;

// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
}
 Array in Java

An array in Java is a collection of elements that stores


multiple values of the same data type in a single
variable.
It helps you manage data efficiently, especially when
dealing with fixed-size lists of items like numbers,
names, or objects.

Example:
Suppose you want to store marks of 5 students.
Instead of writing:
int mark1, mark2, mark3, mark4, mark5;
You can use an array:
int[] marks = new int[5];

Declaration
Syntax:
dataType[] arrayName;
// or
dataType arrayName[];

Initialization
int[] numbers = new int[5];

 String in Java
In Java, a String is a sequence of characters enclosed in
double quotes (").
Key Characteristics:
 Strings are immutable (cannot be changed once
created).
 The String class provides many useful methods (e.g.,
length(), toUpperCase(), charAt()).
 Strings are used to store textual data like names,
sentences, messages, etc.

How to Create a String Variable in Java


There are two main ways to create a string:

1. Using String Literal


String name = "John";

2. Using the new Keyword


String name = new String("John");

 Inheritance
Inheritance is one of the four core concepts of Object-
Oriented Programming (OOP).
In Java, inheritance allows one class (called the child or
subclass) to inherit fields and methods from another
class (called the parent or superclass).

Syntax
class Parent
{
void display()
{
System.out.println("This is the parent class");
}
}

class Child extends Parent


{
void show()
{
System.out.println("This is the child class");
}
}

public class Test {


public static void main(String[] args) {
Child obj = new Child();
obj.display(); // inherited from Parent
obj.show(); // defined in Child
}
}

Types of Inheritance in Java


1. Single Inheritance
One class inherit another.
In java, all classes implicitly inherit from the object
class, which serves as the root of the class hierarchy.

2. Multiple Inheritance
Java does not support multiple inheritance of classes,
which means a class can not directly inherit from more
than one class.
However multiple inheritance can be achieved through
one interfaces.

3. Multileve Inheritance
A inherits B, B inherits C

4. Hierarchical Inheritance
Multiple classes inherit the same parent.

 Superclass
A superclass also known as base class or parent class.
A superclass is inherited by another class.
It contains common fields and methods that can be
reused by its subclasses.

 Subclass
A subclass is also known as child class.
A class that inherits from another class using the
extends keyword is called subclass.
It inherits the properties and behaviours (methods and
variables) of the superclass and can also have its own
unique features.

 Method Overriding and Method Overloading

Method Overriding
Method Overriding in Java occurs when a subclass
provides a specific implementation of a method that is
already defined in its superclass.

Example: Method Overriding in Java


class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Output: Dog barks (method of
subclass)
}
}

Method Overloading
Method Overloading in Java means having multiple methods
in the same class with the same name but different
parameters (type, number, or order).

Example:
public class Calculator {

// Method 1: No parameter
void add() {
System.out.println("No numbers to add");
}

// Method 2: One parameter


void add(int a) {
System.out.println("Sum = " + a);
}

// Method 3: Two parameters


void add(int a, int b) {
System.out.println("Sum = " + (a + b));
}
// Method 4: Two double parameters
void add(double a, double b) {
System.out.println("Sum = " + (a + b));
}

public static void main(String[] args) {


Calculator calc = new Calculator();

calc.add(); // No numbers to add


calc.add(5); // Sum = 5
calc.add(10, 20); // Sum = 30
calc.add(3.5, 4.2); // Sum = 7.7
}
}

 Encapsulation

Encapsulation in Java is one of the fundamental


principles of Object-Oriented Programming (OOP).
It refers to the bundling of data (variables) and
methods (functions) that operate on the data into a
single unit, typically a class, and restricting direct access
to some of the object's components.
Key Points:
1. Data Hiding:
Encapsulation allows you to hide the internal state of
the object from the outside world. You expose only
what is necessary via public methods (getters and
setters).

2. Access Modifiers:
Fields (variables) are usually declared private, and
access to them is provided through public getter and
setter methods.

3. Improves Security:
It prevents unauthorized parts of the program from
making unintended changes to the object’s data.

4. Makes Code Maintainable: You can change the internal


implementation without affecting other parts of the
code that use the class.

Example

class demo
{
private int value;
public void setValue(int x)
{
value=x;
}
public int getValue()
{
return value;
}
}
class Main
{
public static void main (String[] args)
{
demo dd = new demo();
dd.setValue(100);
System.out.println(dd.getValue());
}
}

 Polymorphism
Polymorphism in Java is one of the core concepts of Object-
Oriented Programming (OOP). It literally means “many
forms”.
In Java, polymorphism allows objects to be treated as
instances of their parent class rather than their actual class,
enabling flexible and reusable code.

Types of Polymorphism in Java


1. Compile-Time Polymorphism (Static Binding / Method
Overloading)
 Achieved by method overloading.
 The method to be executed is determined at compile
time.
 Same method name but different parameter list (type,
number, or order).
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // calls int
version
System.out.println(calc.add(2.5, 3.5)); // calls double
version
}
}

2. Run-Time Polymorphism (Dynamic Binding / Method


Overriding)
 Achieved by method overriding.
 The method to be executed is determined at runtime.
 Requires inheritance and dynamic method dispatch (a
superclass reference pointing to a subclass object).
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

class Main {
public static void main(String[] args) {
Animal a; // reference of parent class

a = new Dog();
a.sound(); // Output: Dog barks

a = new Cat();
a.sound(); // Output: Cat meows
}
}
 Abstraction and Interfaces

Abstraction
Abstraction is one of the four main pillars of Object-Oriented
Programming (OOP). It means hiding the internal
implementation and showing only the essential features of
an object.
In Java, abstraction is achieved using:
1. Abstract classes
2. Interfaces

1. Abstract Class
An abstract class:
 Cannot be instantiated (you can't create its object).
 Can have abstract methods (no body) and concrete
methods (with body).
 Used when classes share some common behaviour but
also need to define their own specific implementations.
Example:
abstract class Animal {
abstract void sound(); // abstract method

void eat() { // concrete method


System.out.println("Animal eats food");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}
2. Interface
An interface:
 Is a pure abstraction — it contains only abstract
methods (Java 8+ allows default and static methods
too).
 A class implements an interface, not extends it.
 Interfaces are great for multiple inheritance and
contract-based programming.
Example:
interface Vehicle {
void start();
}

class Car implements Vehicle {


public void start() {
System.out.println("Car starts with key");
}
}

 Packages in Java
A package in Java is like a folder that helps you organize your
classes, interfaces, and sub-packages logically and avoid
name conflicts. It’s a way to group related types together.
Why Use Packages?
1. Organize code neatly.
2. Avoid naming conflicts (e.g., two classes with the same
name in different packages).
3. Control access using access modifiers (like public,
protected).
4. Reusability – you can import and reuse code across
projects.
Examples:
 java.util (e.g., ArrayList, HashMap)
 java.io (e.g., File, InputStream)
 java.lang (automatically imported, e.g., String, Math)

 CLASSPATH in java
The classpath in Java is a parameter that tells the Java
compiler (javac) and Java Virtual Machine (java) where to
look for user-defined classes and packages when
compiling or running Java programs.
Think of it as a path to all the .class files or JARs your
application depends on.

Purpose of setting the classpath


1. Locating classes and resources
2. Handling dependencies
3. Supporting Modular development
4. Avoiding class name conflicts
5. Class loading and resolution

 JAR (Java Archive) Files


JAR stands for Java Archive.
It’s a compressed file format (like .zip) used to bundle
multiple .class files, resources (like images or config
files), and metadata into one file for:
 Easy distribution
 Deployment
 Execution of Java applications

Steps to Create a JAR File


Step 1: Write Java Source Code
Create the required .java files. Example:
public class Main {
public static void main(String[] args) {
System.out.println("Hello from JAR!");
}
}

Step 2: Compile Java Files


Use the javac command to compile .java files into .class files:
javac Main.java

Step 4: Create the JAR File


Use the jar tool provided by the JDK.
For a simple JAR
jar cf MyApp.jar Main.class

Step 5: Run the JAR File


If the JAR file is executable, use the following command to
run it:
java -jar MyApp.jar

 Difference between Static Import and Regular Import

Static Import Regular Import


1. Used to import static 1.Used to import classes
members (fields and or packages.
methods) from a class.
2. import static 2.import
3. package.className.*; 3.package.ClassName.;
4. Allows you to use static 4.Enables you use the
members without the class name without the
class name prefix package prefix.
5. java import static 5.java import java
java.lang.Math.*; .util.List;

You might also like