0% found this document useful (0 votes)
44 views55 pages

Java Control Statements Overview

The document outlines Unit II of a Java programming course, covering control statements, classes and objects, and inheritance. It details decision-making statements, looping constructs, and jumping statements, along with their syntax and examples. Additionally, it introduces basic concepts of Object-Oriented Programming (OOP) and emphasizes the importance of OOP in managing complex software development.

Uploaded by

KUSH SHARMA
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)
44 views55 pages

Java Control Statements Overview

The document outlines Unit II of a Java programming course, covering control statements, classes and objects, and inheritance. It details decision-making statements, looping constructs, and jumping statements, along with their syntax and examples. Additionally, it introduces basic concepts of Object-Oriented Programming (OOP) and emphasizes the importance of OOP in managing complex software development.

Uploaded by

KUSH SHARMA
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

JAVA (UGCA-1932)

UNIT-II

Course Code: UGCA1932 (PTU)


Course Name: Programming in Java
Course: BCA, Semester: 5th
UNIT-II
Control Statements: Decision making statements (if, if-else, nested if, else if ladder, switch,
conditional operator), Looping statements (while, do-while, for, nested loops), Jumping statements
(Break and Continue).

Classes and Objects: Basic concepts of OOPS, Classes and Objects, Modifiers, Passing
arguments, Constructors, Overloaded Constructors, Overloaded Operators, Static Class Members,
Garbage Collection.

Inheritance: Basics of inheritance, Inheriting and Overriding Superclass methods, Calling


Superclass Constructor, Polymorphism, Abstract Classes, Final Class.

Control Statements:

Java compiler executes the code in the program from top to bottom. The statements in the code are
executed according to their order in which they appear in the program. However, Java provides
statements that can be used to control the flow of Java code. Those statements are called control
flow statements. It is a fundamental features of Programming including Java programming
language.
JAVA (UGCA-1932)
UNIT-II

There are three types of control flow statements in Java:


1. Decision Making Statements
2. Loop Statements
3. Jump Statements

Decision-making Statements (if, if-else, nested if, else if ladder, switch,


conditional operator):
Decision-making statements in Java are used to control the execution flow, based on certain
conditions. They allow a program to execute different parts of code depending on whether a
condition or set of conditions is true or false.
Decision-making statements are; if, if-else, switch, etc.

‘if’ Statement in Java:


The if statement in Java evaluates a condition. If the condition is true, the block of code inside
the if statement is executed. It's the simplest form of decision-making in programming, allowing
for the execution of code based on a condition.
Syntax:
if(condition)
{
//statements
}
Example:
public class Student {
pubic static void main(String args[])
{
int age = 20;
if(age >=18)
{
[Link](“Eligible for vote!”);
}
}
}
Output:
Eligible for Vote!

if-else statement:
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
the else block. The else block is executed if the condition of the if-block is false.
JAVA (UGCA-1932)
UNIT-II

Syntax:
if(condition) {
statement 1; //executes when the condition is true
}
else{
statement 2; //executes when the condition is false
}

Example:
public class Student {
pubic static void main(String args[])
{
int age = 15;
if(age >=18)
{
[Link](“Eligible for vote!”);
}
Else{
[Link](“Not Eligible for vote!”);
}
}
}

Output:
Note Eligible for vote!

if-else-if ladder: (ladder = सीढ़ी)


The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that creates a decision tree where the
program may enter into the block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
JAVA (UGCA-1932)
UNIT-II

}
else {
statement 2; } //executes when all the conditions are false
Examkple:
public class Student {
pubic static void main(String args[])
{
int age = 22;
if(age >=21)
{
[Link](“Eligible for abroad employment & Voting in India!”);
}
else-if(age>=18){
[Link](“Eligible for vote in India only!”);
}
Else{
[Link](“He/She is minor Studen!”);
}
}
}
OUTPUT:

Nested if-statement:
In nested if-statements, the if statement can contain an if or if-else statement inside another if or
else-if statement.

Syntax
if(condition 1) {
if(condition 2) { //nesting
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
JAVA (UGCA-1932)
UNIT-II

passed as a parameter of the switch statement. The switch statement is easier to use instead of if-
else-if statements. It also enhances the readability of the program.

Points to be noted about the switch statement:


 The case variables can be int, short, byte, char, or enumeration. String type has also been
supported since version 7 of Java
 Cases cannot be duplicated
 Default statement is executed when any of the cases doesn't match the value of the
expression. It is optional.
 Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, the next case is executed.
 While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.

Syntax:
switch (expression/condition){
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
default statement;
}

How does the switch-case statement work?


 The expression is evaluated once and compared with the values of each case.
 If the expression matches with value1, the code of case value1 is executed. Similarly, the
code of case value2 is executed if the expression matches with value2 and so on.
 If there is no match, the code of the default case is executed

Example:

class Main {
public static void main(String[] args) {
int number = 3;
String day;
JAVA (UGCA-1932)
UNIT-II

switch (number) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
// match the value of the weekdays
case 3:
day= "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day = "Invalid Number!";
break;
}
[Link]("Day: " + day);
}
}
OUTPUT

Conditional Operator:
Conditional operators in Java are essential for creating logical expressions that give Boolean
results. They control the flow of execution in a Java program, enabling different actions or
statements based on specific conditions.
JAVA (UGCA-1932)
UNIT-II

By using conditional operators, developers can create dynamic decision-making structures. It also
helps improve the functionality and adaptability of their Java applications.

In Java, there are three types of conditional operators:

1. Conditional AND
The conditional AND is a binary operator denoted by the symbol “&&” which combines boolean
expressions and returns true only if both expressions are true. The result will return false if any
one expression is false.

Syntax:
condition1 && condition2
//It evaluates both condition 1 and condition 2.
Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean condition1 = (x > 0); // true
boolean condition2 = (y > 5); // true
boolean result = condition1 && condition2;
[Link](result); // Output: true
}
}
Output:
True

2. Conditional OR
The conditional OR operator is denoted by the symbol “||”. It combines two Boolean expressions,
which return true if one of them expressions is true. The result will be false if the expressions are
false.
Syntax:
condition1 || condition2
//It evaluates both condition1 and condition 2.
Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean condition1 = (x > 0); // true
JAVA (UGCA-1932)
UNIT-II

boolean condition2 = (y < 5); // false


boolean result = condition1 || condition2;
[Link](result); // Output: true
}
}

3. Ternary Operator:
The meaning of ternary is composed of three parts. The ternary Operator (?:) consists of three
operands. It’s a one-liner replacement for the if-else statements and is used a lot in Java
programming. It takes less space and helps to write the if-else statements in the shortest way.

Syntax:
variable = Expression1 ? Expression2: Expression3

Example:
class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, max;

[Link]("First num: " + n1);


[Link]("Second num: " + n2);

max = (n1 > n2) ? n1 : n2; //conditional operator

[Link]("Maximum is = " + max);


}
}
Output:

Looping Statements:
JAVA (UGCA-1932)
UNIT-II

Looping is a feature that facilitates the execution of a set of instructions repeatedly until a certain
condition is false. Loops are also known as Iterating statements or Looping constructs in Java.

In simple, computer programming loops are used to repeat a block of code. For example, if you
want to show a message 100 times, then rather than typing the same code 100 times, you can use
a loop.

In Java, there are three types of loops.


 for loop
 while loop
 do...while loop

Java for Loop:


Java for loop is used to run a block of code for a certain number of times based on the condition
provided by programmer.

syntax of for loop is:


for (initialization; condition; increment/decrement) {
// body of the loop
}

In above syntax:
 The initialization, declares a variable and executes only once.
 The condition is evaluated. If the condition is true, the body of the for loop is executed.
 The increment/decrement updates the initialized value.
 The condition is evaluated again. The process continues until the condition is false.

Example1: Display a line Five Times

class Main {
public static void main(String[] args) {

int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
[Link]("SHAHID is learning Java!");
}
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Example2: Display numbers 1-5

class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
[Link](i);
}
}
}
OUTPUT

Java while loop:


A while loop is a control flow statement that allows code to be executed repeatedly based on a
given condition. The while loop can also be considered as a repeating if statement. While loop is
also known as an “entry-control loop”.

Syntax:
while (condition)
{
loop statements...
}
JAVA (UGCA-1932)
UNIT-II

Example:
class while_loop {
public static void main (String[] args) {
int i=1;
while (i<5)
{
[Link]("Shahid is learning Java!");
i++;
}
}}
OUTPUT

Java do-while loop:


Do while loop is similar to while loop with only a difference is that it checks condition after
executing the statement once. Hence if condition is false even it gives the output only once. Do-
while loop is also called “exit-control loop”.

Syntax:
do
{
statements..
}
while (condition);

Example:
class do_while_loop {
public static void main (String[] args) {
int i=1;
do
{
[Link]("You are learning do-while loop.");
i++;
}while(i<5);
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Nested Loop:
A nested loop means a loop statement inside another loop statement. There are different
combinations of loop using for loop, while loop, and do-while loop.

Syntax of nested for-loop:


// outer loop
for (int i = 1; i <= 5; ++i) {
// codes
// inner loop
for(int j = 1; j <=2; ++j) {
// codes
}
}
OUTPUT

Jumping statements (Break and Continue):


Jumping statements are control statements that transfer execution control from one point to another
point in the program. such as jumping out of a loop, skipping iterations, and branching to a
different section of code based on certain conditions.

Java provides three Jump statements:


JAVA (UGCA-1932)
UNIT-II

1. Break statement.
2. Continue statement.
3. Return Statement

Break Statement:
The break statement is used to terminate the execution of a loop or switch statement. When a break
statement is encountered inside a loop or switch statement it immediately exits the loop or switch
control flow.

Example:
class break_statement {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6) //stops iteration when 6 is encountered
break;
[Link](i);
}
}
}
OUTPUT

Continue Statement:
The continue statement is used to skip the current iterative value or statement of result and proceed
to the next iteration. It means that, it skips any code following the continue statement within the
loop and jumps to the next iteration.
JAVA (UGCA-1932)
UNIT-II

Example:
class Continue_statement{
public static void main(String[] args)
{
for (int i = 1; i <=10; i++) {
if (i == 5){
[Link]();
continue; // to skip the current iterative value 5
}
[Link](i);
}
}
}
OUTPUT

Return Statement: (not in PTU syllabus)


The return statement is used to exit from a method and return a value to the caller. Since the control
jumps from one part of the program to the caller, hence it is a Jump statement.
 “return” is a reserved keyword means we can’t use it as an identifier and variable.
 It is used to exit from a method, with or without a value.

Example:
class ReturnExample {
public static int calculateSum(int num1, int num2)
{
int sum = num1 + num2;
// Return the calculated sum
return sum;
}
JAVA (UGCA-1932)
UNIT-II

public static void main(String[] args)


{
int result = calculateSum(5, 10);
// Print the result
[Link]("Result: " + result);
}
}
OUTPUT

Class and Objects: (Basic concepts of OOPs)


OOP (Object-Oriented Programming) is a paradigm that provides many concepts, such as
inheritance, data binding, polymorphism, etc. A programming language in which everything is
represented as an object is known as an Object-Oriented programming language.

Object-oriented programming (OOP) was introduced to eliminate the limitations of procedural


programming by providing a more efficient way to manage complex software development.
Procedural programming, also known as imperative programming, was widely used before the
invention of Object-Oriented Programming (OOP).

Important points to notice in OOPs:


 Programming concept which is used to solve real-world problems.
 A programming style which involves dividing a program into pieces of objects that can
communicate with each other.
 Object base coding style in which each object (a real-world entity) has its own properties
and behaviors.
 The fundamental idea is to combine properties and behaviors in order to promote
modularity.
 OOP promotes modularity by encapsulating data and behavior within objects.

Classes:
A class in Object-oriented Programming (OOP) is a blueprint or template that defines the attributes
(data) and methods (functions) that is accessed using object. It encapsulates the data and methods
to manipulate using objects. Classes are fundamental element of OOP as they enable the creation
of modular and reusable code.
JAVA (UGCA-1932)
UNIT-II

Key Components of a Class:


 Attributes: These are the variables that hold the state of the object. They are sometimes
referred to as properties or fields.
 Methods: These are the functions that define the behavior of the objects created from the
class. Methods can manipulate the object's attributes and perform operations.

Class Declaration in Java:


Access_modifier class <class_name>
{
Data member;
Methods/functions;
Constructor;
Nested class;
}

Example of Java class:


class Student {
// data member also instance variable
int roll = 295;
// data member also instance variable
String name = "SHAHID";

public static void main(String args[])


{
[Link]("Thi Output is example of calsses in OOPs");
Student s1 = new Student();//OBJECT
[Link]([Link]);
[Link]([Link]);
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Object:
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities.
Objects are the instances of a class that are created to use the attributes and methods of a class.
When a class is defined, no memory is allocated until an object of that class is created.
An object consists of:
 State: It is represented by attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object with other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.
For Example: a student named Shahid is a Real-World entity which has his behavior like walking,
speaking, eating, etc., in programming terms it's an Object.

Creating an object of a class in Java:


There are various ways in Java to create an object of a class but one of them is popular way by
using a new keyword. It is the most common and general way to create an object in Java. When an
object of a class is created, the class is said to be “instantiated”.
All the instances share the attributes and the behavior of the class. But the values of those attributes,
i.e. the state are unique for each object.

Syntax:
//object of a class
Test obj = new Test();

Example:
public class Object_example {
int roll = 295;
String name = "Shahid";

public static void main(String[] args) {


[Link]("Example of Object.");

Object_example myObj = new Object_example();


//Above line contains an Object named myObj

[Link]("Roll NO: "+[Link]);


[Link]("Name : "+[Link]);
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Attributes: (important in OOPs but not in the PTU syllabus)


Attributes, also known as properties or fields, are variables that hold data specific to an object.
They define the state of an object and are typically represented as nouns. Attributes are
fundamental in distinguishing one object from another within the same class.
Example: Consider a Student class. The attributes could include:
 Name: The student's name
 ID: The student's identification number
 Age: The student's age
 Marks: The student's marks

Behaviors: (important in OOPs but not in the PTU syllabus)


Behaviors, also known as methods or functions, are actions that objects can perform. They define
the functionality of the class and are typically represented as verbs. Behaviors operate on the
attributes of the class to perform specific tasks.
Example: Continuing with the Student class, behaviors could include:
 Display: Show student details
 Update Marks: Change the student's marks
 Calculate Average: Compute the average of the student's marks

Class vs Object:
Object Class
Class is a blueprint or template from
Object is an instance of a class.
which objects are created.
The object is a real-world entity such as a pen,
Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair, etc.
The object is a physical entity. Class is a logical entity.
JAVA (UGCA-1932)
UNIT-II

An object is created through a new keyword mainly Class is declared using class
e.g. Student s1=new Student(); keyword e.g. class Student{}
An object is created many times as per
Class is declared once.
requirement.
Class doesn't allocate memory when it is
Object allocates memory when it is created.
created.
There are many ways to create objects in Java such
There is only one way to define a
as new keyword, newInstance() method, clone()
class in java using the class keyword.
method, factory method, and deserialization.

Access Modifiers in Java:


The access modifiers in Java specify the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and classes by applying the
access modifier.
In Java, Access modifiers help restrict the scope of a class, constructor, variable, method, or data
member. It provides security, and accessibility to the user depending upon the access modifier
used with the element.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the default.

3. Protected: The access level of a protected modifier is within the package and outside the
package through the child class. If you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package, and outside the package.
JAVA (UGCA-1932)
UNIT-II

Private:
The private access modifier is specified using the keyword private. The methods or data members
declared as private are accessible only within the class in which they are declared. It means, When
variables and methods are declared private, they cannot be accessed outside of the class.

Example:
class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){
//Create an object of Data
Data obj = new Data();
// access private variable and field from another class
[Link] = "Private_Access_Modifier!";
[Link]([Link]);
}
}

In the above example, we have declared a private variable named name. When we run the program,
we will get the following error:
JAVA (UGCA-1932)
UNIT-II

Default:
When no access modifier is specified for a class, method, or data member It is said to be having
the default access modifier by default. The data members, classes, or methods that are not declared
using any access modifiers or default access modifiers are accessible only within the same
package.
Example1: (new package)
package p1;

// Class Geek is having Default access modifier


Class default_mdf
{
void display()
{
[Link]("Hello World!");
}
}
Example 2: (importing previously created package)
package p2;
import p1.*;

// This class is having default access modifier


class default_mdf_new
{
public static void main(String args[])
{
// Accessing class Geek from package p1
default-mdf obj = new default-mdf ();

[Link]();
}
JAVA (UGCA-1932)
UNIT-II

}
OUTPUT

Protected:
The protected access modifier is specified using the keyword protected. The methods or data
members declared as protected are accessible within the same package and outside of the package
using the concept of inheritance only. The protected access modifier can be applied to the data
member, method and constructor but it can’t be applied on the class.

Example:
In this example, will create two packages pck1 and pck2. And we will try to access the methods
from one package to another package.

Package1:
//save by .java extension
package pck1;
public class A{
protected void msg()
{
[Link]("Hi, You learning Protected Modifier.");
}
}

Package 2:
//save by .java extension
package pck2;
import pck.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Public:
The public access modifier is specified using the keyword public. The public access modifier has
the global scope among all other access modifiers. Classes, methods, or data members that are
declared as public are accessible from everywhere in the program. There is no restriction on the
scope of public data members.

Example:
Package 1;
//save by .java extension
package pck1;
public class A{
public void msg()
{
[Link]("Hi, You learning Public Modifier.");
}
}
Package 2:
//save by .java extension
package pck2;
import pck.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Java Constructors:
Java constructor is a technique that is used to construct something in our Java programs. A
constructor in Java is a special method that is used to initialize objects. The constructor is called
automatically when an object of a class is created.

Rules for creating Java Constructor:


1. The constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: - We can have private, protected, public, or default constructors in Java.

Example:
class OOPs {
OOPs() // Constructor
{
super();
[Link]("Constructor Called");
}
public static void main(String[] args)
{
OOPs obj = new OOPs();//constructor will call automatically
} }
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Types of Java constructors:


1. Default constructor
2. No-Arg constructor
3. Parameterized constructor

Default Constructor:
If we don’t provide a constructor, then Java provides a default constructor implementation for us
to use. The default constructor is always without argument and provided by Java compiler only
when there is no existing constructor defined.
Let’s look at a simple program where a default constructor is being used since we will not explicitly
define a constructor.
class Main {
int a;
boolean b;
public static void main(String[] args) {
Main obj = new Main(); // calls default constructor
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
OUTPUT

No-Arg Constructor:

Similar to methods, 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.

Example:
class Main {
// constructor with no parameter
Main () {
[Link]("Constructor is called");
JAVA (UGCA-1932)
UNIT-II

public static void main(String[] args) {


// calling the constructor without any parameter
Main obj = new Main ();
}
}
OUTPUT

Parameterized Constructor:
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).

Example:
class Main {
// constructor accepting single value
Main(String lang) {
[Link](lang + " Programming Language");
}

public static void main(String[] args) {


Main obj1 = new Main("Java"); // call constructor by passing a single value
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Constructor vs Methods:
Constructor Methods

A constructor is used to initialize the state A method is used to expose the behavior
of an object. of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default


The method is not provided by the
constructor if you don't have any
compiler in any case.
constructor in a class.

The constructor name must be the same as The method name may or may not be the
the class name. same as the class name.

Java Constructor Overloading:


In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with same name and different parameters so
that every constructor can perform a different task.

Syntax of Constructor Overloading:

public class MyClass {


// Constructor with no parameters
public MyClass() {
// Initialization code
}

// Constructor with one parameter


public MyClass(int parameter) {
// Initialization code using the provided parameter
}

// Constructor with multiple parameters


JAVA (UGCA-1932)
UNIT-II

public MyClass(int parameter1, String parameter2) {


// Initialization code using the provided parameters
}

// Additional constructors as needed...


}

Here, ‘MyClass’ contains multiple constructors. Each constructor has a different parameter list.
The constructors can then perform specific initialization tasks based on the parameters they
receive.

Example of Constructor Overloading:


class Student{
//1 constructor
Student()
{
[Link]("I am a Student.");
}

//2 constructor
Student(String name)
{
[Link]("I am a Student. My name is "+name);
}

//3 constructor
Student(String name, int roll)
{
[Link]("I am a student. My name is "+name+" and roll is "+roll);
}

public static void main(String args[])


{
Student obj = new Student(); //Constructor 1
Student obj2 = new Student("Shahid"); //constructor 2
Student obj3 = new Student("Shahid",295); //Constructor 3
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Static Members:
In Java, static members are those which belongs to the class and you can access these members
without instantiating the class. The static keyword can be used with methods, fields, classes, and
blocks.
Static variables, Static Initialization Block, and Static Methods; these all are static components or
static members of a class. These static members are stored inside the Class Memory. To access
static members, you need not to create objects. Directly you can access them with the class name.

Static Methods: You can create a static method by using the keyword static. Static methods can
access only static field methods. To access static methods there is no need to instantiate the class,
you can do it by just using the class name.

Example:
public class MyClass {
//static member
public static void sample(){
[Link]("Hello SHAHID");
}
public static void main(String args[]){
//static member
[Link]();//static method
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Static Blocks: These are a block of code with a static keyword. In general, these are used to
initialize the static members. JVM (Java Virtual Machine) executes static blocks before the main
method at the time of class loading.

Example:
public class MyClass {
//static block
static{
[Link]("Hello I am from static block");
}
public static void main(String args[]){
[Link]("I am inside main method");
}
}
OUTPUT

Static Fields: You can create a static field by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when the class is
loaded for the first time. Just like static methods you can access static fields using the class name
(without instantiation).

Example:
public class MyClass {
//stati Fields
public static String name = "SHAHID";
public static int roll = 295;
public static void main(String args[]){
[Link]("My name is "+[Link]);
[Link]("My Roll no. is "+[Link]);
}

}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Garbage Collection in Java:


Garbage collection in Java is the process by which Java programs perform automatic memory
management. When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these unused
objects and deletes them to free up memory. To do so, we were using free() function in C language
and delete() in C++. But, in java it is performed automatically. So, java provides better memory
management.

Advantages of Garbage Collection


 It makes Java memory efficient because the garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector (a part of JVM) so we don't need to make
extra efforts.

There are many ways to make an object eligible for garbage collection:
1. Nullifying the reference variable
Example:
Employee e = new Employee();
e = null;

2. Re-assigning the reference variable


Example:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
//now the first object referred by e1 is available for garbage collection

3. By anonymous Object
Example:
new Employee();
JAVA (UGCA-1932)
UNIT-II

We can also request JVM to run a garbage collector using various methods:

gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing.
Syntax:
public static void gc()
{ }
finalize() method: The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in the Object class
as:

protected void finalize()


{ }

Simple Example of Java Garbage Collection:


public class TestGarbage1{
public void finalize()
{
[Link]("[Link] is garbage collected");
}
public static void main(String args[]){
[Link]("[Link] is garbage collected");
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1 = s2;
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Passing arguments: (Object as an argument or parameter)


In Java, you can pass objects as arguments to methods. When you pass an object as an argument,
you’re passing a reference to that object, not the actual object itself. This means that changes made
to the object inside the method will affect the original object.
Example1:
class Car {
String model;

Car(String model) {
[Link] = model;
}

void printModel() {
[Link]("Car model: " + model);
}
}

public class Main {


public static void main(String[] args) {
// Create a Car object
Car myCar = new Car("Tesla Model S");

// Pass the Car object to the method


changeModel(myCar);

// Print the model after the method call


[Link](); // Output: Car model: Tesla Model X
}
JAVA (UGCA-1932)
UNIT-II

// Method that takes a Car object as a parameter


static void changeModel(Car car) {
[Link] = "Tesla Model X"; // This changes the model of the original Car object
}
}
OUTPUT

Example 2:
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
boolean equalTo(ObjectPassDemo o)
{
// notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}
public class ObjectPassing {
public static void main(String args[])
{ // Creating object of above class inside main()
ObjectPassDemo obj1 = new ObjectPassDemo(10, 20);
ObjectPassDemo obj2 = new ObjectPassDemo(10, 20);
ObjectPassDemo obj3 = new ObjectPassDemo(-1, -1);
// Checking whether object is equal as custom values

[Link]("obj1 == obj2: "+ [Link](obj2));


[Link]("obj1 == obj3: "+ [Link](obj3));
}
}
JAVA (UGCA-1932)
UNIT-II

OUTPUT

Java Operator Overloading:


Java does not support operator overloading in the way that languages like C++ do. This means you
cannot redefine or "overload" standard operators (like +, -, *, etc.) to work with user-defined types
(such as classes and objects) directly.
Java doesn't Support Operator Overloading Except for one case i.e. + operator it can be used to
add numbers as well as strings.
Example 1:
public class Addition {
public static void main(String[] args) {

int a = 10;
int b = 20;
int c = a + b;
[Link](c); // 30
}
}
OUTPUT
30
Example 2:

public class StringAddition {


public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2;
[Link](s3);
}
}
OUTPUT
Hello World
JAVA (UGCA-1932)
UNIT-II

Note:
In The First Example + Operator Add Two Integer values but in the Second it Add Two String.
This is called Operator Overloading. In the Above Example + operator is overloaded as it performs
different actions depending on the parameters passed.

Inheritance: (Basic of inheritance)


Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class
(the subclass or derived class) to inherit properties and behaviors from another class (the superclass
or base class). A class that inherits from another class can reuse the methods and fields of that
class.
Important Terminologies Used in Java Inheritance:
Class: A class is a set of objects which shares common behavior and common properties. Class is
not a real-world entity. It is just a template or blueprint from which objects are created.

Super Class/Parent Class: The class whose features are inherited is known as a superclass (or a
base class or a parent class).

Sub Class/Child Class: The class that inherits the other class is known as a subclass (or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.

How to Inherit any class?


The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are
derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Example:
// Parent class
class One {
public void Shahid()
{
[Link]("I am Shahid from parent class.");
}
}
//child class
class Two extends One {
JAVA (UGCA-1932)
UNIT-II

public void harsh()


{
[Link]("I am harsh from child class.");
}
}
public class Main {
public static void main(String[] args)
{
Two obj = new Two();
[Link]();
[Link]();
}
}
OUTPUT

Types of Inheritance in Java:


Java supports several types of inheritance, each with its own characteristics. Here are the types of
inheritance supported in Java:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (through Interfaces)
5. Hybrid Inheritance

Single Inheritance:
Single inheritance refers to the inheritance where a class inherits properties and behaviors from
only one parent class. It inherits the properties and behavior of a single-parent class. Sometimes,
it is also known as simple inheritance.
JAVA (UGCA-1932)
UNIT-II

Example:
// Parent class
class One {
public void Shahid()//name of coder
{
[Link]("I am from parent class of Single Inheritance.");
}
}
//child class
class Two extends One {
public void harsh() //name of coder's friend
{
[Link]("I am from child class fro Single Inheritance.");
}
}
public class Main {
public static void main(String[] args)
{
Two obj = new Two();
[Link]();
[Link]();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Multilevel Inheritance:
Multilevel inheritance involves a chain of inheritance where a derived class serves as a base class
for another class. In simple we can say that the last class inherits its previous class and that class
also inherits its previous class and so on.
In the below image, class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C.

Syntax:
class Grandparent {
// Grandparent class members
}
class Parent extends Grandparent {
// Parent class inherits from Grandparent
}
class Child extends Parent {
// Child class inherits from Parent (and indirectly from Grandparent)
}
JAVA (UGCA-1932)
UNIT-II

Example:
// Parent class
class Grand_Parent {
public void Shahid()//name of coder
{
[Link]("I am from Grand_parent class of Multi-leve Inheritance.");
}
}
//child class
class Parent extends Grand_Parent {
public void Shahid2() {
[Link]("I am from Parent class of Multi-level Inheritance.");
}
}
class Child extends Parent {
public void Shahid3() {
[Link]("I am from child class of Multi-level Inheritance.");
}
}
public class Main {
public static void main(String[] args)
{
Child obj = new Child();
[Link]();
obj.Shahid2();
obj.Shahid3();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Hierarchical Inheritance:
Hierarchical inheritance involves one base class being inherited by multiple derived classes. In
Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.

Example:
class A {//superclass or Base class for all the classes
public void Shahid()//name of coder
{
[Link]("I am Base class in Hierarchical Inheritance.");
}
}
//child class
class B extends A {
public void Shahid2() {
[Link]("I am class B inheriting A.");
}
}
class C extends A {
public void Shahid3() {
[Link]("I am class C inheriting A.");
}
}
class D extends A {
public void Shahid4() {
[Link]("I am class D inheriting A.");
JAVA (UGCA-1932)
UNIT-II

}
}
public class Main {
public static void main(String[] args)
{
B obj = new B();
[Link]();
obj.Shahid2();
C obj2 = new C();
[Link]();
obj2.Shahid3();
D obj3 = new D();
[Link]();
obj3.Shahid4();

}
}
OUTPUT

Multiple Inheritance (Through Interfaces):


In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple inheritances with classes. In Java,
we can achieve multiple inheritances only through Interfaces. In the image below, Class C is
derived from interfaces A and B.
Interface: An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class. The interface in Java is a mechanism to achieve abstraction.
JAVA (UGCA-1932)
UNIT-II

Syntax:
interface InterfaceA {
void methodA();
}

interface InterfaceB {
void methodB();
}

class MyClass implements InterfaceA, InterfaceB {


public void methodA() {
// Implementation of methodA
}

public void methodB() {


// Implementation of methodB
}
}

Example:
interface A {//interface1
public void Shahid();//name of coder
}
interface B {//interface2
public void Shahid2() ;
}
JAVA (UGCA-1932)
UNIT-II

class C implements A, B {
public void Shahid() {
[Link]("Method1 of interface1: \nI am class C utilizing interface A And B.");
}
public void Shahid2(){
[Link]("Method2 of interface2: \nI am class C utilizing interface A And B");
}
}
public class Main {
public static void main(String[] args)
{
C obj = new C();
[Link]();
obj.Shahid2();
}
}
OUTPUT

Hybrid Inheritance:
Hybrid inheritance combines different types of inheritance within a single class. It is a mix of two
or more of the above types of inheritance. Java does not support multiple inheritance of classes,
we can achieve hybrid inheritance only through Interfaces.
JAVA (UGCA-1932)
UNIT-II

Example: (Single and Multiple Inheritance)

class HumanBody //Base class for single inheritance


{
public void displayHuman()
{
[Link]("Method defined inside HumanBody class");
}
}
interface Male //interface1
{
public void show();
}
interface Female //interface2
{
public void show();
}
//1single Inheritance //2Multiple Inheritance by interfaces
public class Child extends HumanBody implements Male, Female
{
public void show()
{
[Link]("Implementation of show() method defined in interfaces Male and
Female");
}

public static void main(String args[])


{
Child obj = new Child();
[Link]("Implementation of Hybrid Inheritance in Java");
[Link]();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Overriding Superclass methods:


If a subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java. In other words, if a subclass provides the specific implementation of the method
that has been already declared by its parent class, it is known as method overriding.
Note:
 The method must have the same name as in the parent class.
 The method must have the same parameter as in the parent class.
 It's a good practice to use the @Override annotation above or before the overriding method.
This helps to catch errors at compile time if the method is not actually overriding any
method in the superclass.
Example1:
// Base Class
class Parent {
void show() { [Link]("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
[Link]("Child's show()");
}
}

// Driver class
Public class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called
Parent obj1 = new Parent();
[Link]();

// If a Parent type reference refers to a Child object Child's show() is called.


Parent obj2 = new Child();
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II

Example2:
class Animal {
void sound() {
[Link]("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("The dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object

[Link](); // Output: The animal makes a sound


[Link](); // Output: The dog barks
[Link](); // Output: The cat meows
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Calling Superclass Constructor:


The super keyword in Java is a reference variable that is used to refer the parent class when we’re
working with objects.

Characteristics of Sumer keyword in Java:


 super is used to call a superclass constructor: When a subclass is created, its constructor
must call the constructor of its parent class. This is done using the super() keyword, which
calls the constructor of the parent class.

 super is used to call a superclass method: A subclass can call a method defined in its
parent class using the super keyword. This is useful when the subclass wants to call the
parent class’s method.

 super is used to access a superclass field: A subclass can access a field defined in its
parent class using the super keyword. This is useful when the subclass wants to access the
parent class’s field.

 Super must be the first statement in a constructor: When calling a superclass


constructor, the super() statement must be the first statement in the constructor of the
subclass.

Overall, the super keyword is a powerful tool for sub-classing in Java, allowing subclasses to
inherit the defined functionality of their parent classes.

Use of Super keyword in Java:


1. Use of super with Variables
2. Use of Super with Methods
3. Use of super with Constructors

Use of super with constructors:


The super keyword can also be used to access the parent class constructor. Super keywords can
call both parametric as well as non-parametric constructors depending on the situation.

Example:
// superclass Person
class Person {
Person()
{
[Link]("I am from Constructor");
}
}
JAVA (UGCA-1932)
UNIT-II

// subclass Student extending the Person class


class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();
[Link]("I am from Constructor");
}
}

public class Test {


public static void main(String[] args)
{
Student s = new Student();
}
}
OUTPUT

Polymorphism in Java:
The word polymorphism means having many forms. In simple words, we can define Java
Polymorphism as the ability of a message to be displayed in more than one form.

Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the
same time. Like a man at the same time is a father, a husband, and an employee. So the same
person possesses different behaviors in different situations. This is called polymorphism.

Polymorphism is considered one of the important features of Object-Oriented Programming.


Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, So it means many forms.
JAVA (UGCA-1932)
UNIT-II

In Java Polymorphism is mainly divided into two types:


I. Compile-time Polymorphism (Method overloading)
II. Runtime Polymorphism (Method Overriding)

Compile-Time Polymorphism (Method Overloading):


Compile-time polymorphism, also known as static polymorphism, is a type of polymorphism that
is resolved during the compile time of the program. It is achieved through method overloading and
operator overloading (although operator overloading is not supported in Java). Method
overloading allows a class to have more than one method with the same name.
Method Overloading:
When there are multiple functions with the same name but different parameters then these
functions are said to be overloaded. Functions can be overloaded by changes in the number of
arguments or a change in the type of arguments.
Example:
class Calculator {

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to add three integers

public int add(int a, int b, int c) {

return a + b + c;

// Method to add two doubles

public double add(double a, double b) {

return a + b;

public class Main {


JAVA (UGCA-1932)
UNIT-II

public static void main(String[] args) {

Calculator obj = new Calculator();

[Link]([Link](5, 10)); // Calls add(int, int)

[Link]([Link](5, 10, 15)); // Calls add(int, int, int)

[Link]([Link](5.5, 10.5)); // Calls add(double, double)

}
OUTPUT

In the above program:


When the add method is called with two integers, the first add method is invoked. When it is called
with three integers, the second add method is invoked. When it is called with two doubles, the
third add method is invoked. The compiler determines which method to call based on the method
parameters.

Run-Time Polymorphism (Method overriding):


Runtime polymorphism, also known as dynamic polymorphism or method overriding, is a type of
polymorphism in which a call to an overridden method is resolved at runtime rather than compile-
time. This allows a subclass to provide a specific implementation of a method that is already
defined in its superclass. The JVM determines at runtime which method to invoke based on the
actual object's type, not the reference type.
Method Overriding:
Method overriding is the most common and fundamental form of runtime polymorphism in Java.
It occurs when a subclass provides a specific implementation of a method that is already defined
in its superclass. The method in the subclass must have the same name, return type, and parameters
as the method in the superclass.
JAVA (UGCA-1932)
UNIT-II

Example:
// Class 1
class Parent {
// Method of parent class
void Print()
{
[Link]("I am from parent class");
}
}
// Class 2
class subclass1 extends Parent {
// Method
void Print() { [Link]("I am from subclass1"); }
}
// Class 3
class subclass2 extends Parent {
// Method
void Print()
{ [Link]("I am fromsubclass2"); }
}
public class Main {
public static void main(String[] args)
{
Parent a;
a = new Parent();
[Link]();

a = new subclass1();
[Link]();

a = new subclass2();
[Link]();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II

Abstract Classes:
Java abstract class is a class that cannot be initiated by itself means an instance of an abstract class
cannot be created, it needs to be sub classed by another class to use its properties.

In Java, abstract class is declared with the abstract keyword. An abstract is a Java modifier
applicable for classes and methods in Java but not for Variables.

Syntax:
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
Example:
abstract class Bird {
// Abstract method for flying
public abstract void fly();
// Abstract method for eating
public abstract void eat();
//concrete method
public void sleep() { [Link]("Bird is sleeping"); }
}
class Sparrow extends Bird {
@Override
public void fly() {
[Link]("Sparrow is flying");
}
@Override
public void eat() {
[Link]("Sparrow is eating seeds");
}
}
public class Main {
public static void main(String[] args) {
Sparrow obj = new Sparrow();
[Link](); // Output: Sparrow is flying
[Link](); // Output: Sparrow is eating seeds
[Link](); // Output: Bird is sleeping (inherited from Bird class)
}
}
JAVA (UGCA-1932)
UNIT-II

Observation of the above program:


 Bird serves as an abstraction that defines common behaviors (fly() and eat()) for all types
of birds.
 Sparrow extends Bird and provides concrete implementations for fly() and eat() specific
to sparrows.
 The Main class demonstrates how you can create an instance of Sparrow and invoke its
methods to perform specific actions (fly(), eat(), and sleep()).

Final Class:
A final class in Java is a concept of object-oriented programming where a class is declared using
the "final" keyword. This type of class cannot be extended or inherited by other classes (meaning
that no subclass can be created from it.) making it inflexible.
If a class is complete in nature then we can make it a final class which tells us that it can’t be an
abstract class. If in case anyone tries to inherit the final class to any subclass, the compiler will
throw an error.

Final keyword:
In Java, the "final" keyword is used to indicate that a variable, method, or class can only be
assigned a value once and cannot be changed thereafter. The final keyword is used to limit access
and modification by the user. It can be used in any context such as final variable, final class, or
final method.

Syntax:
final class className
{
// Body of class
}
Example:
final class finalclass
{
void method()
{
[Link]("this is final class");
}
}
class childClass extends finalclass
{
void method()
{
JAVA (UGCA-1932)
UNIT-II

[Link]("this is the childClass");


}
}
class MainClass
{
public static void main(String arg[])
{
finalclass fx = new childClass();
[Link]();
}
}
OUTPUT

So from the above code output, we can clearly see that it will throw a compilation error because
the class is declared as final. This proves that we cannot inherit from the final class in Java.

You might also like