0% found this document useful (0 votes)
10 views143 pages

Java Object-Oriented Programming Course

The document outlines a course on Object Oriented Programming using Java for the academic year 2025-2026, covering Java programming fundamentals, the comparison between traditional and object-oriented approaches, and the advantages of object-oriented methods. It details Java's history, features, programming paradigms, and the differences between JDK, JRE, and JVM, along with examples of Java syntax and operators. The document serves as a comprehensive guide for understanding Java programming concepts and practices.

Uploaded by

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

Java Object-Oriented Programming Course

The document outlines a course on Object Oriented Programming using Java for the academic year 2025-2026, covering Java programming fundamentals, the comparison between traditional and object-oriented approaches, and the advantages of object-oriented methods. It details Java's history, features, programming paradigms, and the differences between JDK, JRE, and JVM, along with examples of Java syntax and operators. The document serves as a comprehensive guide for understanding Java programming concepts and practices.

Uploaded by

xyz.randomly1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Department

of
Information Technology
1

Course Title: Object Oriented Programming Year : 2025-2026


using Java

Course Code: 4CSPL2023 Credits: 2-0-1-3


Module–I: Java Programming

Java programming : the history of Java, Java’s magic: the byte


code, the evolution of Java, Java keywords, data types, user-
defined and pre - defined data types, variables, constants, scope
and life time of variables, operators, operator hierarchy,
expressions, type conversion and casting, programming
constructs in Java, console i/o, objects and classes, constructors,
static attributes and methods, access control.
COMPARISION OF TRADITIONAL AND OBJECT ORIENTED
APPROACH

TRADITIONAL APPROACH OBJECT-ORIENTED APPROACH

[Link] of procedures/functions [Link] of objects

[Link] is on operation [Link] on data

[Link] from one phase to another is difficult [Link] from one phase to another is easier

[Link] Duration of the project [Link] Duration of project

[Link] Complexity [Link] complexity and redundancy


WHY AN OBJECT-ORIENTATION?

OO methods enables to create set of objects that work together to produce software that better
model the problem domains than similar systems produced by traditional techniques.

The systems are easier to adapt to:


▪ changing requirements,
▪ easier to maintain,
▪ more robust,
▪ promote greater design and,
▪ code reuse.
▪ OO development allows us to create modules of functionality
▪ Once objects are defined, it can be taken for granted that they will perform their desired
functions.
REASONS FOR WHY OBJECT ORIENTATION WORKS?

[Link] LEVEL OF ABSTRACTION.

▪ The top-down approach supports abstraction at the function level.

▪ The object-oriented approach supports abstraction at the object level.

▪ Since objects encapsulate both data (attributes) and functions (methods), they work at a higher level of
abstraction.

▪ The development can proceed at the object level and ignore the rest of the system for as long as necessary.

▪ This makes designing, coding, testing, and maintaining the system much simpler.
REASONS FOR WHY OBJECT ORIENTATION WORKS?

2. SEAMLESS TRANSITION AMONG DIFFERENT PHASES OF SOFTWARE DEVELOPMENT.

• The traditional approach to software development requires different styles and methodologies for each step of the
process.

• Moving from one phase to another requires complex transition of perspective between models that almost can be in
different worlds.

• The transition not only can slow the development process but also increases the size of the project and the chance for
errors introduced in moving from one language to another.

• The object oriented approach essentially uses the same language to talk about analysis, design, programming, and
database design.

• This seamless approach reduces the level of complexity and redundancy and makes for clearer, more robust system
development.
REASONS FOR WHY OBJECT ORIENTATION WORKS?

3. ENCOURAGEMENT OF GOOD PROGRAMMING TECHNIQUES.


▪ A class in an OO system carefully delineates between its interface (specifications of what the class can do) and the
implementation of that interface (how the class does what it does).

▪ The routines and attributes within a class are held together tightly.

▪ In a properly designed system, the classes will be grouped into subsystems but remain independent; therefore, changing
one class has no impact on other classes and so the impact is minimized.

▪ By raising the level of abstraction from the function level to the object level and by focusing on the real-world aspects
of the system, the OO method tends to promote clearer designs; which are easier to implement, and provide for better
overall communication.
REASONS FOR WHY OBJECT ORIENTATION WORKS?

4. PROMOTION OF REUSABILITY.
• Objects are reusable because they are modeled directly out of a real-world problem domain.

• Each object stands by itself or within a small circle of peers (other objects).

• Within this framework, the class does not concern itself with the rest of the system or how it is going to be used within a
particular system.

• This means that classes are designed generically, with reuse as a constant background goal.

• The object orientation adds inheritance, which is a powerful technique that allows classes to be built from each other;

• Therefore, only differences and enhancements between the classes need to be designed and coded.

• All the previous functionality remains and can be reused without change.
What is Java?

Java is a programming language and a platform.


Java is a high level, robust, object-oriented and
secure programming language.
History of Java

• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of Sun Microsystem engineers called Green
Team.
• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt
• Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
• After that, it was called Oak and was developed as a part of the Green project.
• In 1995, Oak was renamed as "Java"
Why Java Programming named "Java"?

• Java was callead Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.

• In 1995, Oak was renamed as "Java"

• Java is an island in indonesia where he first coffee was produced ( called java
coffee)
Java Version History

[Link] Alpha and Beta (1995) [Link] 1.0 (23rd Jan 1996)
[Link] 1.1 (19th Feb 1997) 4.J2SE 1.2 (8th Dec 1998)
5.J2SE 1.3 (8th May 2000) 6.J2SE 1.4 (6th Feb 2002)
7.J2SE 5.0 (30th Sep 2004) [Link] SE 6 (11th Dec 2006)
[Link] SE 7 (28th July 2011) [Link] SE 8 (18th Mar 2014)
[Link] SE 9 (21st Sep 2017) [Link] SE 10 (20th Mar 2018)
[Link] SE 11 (September 2018) [Link] SE 12 (March 2019)
[Link] SE 13 (September 2019) [Link] SE 14 (Mar 2020)
[Link] SE 15 (September 2020) [Link] SE 16 (Mar 2021)
[Link] SE 17 (September 2021) [Link] SE 18 (to be released by March 2022)
Features of Java
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Java Programming paradigms
• Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior.
• This is controlled by the following four paradigms
• OOPS concepts

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Bytecode

• The Java compiler translates Java programs into byte‐code.


Once compiled to byte‐code, a Java program can be used on any computer,
making it very portable machine.

• The Java Virtual Machine (JVM) translates the byte code into machine language
The evolution of Java

• In 1995, Java 1.0 was introduced.


With 211 classes and interfaces.
• In December 1998, Java 2 platform was announced.
Applies to current Java technology

• Java application program interface (API) contains the predefined classes and
interfaces for developing Java programs.
Java API
There are 3 editions of the Java API:
• Java 2 standard edition (J2SE)
Client‐side standalone applications or applets.
• Java 2 Enterprise Edition (J2EE)
Server‐side applications, such as Java servlets and JavaServer Pages.
• Java 2 Micro Edition (J2ME) Java 2 Micro Edition (J2ME)
Mobile devices, such as cell phones or pda.
Difference between JDK, JRE, and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides a runtime environment in which Java bytecode can
be executed.

The JVM performs the following main tasks:

Loads code
Verifies code
Executes code
Provides runtime environment
JRE
The Java Runtime Environment is a set of software tools which are used for
developing Java applications.
It is used to provide the runtime environment.
It is the implementation of JVM.
JDK
The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

Standard Edition Java Platform


Enterprise Edition Java Platform
Micro Edition Java Platform
Simple Java Program
class Simple
{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
To compile: javac [Link]
To execute: java Simple
Valid Java main() method signature

public static void main(String[] args)


public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)

Invalid Java main() method signature

public void main(String[] args)


static void main(String[] args)
public void static main(String[] args)
What happens at runtime?
Variables
• Variables are containers for storing data values.
• Variables are used to represent values that may be changed in the program.

Rules for naming the variable:

• Its is a sequence of characters that consists of letters, digits, underscores (_), and
dollar signs ($).
• It must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a
digit.
• It cannot be a reserved word.
• It cannot be true, false, or null.
• It can be of any length.
• The syntax for declaring a variable is
datatype variableName;

int count;
double radius;

datatype variable1, variable2, ..., variablen;

• int i, j, k;
• int count = 1;
• int count;
count = 1;
• int i = 1, j = 2;
Types of variables

• Local Variables
• Instance Variables
• Static Variables

• Local Variables: A variable defined within a block or method or constructor is


called local variable.
• Instance Variables: Instance variables are non-static variables and are declared in
a class outside any method, constructor or block.
• Static Variables: Static variables are also known as Class variables.
SCOPE AND LIFETIME OF VARIABLES
• Java allows variables to be declared in any block. A block defines a
scope.
• Scope determines what objects are visible to other parts of the
program and also determines the lifetime of those objects.
Final Variables ( Constant )
• Declare a variable in any scope to be final
• The value of a final variable cannot change after it has been initialized
To declare a final variable,
final double PI = 3.14159;
Data Types
• Primitive data types:
The primitive data types include boolean, char, byte, short, int, long,
float and double.

• Non-primitive data types:


The non-primitive data types include Classes, Interfaces, and Arrays.
Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values


Operators
• Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Unary Operator

• The Java unary operators require only one operand.


• incrementing/decrementing a value by one
++ increment operator
-- decrement operator

• negating an expression ( ~ )

• inverting the value of a boolean ( ! )


public class OperatorExample{
public static void main(String args[]){
int x=10;
[Link](x++);
[Link](++x);
[Link](x--);
[Link](--x);
}}
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
[Link](~a);
[Link](~b);
[Link](!c);
[Link](!d);
}}
Arithmetic Operators
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);
[Link](a-b);
[Link](a*b);
[Link](a/b);
[Link](a%b);
}}
public class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}
Shift Operator

Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to
the left side of a specified number of times.

Right Shift Operator

The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
public class OperatorExample{
public static void main(String args[]){
[Link](10<<2);
[Link](10<<3);
[Link](20<<2);
[Link](15<<4);
}}
public OperatorExample{
public static void main(String args[]){
[Link](10>>2);
[Link](20>>2);
[Link](20>>3);
}}
Relational Operators
• Comparison operators are used to compare two values:
public class OperatorExample{
public static void main(String[] args) {
int a = 7, b = 11;
[Link]("a is " + a + " and b is " + b);

// == operator
[Link](a == b);
// != operator
[Link](a != b);
// > operator
[Link](a > b);
// < operator
[Link](a < b);
// >= operator
[Link](a >= b);
// <= operator
[Link](a <= b);
}
}
Logical Operators

Logical operators are used to determine the logic between variables or


values:
public class OperatorExample{
public static void main(String[] args) {

// && operator
[Link]((5 > 3) && (8 > 5));
[Link]((5 > 3) && (8 < 5));
// || operator
[Link]((5 < 3) || (8 > 5));
[Link]((5 > 3) || (8 < 5));
[Link]((5 < 3) || (8 < 5));

// ! operator
[Link](!(5 == 3));
[Link](!(5 > 3));
}
}
Bitwise operators

Bitwise operators are used to performing manipulation of individual bits of


a number.
Bitwise OR (|) –
This operator is a binary operator, denoted by ‘|’. It returns bit by
bit OR of input values
Bitwise AND (&) –
This operator is a binary operator, denoted by ‘&’. It returns bit by
bit AND of input values
Bitwise XOR (^) –
This operator is a binary operator, denoted by ‘^’. It returns bit by
bit XOR of input values
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
[Link]("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
[Link]("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
[Link]("a^b = " + (a ^ b));
}
}
Ternary Operator
Ternary operator is used as one line replacement for if-then-else
statement

public class OperatorExample{


public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Assignment Operator
It is used to assign the value on its right to the operand on its left.
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;
[Link](a);
a-=4;
[Link](a);
a*=2;
[Link](a);
a/=2;
[Link](a);
}}
Operators Hierarchy
Type conversion and casting

Type conversion
A data type is automatically converted into another data type by a compiler at the compiler time. It is also called widening
conversion
int x=30;
float y;
y=x; // y==30.000000.

Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double
Type Casting
A data type is converted into another data type by the programmer using the casting operator during the program design. It is
also called narrowing conversion.
destination_datatype = (target_datatype)variable;
(): is a casting operator.

float x;
byte y;
... ...
y=(byte)x;

Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

[Link](myDouble); // Outputs 9.78


[Link](myInt); // Outputs 9
}
}
Control Statements

• Decision Making statements OR Selection


• if statements
• switch statement
• Loop statements OR Iteration
• do while loop
• while loop
• for loop
• for-each loop
• Jump statements
• break statement
• continue statement
Decision-Making statements:

• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
• Simple if statement:

if(condition) {
statement 1; //executes when condition is true

• if-else statement

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
• if-else-if ladder:

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
• Nested if-statement

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
• Switch Statement:

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
• Loop Statements

• for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop
• The forEach() method is also used to loop through arrays, but it uses a function differently than the
classic “for loop”. It passes a callback function for each element of an array together with the below
parameters:
• Current Value (required): The value of the current array element
• Index (optional): The index number of the current element
• Array (optional): The array object the current element belongs to

for(data_type var : array_name/collection_name){


//statements
}
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for(String name:names) {
[Link](name);
}
• while loop

while(condition){
//looping statements
}
• do-while loop

do
{
//statements
} while (condition);
• Jump Statements
break statement

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
}
}
}
}
• continue statement

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
continue;
}
}
}
}
Arrays

Java array is an object which contains elements of a similar data type.


Types of Array

• Single Dimensional Array


• Multidimensional Array
• Jagged Array
• Array Declaration

Syntax :
datatype[ ] identifier;
or datatype identifier[ ];

Example:

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
Initialization of Array

Datatype var-name[] = new Datatype [size];

int arr[] = new int[10];


• Declaring array literal

int arr[] = {10,20,30,40,50};


Or
int intArray[] = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
Accessing elements in an array
class Arrayaccess
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i +
" : "+ arr[i]);
}
}
Multi-Dimensional Array

Syntax:
datatype[ ][ ] identifier;
or datatype identifier[ ][ ];

Example:
int[ ][ ] arr = new int[10][10];
Or
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
[Link](arr[i][j] + " ");

[Link]();
}
}
}
• Jagged Array

Jagged means to have an uneven edge or surface.

In java, a jagged array means to have a multi-dimensional array with


uneven size of rows in it.
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];

// Making the above array Jagged

// First row has 3 columns


arr[0] = new int[3];

// Second row has 2 columns


arr[1] = new int[2];
foreach or enhanced for loop

class Test {
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr) { [Link](x);
}}}
Read input from console in Java

Using Scanner Class

Scanner scanner = new Scanner([Link]);

int age = [Link]();


double height = [Link]();

import [Link];

nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
next()
nextLine()
import [Link];

class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner([Link]);

String s = [Link]();
[Link]("You entered string " + s);

int a = [Link]();
[Link]("You entered integer " + a);

float b = [Link]();
[Link]("You entered float " + b);
}
}
Class

• A class is a group of objects that has common properties.


• It is a template or blueprint from which objects are created.

class ClassName {
// fields // data member
// methods
}
INTRODUCTION

The main motivation of object oriented system design is to make software development easier and more natural by raising the
level of abstraction.

The object oriented concepts are language independent.

WHAT IS AN OBJECT?
A real world entity, identifiably separate from the surroundings.
An entity that has state and behavior is known as an object
Example: chair, bike, marker, pen, table, car, etc.

An object has two characteristics:

▪ Attributes or properties describe object‘s state (data)

▪ Methods (properties or functions) define its behavior such as deposit, withdraw, etc.
OBJECTS

▪ Combination of data and logic that represents some real world entity.

▪ Simula is the first object oriented programming language.

▪ In the Car example the car’s attributes are: color, manufacturer, cost, owner, model, etc.

▪ In the Car example the car’s methods are: drive it, lock it, change mileage, stop, start, carry passenger in it.

▪ When developing an object oriented applications, two questions always arises

1. What object does the application need?

2. What functionality should those objects have?

▪ Programming in an object oriented system consist of adding new kinds of object to the system and defining how they
behave.
INTRODUCTION-OBJECT

Example 1:
INTRODUCTION-OBJECT

Example 2:
INTRODUCTION-OBJECT

Example 3:
INTRODUCTION-OBJECT

Example 5:
INTRODUCTION-OBJECT

Example 4:

Class defines common characteristics or properties of an object. Class is a template or blue print to define object.
Object is an instance of a class having specific values of common properties.
INTRODUCTION-OBJECT

▪ OBJECT’S ATTRIBUTES

Attributes are represented by data type. They describe objects states.


In the Car example the car’s attributes are: color, manufacturer, cost, owner, model, etc.

▪ OBJECT’S METHODS

Methods define objects behavior and specify the way in which an Object’s data are manipulated.
In the Car example the car’s methods are: drive it, lock it, tow it, carry passenger in it.
Objects
• An entity that has state and behaviour is known as an object

• An object has three characteristics:


• State
• Behaviour
• Identity- not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.
className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();


class Flight{
int flightid; //data member
String name; //data member
}
Class tester{
public static void main(String args[]){
Flight obj=new Flight ();//creating an object
[Link]([Link]);
[Link]([Link]);
}
}
//new keyword is used to allocate memory at runtime.
class Lamp {
// stores the value for light true if light is on false if light is off
boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
[Link]("Light on? " + isOn);

}
public static void main(String[] args) {

// create an object of Lamp


Lamp led = new Lamp();

// access method using object


[Link]();
}
}
class Lamp {
// stores the value for light true if light is on false if light is off
boolean isOn;
// method to turn on the light
void turnOn() {
isOn = true;
[Link]("Light on? " + isOn);
}
// method to turnoff the light
void turnOff() {
isOn = false;
[Link]("Light on? " + isOn);
}
}
class Main {
public static void main(String[] args) {
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();
// turn on the light by calling method turnOn()
[Link]();
// turn off the light by calling method turnOff()
[Link]();
}
}
Static keyword ( Static Attribute )

Declare any variable as static, it is known as a static variable.


• The static variable can be used to refer to the common property of all
objects
• The static variable gets memory only once in the class area at the time
of class loading.
class Student{
int rollno;
String name;
String college="ITS";
}
class Student
{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){[Link](rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1 {
public static void main(String args[]) {
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//[Link]="BBDIT";
[Link]();
[Link]();
} }
Program of the counter without static variable
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
[Link](count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Program of counter by static variable
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Methods
A method is a block of code that performs a specific task.

In Java, there are two types of methods:


• User-defined Methods: We can create our own method based on our
requirements.
• Standard Library Methods: These are built-in methods in Java that are
available to use.
Declaring a Java Method

returnType methodName() {
// method body
}

int addNumbers() {
// code
}

modifier static returnType nameOfMethod (parameter1, parameter2, ...) {


// method body
}
Calling a Method

// calls the method


addNumbers();
class Main {

// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}

public static void main(String[] args) {

int num1 = 25;


int num2 = 15;

// create an object of Main


Main obj = new Main();
// calling method
int result = [Link](num1, num2);
[Link]("Sum is: " + result);
}
}
class Main {

// create a method
public static int square(int num) {

// return statement
return num * num;
}

public static void main(String[] args) {


int result;

// call the method


// store returned value to result
result = square(10);

[Link]("Squared value of 10 is: " + result);


}
}
Without Return value

public void square(int a) {


int square = a * a;
[Link]("Square is: " + a);
}
// method with two parameters
int addNumbers(int a, int b) {
// code
}

// method with no parameter


int addNumbers(){
// code
}

// calling the method with two parameters


addNumbers(25, 15);

// calling the method with no parameters


addNumbers()
class Main {

// method with no parameter


public void display1() {
[Link]("Method without parameter");
}

// method with single parameter


public void display2(int a) {
[Link]("Method with a single parameter: " + a);
}

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// calling method with no parameter


obj.display1();

// calling method with the single parameter


obj.display2(24);
}
Standard Library Methods

• The standard library methods are built-in methods in Java that are
readily available for use.

For example,

• print() is a method of [Link].


• sqrt() is a method of Math class
public class Main {
public static void main(String[] args) {

// using the sqrt() method


[Link]("Square root of 4 is: " + [Link](4));
}
}
public class Main {

// method defined
private static int getSquare(int x){
return x * x;
}

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {

// method call
int result = getSquare(i);
[Link]("Square of " + i + " is: " + result);
}
}
}
Passing Parameter by value

public class Increment {


public static void main(String[] args) {
int x=1;
[Link](“Before the call, x is “ + x);
increment(x);
[Link](“After the call, x is “ + x);
}

// method defined
private static void increment(int n){
n++;
[Link](“n inside the method is : “ + n);
}
}
How to initialize an object?
Constructor

Constructor in java is a special type of method that is used to initialize the


object.

Java constructor is invoked at the time of object creation. It constructs the


values i.e. provides data for the object that is why it is known as
constructor.
class Test {
Test() {
// constructor body
}
}
Rules for creating java constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
3. Constructor cannot be static , abstract and synchronised
class Main {
private String name;

// constructor
Main() {
[Link]("Constructor Called:");
name = "Program";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
[Link]("The name is " + [Link]);
}
}
Types of Constructor

constructors can be divided into 3 types:


• No-Arg Constructor
• Parameterized Constructor
• Default Constructor
No-Arg Constructors
• A Java constructor may or may not have any parameters (arguments).
• If a constructor does not accept any parameters, it is known as a no-argument constructor.

class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
[Link]("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
[Link]("Value of i: " + obj.i);
}
}
Parameterized Constructor
• A Java constructor can also accept one or more parameters. Such constructors are known as parameterized
constructors (constructor with parameters).

class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}
public static void main(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Default Constructor
• If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.

class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
JAVA Constructor vs Method

Constructor
1. Constructor is used to initialize the state of an object.
2. Constructor must not have return type.
3. Constructor is invoked implicitly.
4. The java compiler provides a default constructor if you don't have any
constructor.
5. Constructor name must be same as the class name.
Method
1. Method is used to expose behavior of an object.
2. Method must have return type.
3. Method is invoked explicitly
4. Method is not provided by compiler in any case.
5. Method name may or may not be same as class name.
Java Package
A package is simply a container that groups related types (Java classes,
interfaces, enumerations, and annotations).

⮚ Two Forms of Packages

❖Built-in package

❖User-defined package.
Built-in Packages

1) [Link]
2) [Link]
3) [Link]
4) [Link]
5) [Link]
6) [Link]
• Package, Sub-Package & Classes
• User-defined package
These are the packages that are defined by the user.
The package keyword is used to create a package in java.

//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}

Access package from another package

⮚ import package.*;

⮚ import [Link];

⮚ fully qualified name.


Using packagename.*

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using [Link]

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using fully qualified name

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
What will happen now?

import [Link];
import [Link];

Java programming is that only one unique class name is allowed in a Java
project.
Name Conflicts

import [Link];
import [Link].*;
[Link] deadLine = new [Link]();
[Link] today = new [Link]();
Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Access Modifiers ( Access Control)
Access modifiers are used to set the accessibility (visibility) of classes,
interfaces, variables, methods, constructors, data members.
Types of Access Modifier

Modifier Description

declarations are visible only within


Default
the package (package private)

declarations are visible within the


Private
class only

declarations are visible within the


Protected
package or all subclasses

Public declarations are visible everywhere


Default Access Modifier

package defaultPackage;
class Logger {
void message(){
[Link]("This is a message");
}
}
Private Access Modifier
class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


[Link] = "Program";
}
}
class Data {
private String name;

// getter method
public String getName() {
return [Link];
}
// setter method
public void setName(String name) {
[Link]= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();

// access the private variable using the getter and setter


[Link]("Program");
[Link]([Link]());
}
}
Protected Access Modifier
class Animal {
// protected method
protected void display() {
[Link]("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
[Link]();
}
}
Public Access Modifier
// [Link] file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs."); }}

// [Link]
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


[Link] = 4;
// accessing the public method
[Link]();
}
}

You might also like