0% found this document useful (0 votes)
0 views

Oop Thr Java-unit 1 (1)

The document outlines the course objectives and outcomes for Object-Oriented Programming (OOP) through Java, emphasizing key concepts such as inheritance, multithreading, and GUI programming. It provides an overview of Java's history, editions, and types of applications, while contrasting procedural programming with object-oriented programming. Additionally, it explains core OOP principles like abstraction, encapsulation, inheritance, and polymorphism, and discusses the importance of these concepts in managing complexity and improving code reusability.
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)
0 views

Oop Thr Java-unit 1 (1)

The document outlines the course objectives and outcomes for Object-Oriented Programming (OOP) through Java, emphasizing key concepts such as inheritance, multithreading, and GUI programming. It provides an overview of Java's history, editions, and types of applications, while contrasting procedural programming with object-oriented programming. Additionally, it explains core OOP principles like abstraction, encapsulation, inheritance, and polymorphism, and discusses the importance of these concepts in managing complexity and improving code reusability.
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/ 72

OOP through Java UNIT-1

OBJECT ORIENTED PROGRAMMING


THROUGH JAVA (R22)
II B. Tech - II Semester

P.Ramesh, Assistant Professor, AIML Dept, TKREC 1


OOP through Java UNIT-1

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Course Objectives:

 To understand the basic object-oriented programming concepts and apply them in


problem solving.
 To illustrate inheritance concepts for reusing the program.
 To demonstrate multitasking by using multiple threads and event handling
 To develop data-centric applications using JDBC.
 To understand the basics of java console and GUI based programming

Course Outcomes:
 Demonstrate the behavior of programs involving the basic programming constructs like
control structures, constructors, string handling and garbage collection.
 Demonstrate the implementation of inheritance (multilevel, hierarchical and multiple) by
using extend and implement keywords
 Use multithreading concepts to develop inter process communication.
 Understand the process of graphical user interface design and implementation using AWT
or swings.
 Develop applets that interact abundantly with the client environment and deploy on the
server

P.Ramesh, Assistant Professor, AIML Dept, TKREC 2


OOP through Java UNIT-1

UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents,
responsibility, messages, methods, History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion and
casting, simple java program, concepts of classes, objects, constructors, methods, access control,
this keyword, garbage collection, overloading methods and constructors, method binding,
inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes,
exploring string class.

Object oriented thinking and Java Basics: OOP stands for Object-Oriented
Programming. Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and methods.

Object-oriented programming (OOP) is a fundamental programming paradigm based on the


concept of “objects”. These objects can contain data in the form of fields (often known as
attributes or properties) and code in the form of procedures (often known as methods).
The core concept of the object-oriented approach is to break complex problems into smaller
objects.

Java is a high-level, general-purpose, object-oriented, and secure programming language


developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In
1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem takeover by Oracle
Corporation.

Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
 Java Standard Editions (JSE): It is used to create programs for a desktop computer.
 Java Enterprise Edition (JEE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
 Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java programming:
 Standalone Applications: Java standalone applications uses GUI components such as
AWT, Swing, and JavaFX. These components contain buttons, list, menu, scroll panel, etc.
It is also known as desktop alienations.
 Enterprise Applications: An application which is distributed in nature is called
enterprise applications.
 Web Applications: An applications that run on the server is called web applications. We
use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.
 Mobile Applications: Java ME is a cross-platform to develop mobile applications which
run across smartphones. Java is a platform for App Development in Android.

P.Ramesh, Assistant Professor, AIML Dept, 3


TKREC
OOP through Java UNIT-1

Need for OOP Paradigm: Traditionally, the structured programming techniques were used
earlier. There were many problems because of the use of structured programming technique.
The structured programming made use of a top-down approach. To overcome these problems
the object-oriented programming concept was created.

The object-oriented programming makes use of bottom-up approach. It also manages the
increasing complexity. The description of an object-oriented program can be given as, a data that
controls access to code. The object-oriented programming technique builds a program using the
objects along with a set of well-defined interfaces to that object.

The object-oriented programming technique is a paradigm, as it describes the way in which


elements within a computer program must be organized. It also describes how those elements
should interact with each other.

Whereas in OOP paradigm, the data and methods are tightly coupled to form objects. These
objects help to build structure models of the problem domain and enables to get effective
solutions. OOP uses various principles (or) concepts such as abstraction, inheritance,
encapsulation and polymorphism. With the help of abstraction, the implementation is hidden
and the functionality is exposed. Use of inheritance can eliminate redundant code in a program.
Encapsulation enables the data and methods to wrap into a single entity. Polymorphism enables
the reuse of both code and design.

Why do we need the object-oriented programming paradigm?

Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than produced using traditional techniques.

Object orientation techniques work more efficiently than traditional techniques due to the
following reasons.
 The higher level of abstraction: Top-down approach support abstraction at the
Functional level while object-oriented approach support abstraction at the object level.
 The seamless transition among different software development phases: It uses the
same language for all phases, which reduces the level of complexity and redundancy
makes software development clear and robust.
 Good programming practice: The subroutine and attributes of a class are held together
tightly.
 Improves reusability: it supports inheritance due to which classes can be built from
each other. So only difference and enhancement between classes need to be designed and
coded. All the previous functionality remains as it is and can be used without change.

Procedural and object-oriented programming paradigms

Procedure Oriented Programming Object Oriented Programming


(POP) (OOP)

P.Ramesh, Assistant Professor, AIML Dept, 4


TKREC
OOP through Java UNIT-1

POP follows a top-down approach. OOP takes a bottom-up approach


indesigning a program.

Program is divided into small chunks Program is divided into


basedon the functions. objectsdepending on the
problem.
Functions are more important than The main priority is data rather
data ina program. thanfunctions in a program.

No support for data hiding. Data hiding is possible in OOP.

No such concept of inheritance in POP. Inheritance is allowed in OOP.

Different parts of a program The functions of the objects are


areinterconnected via parameter linkedvia message passing.
passing.
Operator overloading is not allowed. Operator overloading is allowed.

Exception Handling is not present. Exception Handling is done with


Try andCatch block.

Ex: C, Pascal, Fortran. Ex: C++, Java

Summary of Object-Oriented concepts:


OOP stands for Object-Oriented Programming. OOP is a programming paradigm i n
which every program is follows the concept of object. In other words, OOP is a way
of writing programs based on the object concept.

The object-oriented programming paradigm has the following core concepts.


Object
Class
Abstraction
Encapsulation
Inheritance
Polymorphism

Object: Any entity that has state and behavior is known as an object. For
example:chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class: Class is a blueprint/template to create n no. of objects. It is a logical entity.


Inheritance: When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtimepolymorphism.

Abstraction: Hiding internal details and showing functionality is known as abstraction.


For example: phone call, we don't know the internal processing. In the abstraction
concept, we do not show the actual implementation to the end user, instead we provide
only essential things. For example, if we want to drive a car, we do not need to

P.Ramesh, Assistant Professor, AIML Dept, 5


TKREC
OOP through Java UNIT-1

know about the internal functionality like how wheel system works, how brake
system works and how music system works etc.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation: Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with different
medicines. A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.

P.Ramesh, Assistant Professor, AIML Dept, 6


TKREC
OOP through Java UNIT-1

Inheritance: Inheritance is the process of acquiring properties and behaviors from


one object to another object or one class to another class. In inheritance, we derive
a new class from the existing class. Here, the new class acquires the properties and
behaviors from the existing class. In the inheritance concept, the class which
provides properties is called as parent class and the class which receives the
Properties is called as child class. The parent class is also known as base class or super
class. The child class is also known as derived class or sub class.

Polymorphism: When one task is performed by different ways known as


polymorphism. For example: to convince the customer differently, to draw something
e.g. Shape or rectangle etc.

In java, we use method overloading and method overriding to achieve


polymorphism. Another example can be to speak something e.g. cat speaks meaw,
dog barks woof etc.

Benefits of Inheritance:
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent
code exists in two related classes, the hierarchy can usually be re-factored to move
the common code up to a mutual super class. This also tends to result in a better
organization of code and smaller, simpler compilation units.

Inheritance can also make application code more flexible to change because classes
that inherit from a common super class can be used interchangeably. If the return

P.Ramesh, Assistant Professor, AIML Dept, 7


TKREC
OOP through Java UNIT-1

type of a method is super class

 Reusability: facility to use public methods of base class without rewriting the
same.
 Extensibility: extending the base class logic as per business logic of the
derivedclass. 
 Data hiding: base class can decide to keep some data private so that it
cannot bealtered by the derived class

Coping with complexity


The size and complexity of a small program is small and simple. Whereas, the size and
complexity of a large application program is large and hard. The complexity in dealing with the
problems to build a large application depends on the 'composition' and 'abstraction'
mechanisms

Abstraction mechanisms.
In object-oriented programming, abstraction is one of three central principles (along with
encapsulation and inheritance). Through the process of abstraction, a programmer hides all but
the relevant data about an object in order to reduce complexity and increase efficiency.

A Way of Viewing the World: To illustrate the major ideas in object-oriented


programming, let us consider how we might go about handling a real-world
situation and then ask how we could make the computer more closely model the
techniques employed.

Suppose I wish to send flowers to a friend who lives in a city many miles away. Let
me call my friend Sally. Because of the distance, there is no possibility of my picking the
flowers and carrying them to her door myself. Nevertheless, sending her the flowers is
an easy enough task; I merely go down to my local Florist (who happens to be named
Flora), tell her the variety and quantity of flowers I wish to send and give her Sally's
address, and I can be assured the flowers will be delivered expediently and
automatically.

An object oriented program is structured as a community of interacting agents,


called objects. Each object has a role to play. Each object provides a service, or
performs an action, that is used by other members of the community.

P.Ramesh, Assistant Professor, AIML Dept, 8


TKREC
OOP through Java UNIT-1

The community of agents helping me.

Another example of a real-world situation.


Let us consider a situation, I am at my office and I wish to get food to my family
members who are at my home from a hotel. Because of the distance from my office to
home, there is no possibility of getting food from a hotel myself. So, how do we solve the
issue?

To solve the problem, let me call zomato (an agent in food delivery community), tell
them the variety and quantity of food and the hotel name from which I wish to
deliver the foodto my family members. Look at the following image.

Agents and Communities


To solve my food delivery problem, I used a solution by finding an appropriate agent
(Zomato) and pass a message containing my request. It is the responsibility of the agent
(Zomato) to satisfy my request. Here, the agent uses some method to do this. I do not
need to know the method that the agent has used to solve my request. This is usually
hidden from me. So, in object-oriented programming, problem-solving is the solution
to our problem which requires the help of many individuals in the community. We
may describe agentsand communities as follows.

An object-oriented program is structured as a community of interacting agents, called


objects, where each object provides a service (data and methods) that is used by other
members of the community. In our example, the online food delivery system is a
community in which the agents are zomato and set of hotels. Each hotel provides a
variety of services that can be used by other members like zomato, me and my
family in the community.

P.Ramesh, Assistant Professor, AIML Dept, 9


TKREC
OOP through Java UNIT-1

Responsibilities:
In object-oriented programming, behaviors of an object described in terms of
responsibilities. In our example, my request for action indicates only the desired
outcome (food deliveredto my family). The agent (zomato) is free to use any technique
that solves my problem. By discussing a problem in terms of responsibilities increases
the level of abstraction. This enables more independence between the objects in
solving complex problems.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which led to still
more requests among the members of the community until my request has done.
Here, the members of a community interact with one another by making requests
until the problem has satisfied.

In object-oriented programming, every action is initiated by passing a message to an


agent (object), which is responsible for the action. The receiver is the object to
whom the message was sent. In response to the message, the receiver performs some
method to carry out the request. Every message may include any additional
information as arguments. In our example, I send a request to zomato with a
message that contains food items, the quantity of food, and the hotel details. The
receiver uses a method to food get deliveredto my home.

An Overview of Java:
Java is a computer programming language. Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++,
Small Talk, etc. These languages had few disadvantages which were corrected in
Java. Java was invented by a team of 13 employees of Sun Microsystems, Inc. which
is lead by James Gosling, in 1991. The team includes persons like Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan, etc. Java was developed as a part of the
Green project. Initially, it was called Oak, later it was changed to Java in 1995.

History of Java
 The C language developed in 1972 by Dennis Ritchie had taken a decade to
become the most popular language. 
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language
with included OOP fundamentals and features. 
 A project named “Green” was initiated in December of 1990, whose aim was
to create a programming tool that could render obsolete the C and C++
programming languages.
 Finally in the year of 1991 the Green Team was created a new Programming

P.Ramesh, Assistant Professor, AIML Dept, 10


TKREC
OOP through Java UNIT-1

language named “OAK”.


 After some time they found that there is already a programming language with
the name “OAK”.
 So, the green team had a meeting to choose a new name. After so many
discussions they want to have a coffee. They went to a Coffee Shop which is
just outside of the Gosling’s office and there they have decided name as
“JAVA”. 
Execution Process of Java Program:
The following three steps are used to create and execute a java program.
 Create a source code (.java file). 
 Compile the source code using javac command. 
 Run or execute .class file uisng java command. 

Java Buzz Words


Java is the most popular object-oriented programming language. Java has many
advanced features, a list of key features is known as Java Buzz Words.

The java team has listed the following terms as java buzz words.
 Simple 
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded 
 Interpreted
 High performance
 Distributed
 Dynamic 

P.Ramesh, Assistant Professor, AIML Dept, 11


TKREC
OOP through Java UNIT-1

Simple: Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java follow basic programming language C and object-
oriented programming concepts are similar to C++. In a java programming language,
many complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes
java simpler.

Secure: Java is said to be more secure programming language because it does not
have pointers concept, java provides a feature "applet" which can be embedded into
a web application. The applet in java does not allow access to other parts of the
computer, which keeps away from harmful programs like viruses and unauthorized
access.

Portable: Portability is one of the core features of java which enables the java
programs to run on any computer or operating system. For example, an applet
developed using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.

Object-oriented: Java is said to be a pure object-oriented programming language.


In java, everything is an object. It supports all the features of the object-oriented
programming paradigm. The primitive data types java also implemented as objects
using wrapper classes, but still, it allows primitive data types to archive high-
performance.

Robust: Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism,and many more.

Architecture-neutral (or) Platform Independent: Java has invented to archive


"write once; run anywhere, anytime, forever". The java provides JVM (Java Virtual
Machine) to archive architectural-neutral or platform-independent. The JVM allows
the java program created using one operating system can be executed on any other
operating system.

Multi-threaded: Java supports multi-threading programming, which allows us to


write programs that do multiple operations simultaneously.

Interpreted: Java enables the creation of cross-platform programs by compiling


into an intermediate representation called Java bytecode. The byte code is
interpreted to any machine code so that it runs on the native machine.

High performance: Java provides high performance with the help of features like
JVM, interpretation, and its simplicity.

Distributed: Java programming language supports TCP/IP protocols which enable the
java to support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods across a

P.Ramesh, Assistant Professor, AIML Dept, 12


TKREC
OOP through Java UNIT-1

network.

Dynamic: Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and de-
allocation (objects and garbage collector).

Java Data Types:


Java programming language has a rich set of data types. The data type is a
category ofdata stored in variables. In java, data types are classified into two types and
they are as follows.

 Primitive Data Types


 Non-primitive Data Types

Primitive Data Types:


The primitive data types are built-in data types and they specify the type of value
stored in a variable and the memory size. The primitive data types do not have any
additional methods.

In java, primitive data type includes byte, short, int, long, float, double, char, and
boolean.

The following table provides more description of each primitive data type.

Data Memory Default


type Meaning size Range Value

Byte Whole numbers 1 byte -128 to +127 0

Short Whole numbers 2 bytes -32768 to +32767 0

P.Ramesh, Assistant Professor, AIML Dept, 13


TKREC
OOP through Java UNIT-1

Int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

Long Whole numbers 8 bytes -9,223,372,036,854,775,808 to 0L


+9,223,372,036,854,775,807

Float Fractional 4 bytes - 0.0f


numbers

Double Fractional 8 bytes - 0.0d


numbers

Char Single character 2 bytes 0 to 65535 \u0000

Boolean unsigned char 1 bit 0 or 1 0 (false)

Let's look at the following example java program to illustrate primitive data types in
javaand their default values.

Example
public class PrimitiveDataTypes
{
byte i; short j; int k; long l; float m;
double n; char ch; boolean p;
public static void main(String[] args)
{
PrimitiveDataTypes obj = new PrimitiveDataTypes();
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}
OUTPUT:
D:\TKREC\Java>java PrimitiveDataTypes
i = 0, j = 0, k = 0, l = 0
m = 0.0, n = 0.0
ch =
p = false

Non-primitive Data Types


In java, non-primitive data types are the reference data types or user-created
data types. All non-primitive data types are implemented using object concepts. Every
variable of the non-primitive data type is an object. The non-primitive data types may
use additional methods to perform certain operations. The default value of non-
primitive data type variable is null.

In java, examples of non-primitive data types are String, Array, List, Queue, Stack,
Class, Interface, etc.
P.Ramesh, Assistant Professor, AIML Dept, 14
TKREC
OOP through Java UNIT-1

Example:
public class NonPrimitiveDataTypes
{
String str;
public static void main(String[] args)
{
String name = "B Tech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str); //using addition method
System.out.println(wish.concat(name));
}
}
OUTPUT:
D:\TKREC\Java>java NonPrimitiveDataTypes
str = null
Hello, B Tech Smart Class!

Primitive Vs Non-primitive Data Types

Primitive Data Type Non-primitive Data Type


These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all

Java Variables: A variable is a named memory location used to store a data


value. Avariable can be defined as a container that holds a data value.

In java, we use the following syntax to create variables.

Syntax:
data_type variable_name; (or)
data_type variable_name_1; (or)
data_type variable_name = value; (or)
data_type variable_name_1 = value;

Scope and lifetime of variables


In java programming language variables are classified as follows.

P.Ramesh, Assistant Professor, AIML Dept, 15


TKREC
OOP through Java UNIT-1

1. Local variables
2. Instance variables or Member variables or Global variables
3. Static variables or Class variables
4. Final variables

Local variables: The variables declared inside a method or a blocks are known as local
variables. A local variable is visible within the method in which it is declared. The local
variable is created when execution control enters into the method or block and
destroyed after the method or block execution completed.

Example:
public class LocalVariables
{
public void show()
{
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
System.out.println("Inside display method, a = " + a);
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java LocalVariables
Inside show method, a = 10
Inside display method, b = 20
Instance variables or member variables or global variables: The variables
declared inside a class and outside any method, constructor or blocks are known as
instance variables or member variables. These variables are visible to all the
methods of the class. The changes made to these variables by method affectsall the
methods in the class. These variables are created separate copy for every object of
that class.

Example
public class ClassVariables
{

P.Ramesh, Assistant Professor, AIML Dept, 16


TKREC
OOP through Java UNIT-1

int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args)
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java ClassVariables
Inside show method, x = 100
Inside display method, x = 200
Static variables or Class variables: A static variable is a variable that declared using
static keyword. The instance variables can be static variables but local variables cannot.
Static variables are initialized only once, at the start of the program execution. The
static variable only has one copy per class irrespective of how many objects we
create.

The static variable is access by using class name.

Example
public class StaticVariablesExample
{
int x, y; // Instance variables
static int z; // Static variable
StaticVariablesExample(int x, int y)
{
this.x = x;
this.y = y;
}
public void show()
{
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args)
{

P.Ramesh, Assistant Professor, AIML Dept, 17


TKREC
OOP through Java UNIT-1

StaticVariablesExample obj_1 = new StaticVariablesExample(10, 20);


StaticVariablesExample obj_2 = new StaticVariablesExample(100, 200);
obj_1.show();
StaticVariablesExample.z = 1000;
obj_2.show();
}
}
OUTPUT:
D:\TKREC\Java>java StaticVariablesExample
Inside show method,
x = 10, y = 20, z = 0
Inside show method,
x = 100, y = 200, z = 1000

Final variables: A final variable is a variable that declared using final keyword. The
final variable isinitialized only once, and does not allow any method to change it's
value again. The variable created using final keyword acts as constant. All variables
like local,instance and static variables can be final variables.

Example
public class FinalVariableExample
{
final int a = 10;
void show()
{
System.out.println("a = " + a);
// a = 20; Error due to final variable cann't be modified
}
public static void main(String[] args)
{
FinalVariableExample obj = new FinalVariableExample();
obj.show();
}
}
OUTPUT:
D:\TKREC\Java>javac FinalVariableExample.java
FinalVariableExample.java:6: error: cannot assign a value to final variable a
a = 20; //Error due to final variable cann't be modified
1 error
D:\TKREC\Java>java FinalVariableExample
a = 10

Java Arrays
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at
a time.

P.Ramesh, Assistant Professor, AIML Dept, 18


TKREC
OOP through Java UNIT-1

In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values. The index value of an array
starts with '0' and ends with 'size-1'. We use the index value to access individual
elements of an array. In java, there are two types of arrays and they are as follows.

1. One Dimensional Array


2. Multi Dimensional Array

Creating an array: In the java programming language, an array must be created using
new operator and with a specific size. The size must be an integer value but not a byte,
short, or long. We use the following syntax to create an array.

Syntax
data_type array_name[ ] = new data_type[size]; (or)
data_type[ ] array_name = new data_type[size];

Example
public class ArrayExample
{
public static void main(String[] args)
{
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}

OUTPUT:
D:\TKREC\Java>java ArrayExample
Value at index 0 - 10
Length of the array - 5

In java, an array can also be initialized at the time of its declaration. When an array is
initialized at the time of its declaration, it need not specify the size of the array and
useof the new operator. Here, the size is automatically decided based on the number
of values that are initialized.

Example: int list[ ] = {10, 20, 30, 40, 50};

NullPointerException with Arrays: In java, an array created without size and


initializedto null remains null only. It does not allow us to assign a value. When we try
to assign a value it generates a NullPointerException.

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

P.Ramesh, Assistant Professor, AIML Dept, 19


TKREC
OOP through Java UNIT-1

{
short list[] = null;
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
OUTPUT:
D:\TKREC\Java>java ArrayExample1
Exception in thread "main" java.lang.NullPointerException: Cannot store to short
array because "<local1>" is null
at ArrayExample1.main(ArrayExample1.java:6)

ArrayIndexOutOfBoundsException with Arrays: In java, the JVM (Java Virtual


Machine) throws ArrayIndexOutOfBoundsException when an array is trying to access
with an index value of negative value, value equal to array size, or value more than
the array size.

Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
OUTPUT:
D:\TKREC\Java>java ArrayExample2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4
out of bounds for length 3
at ArrayExample2.main(ArrayExample2.java:6)

Looping through an array: An entire array is accessed using either simple for statement
or for-each statement. Look at the following example program to display sum of all the
elements in a list.

Example
import java.util.Scanner;
public class Arrayloops
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);

P.Ramesh, Assistant Professor, AIML Dept, 20


TKREC
OOP through Java UNIT-1

System.out.print("Enter size of the array:");


n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter array elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum of the array is:"+sum);
}
}
OUTPUT:
D:\TKREC\Java>java Arrayloops
Enter size of the array: 3
Enter array elements:
1
3
5
Sum of the array is: 9
Multidimensional Array: In java, we can create an array with multiple dimensions. We
can create 2-dimensional, 3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional
array variable, specify each additional index using another set of square brackets.

Weuse the following syntax to create two-dimensional array.


Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];

When we create a two-dimensional array, it created with a separate index for rows
and columns. The individual element is accessed using the respective row index
followed by the column index.

A multidimensional array can be initialized while it has created using the following
syntax.

Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

When an array is initialized at the time of declaration, it need not specify the size of
the array and use of the new operator. Here, the size is automatically decided based
on the number of values that are initialized.

P.Ramesh, Assistant Professor, AIML Dept, 21


TKREC
OOP through Java UNIT-1

Example: int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two columns.

Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java
providesa rich set of operators.
In java, operators are classified into the following four types.
1. Arithmetic Operators
2. Relational (or) Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Conditional Operators
Let's look at each operator in detail.
1. Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical
operations like addition, subtraction, multiplication, division, modulus, increment,
decrement, etc.,

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Modulus - Remainder of the Division 5%2=1

++ Increment a++

-- Decrement a--

2. Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values.
That means the relational operators are used to check the relationship between two
values. Every relational operator has two possible results either TRUE or FALSE. In
simple words,the relational operators are used to define conditions in a program. The
following table provides information about relational operators.

Operator Meaning Example

P.Ramesh, Assistant Professor, AIML Dept, 22


TKREC
OOP through Java UNIT-1

< Returns TRUE if the first value is smaller than 10 < 5 is FALSE
second value otherwise returns FALSE

> Returns TRUE if the first value is larger than 10 > 5 is TRUE
second value otherwise returns FALSE

<= Returns TRUE if the first value is smaller than or 10 <= 5 is FALSE
equal to second value otherwise returns FALSE

>= Returns TRUE if the first value is larger than or 10 >= 5 is TRUE
equal to second value otherwise returns FALSE

== Returns TRUE if both values are equal 10 == 5 is FALSE


otherwise returns FALSE

!= Returns TRUE if both values are not equal 10 != 5 is TRUE


otherwise returns FALSE

3. Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into
one condition. The following table provides information about logical operators.

Operator Meaning Example

& Logical AND - Returns TRUE if all conditions are false & true => false
TRUE otherwise returns FALSE

| Logical OR - Returns FALSE if all conditions are false | true => true
FALSE otherwise returns TRUE

^ Logical XOR - Returns FALSE if all conditions are true ^ true => false
same otherwise returns TRUE

! Logical NOT - Returns TRUE if condition is FLASE !false => true


and returns FALSE if it is TRUE

&& Short-circuit AND - Similar to Logical AND (&), false & true => false
but once a decision is finalized it does not
evaluate remaining.

|| Short-circuit OR - Similar to Logical OR (|), but


oncea decision is finalized it does not evaluate
remaining.

P.Ramesh, Assistant Professor, AIML Dept, 23


TKREC
OOP through Java UNIT-1

4. Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to
the left- hand side variable (Lvalue). The assignment operator is used in different
variants along with arithmetic operators. The following table describes all the
assignment operators in the java programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable

-= Subtract right-hand side value from left-hand side variable A -= B


value and store the result into left-hand side variable

*= Multiply right-hand side value with left-hand side variable A *= B


value and store the result into left-hand side variable

/= Divide left-hand side variable value with right-hand side A /= B


variable value and store the result into the left-hand side
variable

%= Divide left-hand side variable value with right-hand side A %= B


variable value and store the remainder into the left-hand
side variable
&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

5. Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on
binary values.
The following table describes all the bitwise operators in the java programming
language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).


Operator Meaning Example

P.Ramesh, Assistant Professor, AIML Dept, 24


TKREC
OOP through Java UNIT-1

& the result of Bitwise AND is 1 if all A & B⇒ 16 (10000)


the bits are 1 otherwise it is 0

| the result of Bitwise OR is 0 if all A | B⇒ 29 (11101)


the bits are 0 otherwise it is 1

^ the result of Bitwise XOR is 0 if all A ^ B⇒ 13 (01101)


the bits are same otherwise it is 1

~ the result of Bitwise once ~A⇒ 6 (00110)


complement is negation of the bit
(Flipping)

<< the Bitwise left shift operatorshifts A << 2⇒ 100 (1100100)


all the bits to the left by the
specified number of positions

>> the Bitwise right shift operator A >> 2⇒ 6 (00110)


shifts all the bits to the right by the
specified number of positions

6. Conditional Operators
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the condition
is FALSE the second option is performed.

The conditional operator is used with the following syntax.


Syntax: Condition ? TRUE Part : FALSE Part;
Example
public class ConditionalOperator
{
public static void main(String[] args)
{
int a = 10, b = 20, c;
c = (a>b)? a : b;
System.out.println("c = " + c);
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java ConditionalOperator
c = 20

Expressions
In any programming language, if we want to perform any calculation or to frame any

P.Ramesh, Assistant Professor, AIML Dept, 25


TKREC
OOP through Java UNIT-1

condition etc., we use a set of symbols to perform the task. These set of symbols
makes an expression. In the java programming language, an expression is defined as
follows.

An expression is a collection of operators and operands that represents a specific


value. In the above definition, an operator is a symbol that performs tasks like
arithmeticoperations, logical operations, and conditional operations, etc.

Operands are the values on which the operators perform the task. Here operand can
bea direct value or variable or address of memory location.

Expression Types: In the java programming language, expressions are divided into
THREE types. They are as follows.
1. Infix Expression
2. Postfix Expression
3. Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression- The expression in which the operator is used between


operands is called infix expression. The infix expression has the following general
structure.

Example

Postfix Expression: The expression in which the operator is used after operands is
called postfix expression. The postfix expression has the following general structure.

Example

Prefix Expression: The expression in which the operator is used before operands is
called a prefix expression. The prefix expression has the following general structure.

Example

Java Control Statements:


In java, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations. Sometimes,
we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
To solve this problem, java provides control statements.

P.Ramesh, Assistant Professor, AIML Dept, 26


TKREC
OOP through Java UNIT-1

In java, the control statements are the statements which will tell us that in
which order the instructions are getting executed. The control statements are used
to control the order of execution according to our requirements. Java provides
several control statements, and they are classified as follows.

Types of Control Statements: In java, the control statements are classified as follows.
 Selection Control Statements (Decision Making Statements)
 Iterative Control Statements (Looping Statements)
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements
or branching statements. The selection statements are used to select a part of the
program to be executed based on a condition. Java provides the following selection
statements.
 if statement
 if-else statement
 else-if statement
 nested if statement
 switch statement

Iterative Control Statements


In java, the iterative statements are also known as looping statements or repetitive
statements. The iterative statements are used to execute a part of the program
repeatedly as long as the given condition is True. Using iterative statements reduces
the size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed. Java provides the following iterative statements.
 while statement
 do-while statement
 for statement

P.Ramesh, Assistant Professor, AIML Dept, 27


TKREC
OOP through Java UNIT-1

 for-each statement

Jump Statements
In java, the jump statements are used to terminate a block or take the
execution controlto the next iteration. Java provides the following jump statements.
 break
 continue
 return

Java Selection Statements


In java, the selection statements are also known as decision making statements or
branching statements or conditional control statements. The selection statements
are used to select a part of the program to be executed based on a condition.

Java provides the following selection statements.


 if statement
 if-else statement
 nested if statement
 if-else if statement
 switch statement

if statement in java
In java, we use if statement to test a condition and decide the execution of a block of
statements based on that condition result. if statement checks, the given condition
then decides the execution of a block of statements. If the condition is true, then the
block of statements is executed and if it is False, then the block of statements is
ignored.

The syntax and execution flow of if the statement is as follows.

P.Ramesh, Assistant Professor, AIML Dept, 28


TKREC
OOP through Java UNIT-1

Example: -
class If
{
public static void main(String args[])
{
// defining age variable
int age=40;
// checking the age
if(age>30)
{
System.out.println("Age is Greater than 30");
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java If
Age is Greater than 30

if-else statement in java


In java, we use the if-else statement to test a condition and pick the execution of a
block of statements out of two blocks based on that condition result. The if-else
statement checks the given condition then decides which block of statements to be
executed based on the condition result. If the condition is True, then the true block of
statements is executed and if it is False, then the false block of statements is executed.

The syntax and execution flow of if-else statement is as follows.

Example: -
public class IfElse
{

P.Ramesh, Assistant Professor, AIML Dept, 29


TKREC
OOP through Java UNIT-1

public static void main(String[] args)


{
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java IfElse
odd number

Nested if statement in java


Writing an if statement inside another if-statement is called nested if statement. The
general syntax of the nested if-statement is as follows.

Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
}
}

Example: -
public class NestedIf
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}

P.Ramesh, Assistant Professor, AIML Dept, 30


TKREC
OOP through Java UNIT-1

}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java NestedIf
You are eligible to donate blood

if-else if statement in java


Writing an if-statement inside else of an if statement is called if-else-if statement.

Thegeneral syntax of an if-else-if statement is as follows.

Syntax
if(condition_1)
{
condition_1 true-block;
}
else if(condition_2)
{
condition_2 true-block;
condition_1 false-block too;
}
Example: -
public class IfElseIf
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
P.Ramesh, Assistant Professor, AIML Dept, 31
TKREC
OOP through Java UNIT-1

System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java IfElseIf
C grade
switch statement in java
Using the switch statement, one can select only one option from more number of
options very easily. In the switch statement, we provide a value that is to be compared
with a value associated with each option. Whenever the given value matches the value
associated with an option, the execution starts from that option. In the switch
statement, every option is defined as a case.

The switch statement has the following syntax and execution flow diagram.

P.Ramesh, Assistant Professor, AIML Dept, TKREC 32


OOP through Java UNIT-1

Example: -
public class Switch
{
public static void main(String[] args)
{
//Specifying month number
int month=8;
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");

P.Ramesh, Assistant Professor, AIML Dept, 33


TKREC
OOP through Java UNIT-1

}
//Printing month of the given number
System.out.println(monthString);
}
}
OUTPUT:
D:\TKREC\Java>java Switch
8 - August

Java Iterative Statements


The java programming language provides a set of iterative statements that are used
to execute a statement or a block of statements repeatedly as long as the given
condition is true. The iterative statements are also known as looping statements or
repetitive statements.

Java provides the following iterative statements.


 while statement
 do-while statement
 for statement
 for-each statement

while statement in java


The while statement is used to execute a single statement or block of statements
repeatedly as long as the given condition is TRUE. The while statement is also known
as Entry control looping statement.

Example:
while(num <= 10)
{
System.out.println(num);
num++;
}
Example: -
public class While
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
}
}

P.Ramesh, Assistant Professor, AIML Dept, 34


TKREC
OOP through Java UNIT-1

OUTPUT:
D:\TKREC\Java>java While
1
2
3
4
5

do-while statement in java: The do-while statement is used to execute a single


statement or block of statements repeatedly as long as given the condition is TRUE.
The do-while statement is also known as the Exit control looping statement.
The do-while statement has the following syntax.
Example:
do
{
System.out.println(num);
num++;
}
while(num <= 10);

Example: -
public class DoWhile
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=5);
}
}
OUTPUT:
D:\TKREC\Java>java DoWhile
1
2
3
4
5

for statement in java: The for statement is used to execute a single statement
or a block of statements repeatedly as long as the given condition is TRUE.

Example:
for(int i = 0; i < 10; i++)

P.Ramesh, Assistant Professor, AIML Dept, 35


TKREC
OOP through Java UNIT-1

{
System.out.println("i = " + i);
}
Example: -
public class For
{
public static void main(String[] args)
{
//Code of Java for loop
for(int i=1;i<=4;i++)
{
System.out.println(i);
}
}
}
OUTPUT:
D:\TKREC\Java>java For
1
2
3
4

for-each statement in java: The Java for-each statement was introduced since Java
5.0 version. It provides an approach to traverse through an array or collection in
Java. The for-each statement also known as enhanced for statement. The for-each
statement executes the block of statements for each element of the given array or
collection.

Example:
for(int i : arrayList)
{
System.out.println("i = " + i);
}

Example: -
public class ForEach
{
public static void main(String[] args)
{
//Declaring an array
int arr[]={12,23,44,56,78};

P.Ramesh, Assistant Professor, AIML Dept, 36


TKREC
OOP through Java UNIT-1

//Printing array using for-each loop


for(int i:arr)
{
System.out.println(i);
}
}
}
OUTPUT:
D:\TKREC\Java>java ForEach
12
23
44
56
78

Java Jump Statements:


The java programming language supports jump statements that used to transfer
execution control from one line to another line. The java programming language
providesthe following jump statements.

break statement: The break statement in java is used to terminate a switch or


looping statement. That means the break statement is used to come out of a switch
statementand a looping statement like while, do-while, for, and for-each.

The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop
Example: -
public class Break
{
public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
break;
}
System.out.println(i);

P.Ramesh, Assistant Professor, AIML Dept, 37


TKREC
OOP through Java UNIT-1

}
}
}
OUTPUT:
D:\TKREC\Java>java Break
1
2
3
4

// Java Break Statement with Inner Loop


// It breaks inner loop only if you use break statement inside the inner loop.
//inside an inner loop
public class Break1
{
public static void main(String[] args)
{
//outer loop
for(int i=1;i<=3;i++)
{
//inner loop
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
//using break statement inside the inner loop
break;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
D:\TKREC\Java>java Break1
11
12
13
21
31
P.Ramesh, Assistant Professor, AIML Dept, 38
TKREC
OOP through Java UNIT-1

32
33

continue statement: The continue statement is used to move the execution control to
the beginning of the looping statement. When the continue statement is encountered
in a looping statement, the execution control skips the rest of the statements in the
looping block and directly jumps to the beginning of the loop. The continue statement
can be used with looping statements like while, do-while, for, and for-each.
Example: -
//inside the for loop.
public class Continue
{
public static void main(String[] args)
{
//for loop
for(int i=1;i<=6;i++)
{
if(i==3)
{
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
OUTPUT:
D:\TKREC\Java>java Continue
1
2
4
5
6

labeled break and continue statements: The java programming language does not
support goto statement, alternatively, the break and continue statements can be used
with label.
Example: -
//with label inside an inner loop to continue outer loop
public class ContinueLabel
{

P.Ramesh, Assistant Professor, AIML Dept, 39


TKREC
OOP through Java UNIT-1

public static void main(String[] args) {


aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
//using continue statement with label
continue aa;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
D:\TKREC\Java >java ContinueLabel
11
12
13
21
31
32
33

return statement: In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling
function. That means the return statement transfer the execution control from called
function to the calling function by carrying a value.
Example: -
public class ReturnType
{
public int add() // without arguments
{
int x = 30;
int y = 70;
int z = x+y;
return z;
}

P.Ramesh, Assistant Professor, AIML Dept, 40


TKREC
OOP through Java UNIT-1

public static void main(String args[])


{
ReturnType r = new ReturnType();
int add = r.add();
System.out.println("The sum of x and y is: " + add);
}
}
OUTPUT:
D:\TKREC\Java >java ReturnType
The sum of x and y is: 100

Type conversion and casting

The two terms type casting and the type conversion are used in a program to convert one data
type to another data type. The conversion of data type is possible only by the compiler when they
are compatible with each other.

Type conversion
If a data type is automatically converted into another data type at compile time is known as type
conversion. The conversion is performed by the compiler if both data types are compatible with
each other

Example
Converting an int into long and long into float
int i=100;
long l=I;
float f=l;

i value is 100
l value is 100
f value is 100.0

Widening primitive conversion (Implicitly): Conversion of narrow (Smaller) datatype value to


wider (Larger) datatype is called widening primitive conversion, which happens implicitly.

Ex: byte con be converted to int type easily without losing data
byte-->short-->int-->long-->float-->double

Narrowing primitive conversion (Explicitly): Conversion of wider (Larger) datatype value to


narrow (Smaller) datatype is called widening primitive conversion, which requires explicit type
conversion

Ex: conversion float to int type will not convert implicitly and require some explicit casting
double-->float-->long-->int-->short -->byte

Note: while doing explicit type casting, we may lose some amount of actual data.

P.Ramesh, Assistant Professor, AIML Dept, 41


TKREC
OOP through Java UNIT-1

Type casting: When a datatype is converted into another datatype by a programmer


or user while writing a program code in any language is called type.

If both are incompatible types, we must type casting

Example
Converting a double into long and long into int
double d=100.0;
long l=(long)d;
int i=(int)l;

d value is 100.0
l value is 100
i value is 100

Note: Type conversion done by the compiler and type casting done by the user

Example
class TypeConversion
{
public static void main(String[] args)
{
int x = 10;
float y;
//automatically converts the integer type into float type
y = x;
System.out.println("After conversion, float value "+ y);
}
}
OUTPUT:
D:\TKREC\Java >java TypeConversion
After conversion, float value 10.0

Example
class TypeCasting
{
public static void main(String[] args)
{
double d=10.05;
long l= (long)d;
int i=(int)l;
System.out.println("The value of d is:"+d);
System.out.println("After conversion, l is:"+l);
System.out.println("After conversion, i is:"+i);
}
}

P.Ramesh, Assistant Professor, AIML Dept, 42


TKREC
OOP through Java UNIT-1

OUTPUT:
D:\TKREC\Java >java TypeCasting
The value of d is :10.05
After conversion, l is: 10
After conversion, i is: 10

Simple java program

/* This is a simple Java program. Call this file "Example.java". */

class Example
{

// Your program begins with a call to main().


public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
OUTPUT:
D:\TKREC\Java>java Example
This is a simple Java program.

Concepts of Classes:
Java is an object-oriented programming language, so everything in java program
must be based on the object concept. In a java programming language, the class
concept definesthe skeleton of an object.

The java class is a template of an object. The class defines the blueprint of an
object. Every class in java forms a new data type. Once a class got created, we can
generate as many objects as we want. Every class defines the properties and
behaviors of an object. All the objects of a class have the same properties and
behaviors that were defined in theclass.

Every class of java programming language has the following characteristics.


 Identity - It is the name given to the class.
 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

P.Ramesh, Assistant Professor, AIML Dept, 43


TKREC
OOP through Java UNIT-1

Look at the following picture to understand the class and object concept.

Creating a Class: In java, we use the keyword class to create a class. A class in java
contains properties as variables and behaviors as methods. Following is the syntax of
class in the java.

Syntax
class <ClassName>
{
data members declaration;
methods defination;
}

Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
classis said to be instantiated. All the objects that are created using a single class have
the same properties and methods. But the value of properties is different for every
object. Following is the syntax of class in the java.

Syntax: <ClassName> <objectName> = new <ClassName>( );

Object and Class Example: main within the class

Example: -

//Defining a Class.
class DefiningClass
{
//defining fields
int id;//field or data member or instance variable

P.Ramesh, Assistant Professor, AIML Dept, 44


TKREC
OOP through Java UNIT-1

String name;

//creating main method inside the DefiningClass


public static void main(String args[])
{
//Creating an object or instance
DefiningClass d=new DefiningClass();//creating an object of DefiningClass

//Printing values of the object


System.out.println(d.id);//accessing member through reference variable
System.out.println(d.name);
}
}

OUTPUT:
D:\TKREC\Java>java DefiningClass
0
Null

Object and Class Example: Initialization through reference


Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable

Example: -

// Intializing Object (OR) Creating Object

class CreatingObject
{
int id;
String name;
}
class Intialization
{
public static void main(String args[])
{
CreatingObject obj=new CreatingObject();
obj.id=546;
obj.name="Siri";
System.out.println(obj.id+" \n "+obj.name); //printing members with a white space
}
}

OUTPUT:
D:\TKREC\Java>java Intialization
546
Siri

P.Ramesh, Assistant Professor, AIML Dept, 45


TKREC
OOP through Java UNIT-1

Methods:
A method is a block of statements under a name that gets executes only when it is
called. Every method is used to perform a specific task. The major advantage of
methods is code re-usability (define the code once, and use it many times).

In a java programming language, a method defined as a behavior of an object. That


means, every method in java must belong to a class. Every method in java must be
declared inside a class.

Every method declaration has thefollowing characteristics.


 returnType - Specifies the data type of a return value.
 name - Specifies a unique name to identify it.
 parameters - The data values it may accept or receive.
 { } - Defines the block belongs to the method.

Creating a method: A method is created inside the class and it may be created with
anyaccess specifier. However, specifying access specifier is optional.

Following is the syntax for creating methods in java.

Syntax
class <ClassName>
{
<accessSpecifier> <returnType> <methodName>( parameters )
{
block of statements;
}
}
Calling a method: In java, a method call precedes with the object name of the class
to which it belongs and a dot operator. It may call directly if the method defined with
the static modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.

Syntax: <objectName>.<methodName>( actualArguments );

Variable arguments of a method: In java, a method can be defined with a variable


number of arguments. That means creating a method that receives any number of
arguments of the same data type.

Syntax: <returnType> <methodName>(dataType...parameterName);

How to Create and call a User-defined Method


Example: -
// creating a method and calling a method
import java.util.Scanner;
public class CreatingCallingMethod

P.Ramesh, Assistant Professor, AIML Dept, 46


TKREC
OOP through Java UNIT-1

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

//creating Scanner class object


Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
OUTPUT:
D:\TKREC\Java>java CreatingCallingMethod
Enter the number: 23
23 is odd

Constructor: A constructor in Java is similar to a method that is invoked when an


object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does
not have any return type.

 A constructor is a special method of a class that has the same name as the class
name.
 The constructor gets executes automatically on object creation. It does not
require the explicit method call.
 A constructor may have parameters and access specifies too.
 In java, if you do not provide any constructor the compiler automatically
creates a default constructor.

P.Ramesh, Assistant Professor, AIML Dept, 47


TKREC
OOP through Java UNIT-1

Example
class Demo
{
String name;
// constructor
Demo()
{
System.out.println("Constructor is called");
name="Java";
}
public static void main(String[] args)
{
// Constructor is invoked while creating on object of the Demo class
Demo obj = new Demo();
System.out.println("The Name is: " + obj.name);
}
}
OUTPUT:
D:\TKREC\Java>java Demo
Constructor is called
The Name is: Java

Types of Constructor
In Java, constructors can be divided into 3 types:
 No-Arg Constructor
 Parameterized Constructor
 Default Constructor

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 Test
{
int i;
// constructor with no parameter
Test()
{
i = 10;
System.out.println("Constructor is called");
}
public static void main(String[] args)
{
// calling the constructor without any parameter
Test obj = new Test();
System.out.println("Value of i is: " + obj.i);
}

P.Ramesh, Assistant Professor, AIML Dept, 48


TKREC
OOP through Java UNIT-1

OUTPUT:
D:\TKREC\Java>java Test
Constructor is called
Value of i is: 10

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

Example
class Main
{
String languages;
// constructor accepting single value
Main(String lang)
{
languages = lang;
System.out.println(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");
}
}
OUTPUT:
D:\TKREC\Java>java Main
Java Programming Language
Python Programming Language
C Programming Language

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.

Example
class Test
{
int a;
boolean b;
public static void main(String[] args)
{
// A default constructor is called

P.Ramesh, Assistant Professor, AIML Dept, 49


TKREC
OOP through Java UNIT-1

Test t = new Test();


System.out.println("Default Value:");
System.out.println("a = " + t.a);
System.out.println("b = " + t.b);
}
}
OUTPUT:
D:\TKREC\Java>java Test
Default Value:
a=0
b = false

Access control
Access Control in Java refers to the mechanism used to restrict or allow access to
certain parts of a Java program, such as classes, methods, and variables

In Java, the access specifiers (also known as access modifiers) used to restrict the
scope or accessibility (visibility) of a class, constructor, variable, method or data
member of class and interface.

In java, we cannot employ all access specifiers oneverything.


The following table describes where we can apply the access specifiers.

P.Ramesh, Assistant Professor, AIML Dept, 50


TKREC
OOP through Java UNIT-1

There are four access specifiers, and their list is below.


 Default (or) no modifier: - Declarations are visible only within the package (private
package)
 Private: - Declarations are visible only within the class only
 Protected: - Declarations are visible within the package or all subclasses
 Public: - Declarations are visible everywhere

Default: If we do not explicitly specify any access modifier for classes, methods,
variables, etc, then by default the default access modifier is considered.

Example

Save file A.java


package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

Save file B.java

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
OUTPUT:
D:\TKREC\Java>javac B.java
B.java:3: error: package pack does not exist
import pack.*;
^
B.java:8: error: cannot find symbol
A obj = new A();//Compile Time Error
^
symbol: class A
location: class B

Private: When variables and methods are declared private, they cannot be accessed
outside of the class

P.Ramesh, Assistant Professor, AIML Dept, 51


TKREC
OOP through Java UNIT-1

Example
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
d.name = "Java";
}
}
OUTPUT:
D:\TKREC\Java>javac Main.java
Main.java:16: error: name has private access in Data
d.name = "Java";
^
1 error

Protected: When methods and data members are declared protected, we can access
them within the same package as well as from subclasses.

Example
class Student
{
// protected method
protected void display()
{
System.out.println("I am a Student");
}
}
class siri extends Student
{
public static void main(String[] args)
{
// create an object of Dog class
siri s = new siri();
// access protected method
s.display();
}
}
OUTPUT:
D:\TKREC\Java>java siri
I am a Student

P.Ramesh, Assistant Professor, AIML Dept, 52


TKREC
OOP through Java UNIT-1

Here the protected method display() inside the Student class. Since protected methods can be
accessed from the child classes, we are able to access the method of Student class from the siri
class.

Note: We cannot declare classes or interfaces protected in Java

Public: When methods, variables, classes, and so on are declared public, then we can
access them from anywhere. The public access modifier has no scope restriction.

Example
class Student
{
// public variable
public int id;

// public method
public void display()
{
System.out.println("I am a Student.");
System.out.println(" My ID is:" +id);
}
}
// Main class
public class Main
{
public static void main( String[] args )
{
// accessing the public class
Student s = new Student();

// accessing the public variable


s.id = 546;
// accessing the public method
s.display();
}
}
OUTPUT:
D:\TKREC\Java>java Main
I am a Student.
My ID is: 546

In java, the accessibility of the members of a class or interface depends on its access
specifiers. The following table provides information about the visibility of both data
members and methods.

P.Ramesh, Assistant Professor, AIML Dept, 53


TKREC
OOP through Java UNIT-1

Example
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

P.Ramesh, Assistant Professor, AIML Dept, 54


TKREC
OOP through Java UNIT-1

}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
OUTPUT:
AccessModifiersExample.java:24: error: d has private access in ParentClass
System.out.println("d = " + d); // private member can't be accessed
^
1 error

D:\TKREC\Java>java AccessModifiersExample
Inside ParentClass
a = 10
b = 20
c = 30
d = 40
Inside ChildClass
a = 10
b = 20
c = 30

This keyword
In Java, this keyword is used to refer to the current object inside a method or a constructor

The most common use of this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter).

Example
class Student
{
// instance variables
int rollno;
String name;
Student(int rollno,String name) // formal parameters
{
this.rollno=rollno;
this.name=name;
}
void display()
{
System.out.println(rollno+" "+name);

P.Ramesh, Assistant Professor, AIML Dept, 55


TKREC
OOP through Java UNIT-1

}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"siri");
Student s2=new Student(112,"sai");
s1.display();
s2.display();
}
}
OUTPUT:
D:\TKREC\Java>java Test
111 siri
112 sai

Program where this keyword is not required

Example
class Student
{
// instance variables
int rollno;
String name;
Student(int r,String n) // formal parameters
{
rollno=r;
name=n;
}
void display()
{
System.out.println(rollno+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"xyz");
Student s2=new Student(112,"abc");
s1.display();
s2.display();
}
}
OUTPUT:
D:\TKREC\Java>java Test
111 xyz
P.Ramesh, Assistant Professor, AIML Dept, 56
TKREC
OOP through Java UNIT-1

112 abc

Garbage collection
Garbage collection in Java is the automated process of deleting code that's no longer needed or
used. This automatically frees up memory space and ideally makes coding Java apps easier for
developers. Java applications are compiled into bytecode that may be executed by a JVM.

Advantage of Garbage Collection


 It makes java memory efficient because 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.

Overloading methods
In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading.

Note: The return types of the above methods are not the same. It is because method overloading
is not associated with return types. Overloaded methods may have the same or different return
types, but they must differ in parameters.

Example
class Demo
{
void test()
{
System.out.println("No Parameter");
}
// Overload test for one integer parameter
void test(int a)
{
System.out.println("a is:"+a);
}
// Overload test for one String parameter
void test(String s)
{
System.out.println("s is:"+s);
}
// Overload test for one integer parameter
void test(int a, int b)
{
System.out.println("a and b is:"+a+ " "+b);
}
}
class Overload
{

P.Ramesh, Assistant Professor, AIML Dept, 57


TKREC
OOP through Java UNIT-1

public static void main(String[] args)


{
Demo d=new Demo();
// call all versions of test()
d.test();
d.test(10);
d.test("Hello");
d.test(20,30);
}
}
OUTPUT:
D:\TKREC\Java>java Overload
No Parameter
a is:10
s is: Hello
a and b is :20 30

// automatic type conversions apply to overloading

Example
class Demo
{
void test()
{
System.out.println("No Parameter");
}
// Overload test for one integer parameter
void test(int a, int b)
{
System.out.println("a and b is:"+a+ " "+b);
}
// Overload test for a double parameter
void test(double d)
{
System.out.println("Inside test(double)d:"+d);
}
}
class Overload
{
public static void main(String[] args)
{
Demo d=new Demo();
int i=40;
d.test();
d.test(10,20);
d.test(i);// this will invoke test(double)
d.test(12.3);//this will invoke test(double)
}
P.Ramesh, Assistant Professor, AIML Dept, 58
TKREC
OOP through Java UNIT-1

}
OUTPUT:
D:\TKREC\Java>java Overload
No Parameter
a and b is :10 20
Inside test(double)d:40.0
Inside test(double)d:12.3

Overloading constructors
Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructors overloading.

Example1
class ConDemo
{
int value1;
int value2;
ConDemo()
{
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
// constructor with a single parameter
ConDemo(int a)
{
value1 = a;
System.out.println("Inside 2nd Constructor");
}
// constructor with two parameters
ConDemo(int a, int b)
{
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display()
{
System.out.println("Value1 "+value1);
System.out.println("Value2 "+value2);
}
public static void main(String args[])
{
// call constructor with no parameter
ConDemo d1 = new ConDemo();
d1.display();
// call constructor with single parameter

P.Ramesh, Assistant Professor, AIML Dept, 59


TKREC
OOP through Java UNIT-1

ConDemo d2 = new ConDemo(30);


d2.display();
// call constructor with two parameters
ConDemo d3 = new ConDemo(40,50);
d3.display();
}
}
OUTPUT:
D:\TKREC\Java>java ConDemo
Inside 1st Constructor
value1 10
value2 20
Inside 2nd Constructor
value1 30
value2 0
Inside 3rd Constructor
value1 40
value2 50

Example2
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{

P.Ramesh, Assistant Professor, AIML Dept, 60


TKREC
OOP through Java UNIT-1

return width * height * depth;


}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
OUTPUT:
D:\TKREC\Java>java OverloadCons
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

Method binding
In java, binding is the process of linking a method call to its corresponding method
implementation. Binding decides which method implementation is classed when a method is
called. Binding can happen either at runtime or at compile time

There are two types of binding


 Static Binding (also known as Early Binding).
 Dynamic Binding (also known as Late Binding).

Static Binding: When type of the object is determined at compiled time (by the compiler), it is
known as static binding.
 static binding use type of the class and fields
 Overloading is an example of static binding
 private, final and static methods and variables uses static binding
Example
class Student
{
private void show()
{
P.Ramesh, Assistant Professor, AIML Dept, 61
TKREC
OOP through Java UNIT-1

System.out.println("Studying...");
}
public static void main(String args[])
{
StudentStatic s=new StudentStatic();
s.show();
}
}
OUTPUT:
D:\TKREC\Java>java Student
Studying...

Dynamic Binding: When type of the object is determined at run-time, it is known as dynamic
binding.
 Dynamic binding uses object to resolve binding
 Method overriding is the example of Dynamic binding
 Object and Virtual methods used in dynamic binding
Example
class Teacher
{
void show()
{
System.out.println("Teaching...");
}
}
class Student extends Teacher
{
void show()
{
System.out.println("Studying...");
}
public static void main(String args[])
{
Teacher t=new Student();
t.show();
}
}
OUTPUT:
D:\TKREC\Java>java Student
Studying...

Inheritance
The inheritance is a very useful and powerful concept of object-oriented programming.
In java, using the inheritance concept, we can use the existing features of one class in
another class. The inheritance provides a great advantage called code re-usability.
Withthe help of code re-usability, the commonly used code in an application need not be
written again and again.

P.Ramesh, Assistant Professor, AIML Dept, 62


TKREC
OOP through Java UNIT-1

Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java
Programmer salary is:40000.0
Bonus of Programmer is:10000

Overriding
The method overriding is the process of re-defining a method in a child class that is
already defined in the parent class.

If the same method is defined in both the superclass and the subclass, then the method
of the subclass class overrides the method of the superclass. This is known as method
overriding.

In the case of the method overriding, the method binding happens at run time. The
method binding which happens at run time is known as late binding. So, the method
overriding follows late binding.

The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.

Example
class A
{
public void displayInfo()
{
System.out.println(" This is class A method ");
}
}
class B extends A
{
@Override
public void displayInfo()
{

P.Ramesh, Assistant Professor, AIML Dept, 63


TKREC
OOP through Java UNIT-1

System.out.println("This is class B method ");


}
}
class Methodoverriding
{
public static void main(String[] args)
{
B obj = new B();
obj.displayInfo();
}
}
OUTPUT:
D:\TKREC\Java>java Methodoverriding
This is class B method

Rules for method overriding


While overriding a method, we must follow the below list of rules.
 Static methods cannot be overridden.
 Final methods cannot be overridden.
 Private methods cannot be overridden.
 Constructor cannot be overridden.
 An abstract method must be overridden.

Exceptions
An exception is an unexpected event that occurs during program execution. It disrupts the normal
flow of the program's instructions
We have 3 types of exceptions
 Checked exceptions (Compile Time)
 Unchecked exceptions (Run time)
 Error

Parameter passing
Parameter passing in Java refers to the mechanism of transferring data between methods or
functions.
Java supports two types of parameters passing techniques
 Call-by-value
 Call-by-reference.

Types of Parameters

Formal Parameters: A variable and its corresponding data type are referred to as
formal parameters when they exist in the definition or prototype of a function or
method
Example
void add(int a, int b)
{
---
P.Ramesh, Assistant Professor, AIML Dept, 64
TKREC
OOP through Java UNIT-1

---
}

Actual Parameters: The value or expression that corresponds to a formal parameter and is
supplied to a function or method during a function or method call is referred to as an actual
parameter is also known as an argument.
Example
add(10);

Call by value: In Call-by-value the copy of the value of the actual parameter is
passed to the formal parameter of the method. Any of the modifications made to the
formal parameter within the method do not affect the actual parameter.

In Java, when you pass a primitive type to a method, it is passed by value. Thus, what
occurs to the parameter that receives the argument has no effect outside the method.
For example, consider the following program:

Example
// Primitive types are passed by value.
class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
OUTPUT:
D:\TKREC\Java>java CallByValue
a and b before call: 15 20
a and b before call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10. When you pass an object to a
method, the situation changes dramatically, because objects are passed by what is effectively
call-by-reference

P.Ramesh, Assistant Professor, AIML Dept, 65


TKREC
OOP through Java UNIT-1

Call by reference: It is a method of passing arguments to functions or methods


where the memory address (or reference) of the variable is passed rather than the
value itself. This means that changes made to the formal parameter within the
function affect the actual parameter in the calling environment.

When you pass this reference to a method, the parameter that receives it will refer to the same
object as that referred to by the argument. This effectively means that objects are passed to
methods by use of call-by-reference. Changes to the object inside the method do affect the object
used as an argument. For example, consider the following program:

Example
// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("a and b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("a and b after call: " +ob.a + " " + ob.b);
}
}
OUTPUT:
D:\TKREC\Java>java CallByRef
a and b before call: 15 20
a and b before call: 30 10

As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument. As a point of interest, when an object reference is passed to a method, the reference
itself is passed by use of call-by-value.

Note: When a primitive type is passed to a method, it is done by use of call-by-value. Objects
are implicitly passed by use of call-by-reference.

P.Ramesh, Assistant Professor, AIML Dept, 66


TKREC
OOP through Java UNIT-1

Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to Java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The factorial of a
number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 ×
2 × 3, or 6. Here is how a factorial can be computed by use of a recursive method:

Example
// A simple example of recursion.
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
OUTPUT:
D:\TKREC\Java>java Recursion
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

If you are unfamiliar with recursive methods, then the operation of fact( ) may seem a bit
confusing. Here is how it works. When fact( ) is called with an argument of 1, the function
returns 1; otherwise, it returns the product of fact(n–1)*n. To evaluate this expression, fact( ) is
called with n–1. This process repeats until n equals 1 and the calls to the method begin
returning.

Nested and inner classes


It is possible to define a class within another class; such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
P.Ramesh, Assistant Professor, AIML Dept, 67
TKREC
OOP through Java UNIT-1

Example
class A
{
----
----
class B
{
---
---
}
}
Thus, if class B is defined within class A, then B does not exist independently of A. A nested class
has access to the members, including private members, of the class in which it is nested.
However, the enclosing class does not have access to the members of the nested class.

There are two types of nested classes:


 static
 non-static
Static Nested Class: In Java, we can also define a static class inside another class.
Such class is known as static nested class. Static nested classes are not called static
inner classes. Unlike inner class, a static nested class cannot access the member
variables of the outer class. It is because the static nested class doesn't require you to
create an instance of the outer class.

OuterClass.NestedClass obj = new OuterClass.NestedClass();

Example
class Outer
{
// static nested class
static class Inner
{
int a = 1;
int b = 2;
int getTotal()
{
return a + b;
}
}
}
public class StaticNested
{
public static void main(String[] args)
{
// create an object of the static nested class using the name of the outer class
Outer.Inner obj = new Outer.Inner();
System.out.println("Total Number is: " + obj.getTotal());

P.Ramesh, Assistant Professor, AIML Dept, 68


TKREC
OOP through Java UNIT-1

}
}
OUTPUT:
D:\TKREC\Java>java Recursion
Total Number is: 3

Non-Static Nested Class: A non-static nested class is a class within another class. It has access to
members of the enclosing class (outer class). It is commonly known as inner class. Since the inner
class exists within the outer class, you must instantiate the outer class first, in order to instantiate
the inner class.

An inner class is a non-static nested class. It has access to all of the variables and methods of its
outer class and may refer to them directly in the same way that other non-static members of the
outer class do.

The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named x, one instance method named test( ), and
defines one inner class called Inner.

Example
// Demonstrate an inner class.
class Outer
{
int x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display()
{
System.out.println("Display x is " + x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer o = new Outer();
o.test();
}
}
OUTPUT:
D:\TKREC\Java>java Recursion

P.Ramesh, Assistant Professor, AIML Dept, 69


TKREC
OOP through Java UNIT-1

Display x is: 100

Exploring string class.


A string is a sequence of characters surrounded by double quotations. In a java
programming language, a string is the object of a built-in class String. In the
background, the string values are organized as an array of a character data type.

The string created using a character array cannot be extended. It does not allow to
append more characters after its definition, but it can be modified.

The String class defined in the package java.lang package. String is probably the most
commonly used class in Java’s class library

Java defines one operator for String objects: +. It is used to concatenate two strings.
For example, this statement
String myString = "I" + " like " + "Java.";
results in myString containing “I like Java.”

The following program demonstrates the preceding concepts:

Example

// Demonstrating Strings.
class StringDemo
{
public static void main(String args[])
{
String str1 = "First String";
String str2 = "Second String";
String str3 = str1 + " and " + str2;
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
OUTPUT:
D:\TKREC\Java>java StringDemo
First String
Second String
First String and Second String

The String class contains several methods that you can use. Here are a few. You can
test two strings for equality by using equals( ). You can obtain the length of a string
by calling the length( ) method. You can obtain the character at a specified index
within a string by calling charAt( ).

P.Ramesh, Assistant Professor, AIML Dept, 70


TKREC
OOP through Java UNIT-1

Here is a program that demonstrates these methods:

Example
// Demonstrating some String methods.
class StringDemo2
{
public static void main(String args[])
{
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of str1: " + str1.length());
System.out.println("Char at index 3 in str1: " + str1.charAt(3));
if(str1.equals(str2))
System.out.println("str1 == str2");
else
System.out.println("str1! = str2");
if(strOb1.equals(str3))
System.out.println("str1 == str3");
else
System.out.println("str1! = str3");
}
}
OUTPUT:
D:\TKREC\Java>java StringDemo2
Length of str1: 12
Char at index 3 in str1: s
str1! = str2
str1 == str3

Example
public class JavaStringMethods
{
public static void main(String[] args)
{
String title = "Java Tutorials";
String siteName = "JavaProgram.com";

System.out.println("Index of 'T': " + title.indexOf('T'));


System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}

P.Ramesh, Assistant Professor, AIML Dept, 71


TKREC
OOP through Java UNIT-1

OUTPUT:
D:\TKREC\Java\UNIT-I>java JavaStringMethods
Index of 'T': 5
Last index of 'a': 11
Empty: false
Ends with '.com': true
Equals: false
Sub-string: am.co
Upper case: JAVAPROGRAM.COM

Of course, you can have arrays of strings, just like you can have arrays of any other type
of object.

Example:
// Demonstrate String arrays.
class StringDemo3
{
public static void main(String args[])
{
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}

OUTPUT:
D:\TKREC\Java\UNIT-I>java StringDemo3
str[0]: one
str[1]: two
str[2]: three

P.Ramesh, Assistant Professor, AIML Dept, 72


TKREC

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy