You are on page 1of 94

MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN

Approved by AICTE, New Delhi; Affiliated to JNTU, Hyderabad.

An ISO 9001:2015 Certified Institution

Maisammaguda, Dhulapally, Medchal, Hyderabad -500100,

Telangana.

COURSE FILE

OF

OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

YEAR: II B.Tech SEMESTER: I BRANCH: CSE

Regulation R22

ACADEMIC YEAR: 2023-2024

Prepared by

Dr. Syeda Husna Mehanoor

Professor

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


R22 B.Tech. CSE Syllabus JNTU
Hyderabad
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
B.Tech. II Year I Sem. L
TPC
3003
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.

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.

UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member
access rules, super uses, using final with inheritance, polymorphism- method overriding,
abstract classes, the Object class.
Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing
packages, differences between classes and interfaces, defining an interface, implementing
interface, applying interfaces, variables in interface and extending interfaces. Exploring
java.io.

UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of
exception handling, Termination or resumptive models, exception hierarchy, usage of try,
catch, throw, throws and finally, built in exceptions, creating own exception subclasses.
String handling, Exploring java.util. Differences between multithreading and multitasking,
thread life cycle, creating threads, thread priorities, synchronizing threads, inter thread
communication, thread groups, daemon threads. Enumerations, autoboxing, annotations,
generics.

UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user
interface components- labels, button, canvas, scrollbars, text components, check box,
checkbox groups, choices,lists panels – scrollpane, dialogs, menubar, graphics, layout
manager – layout manager types – border,grid, flow, card and grid bag.

UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent,Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes,Tabbed Panes, Scroll Panes, Trees, and Tables.

TEXTBOOKS:
1. Java the complete reference, 7th edition, Herbert schildt, TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearson education.

REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John
wiley
& sons.
2. An Introduction to OOP, third edition, T. Budd, Pearson education.
3. Introduction to Java programming, Y. Daniel Liang, Pearson education.
4. An introduction to Java programming and object-oriented application development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth
Edition,
Pearson Education
7. Object Oriented Programming with Java, R.Buyya, S.T.Selvi, X.Chu, TMH.
8. Java and Object Orientation, an introduction, John Hunt, second edition, Springer. 9.
Maurach’s
Beginning Java2 JDK 5, SPD.
UNIT - I
OBJECT-ORIENTED THINKING AND JAVA BASICS

NEED FOR OOP PARADIGM

As the name suggests, Object-Oriented Programming or OOP refers to languages that use
objects in programming. They use objects as a primary source to implement what is to
happen in the code. Objects are seen by the viewer or user, performing tasks assigned by
you. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism etc. in programming. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can access this
data except that function.

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 those produced using traditional techniques. The software produced using an object-
oriented programming paradigm is easier to adapt to the changing requirements, easier to
maintain, create modules of functionality, promote greater design, be more robust, and
perform desired work efficiently.

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 has several advantages over procedural programming:

• OOP is faster and easier to execute.


• OOP provides a clear structure for the programs.
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug.
• OOP makes it possible to create full reusable applications with less code and shorter
development time.

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code.
You should extract out the codes that are common for the application and place them at a
single place and reuse them instead of repeating it.

Although, Java has become a popular programming language for developing the web-
application, android apps, IoT applications, etc. Still, C has not lost its popularity because it is
used to develop firmware, operating system, and other system utilities.
APPLICATION

According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:

1. Desktop Applications such as Acrobat Reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

FEATURES OF JAVA {JAVA BUZZWORDS}

The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords. A list of the most important features of the Java language
is given below.

1. Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

2. Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior. Object-oriented programming (OOPs) is a methodology
that simplifies software development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3. Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.There
are two types of platforms software-based and hardware-based. Java provides a software-
based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API (Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).

4. Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

5. Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

6. Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.In C programming, int data type occupies 2 bytes
of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

7. Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

8. High-performance

Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
9. Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.

10. Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

11. Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

A WAY OF VIEWING WORLD

A way of viewing the world is an idea to illustrate the object-oriented programming concept
with an 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 food to
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 agents and
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, myself, and my family in the community.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which led to still more
requestes 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 delivered to my
home.

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 delivered to
my family). The agent (zomato) 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.

Classes and Instances


In object-oriented programming, all objects are instances of a class. The method invoked by
an object in response to a message is decided by the class. All the objects of a class use the
same method in response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.

Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes
(objects) of a community. This graphical representation shows classes listed in a hierarchical
tree-like structure. In this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical
inheritance structure. A child class inherits properties from the parent class that higher
in the tree.
Method Binding, Overriding, and Exception
In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child.
Or a class may provide multiple definitions to a single method to work with different
arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the class
of this receiver. If no suitable method is found, the search is performed in the parent class of
it. The search continues up the parent class chain until either a suitable method is found or the
parent class chain is exhausted. If a suitable method is found, the method is executed.
Otherwise, an error message is issued.

OOP CONCEPTS IN JAVA (SUMMARY OF OOP CONCEPTS)

OOP stands for Object-Oriented Programming. OOP is a programming paradigm in 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.

• Encapsulation
• Inheritance
• Polymorphism
• Abstraction

The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#,
Python, etc.

Encapsulation

Encapsulation is the process of combining data and code into a single unit (object / class). In
OOP, every object is associated with its data and code. In programming, data is defined as
variables and code is defined as methods. The java programming language uses the class
concept to implement encapsulation.
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 recieves the properties is called as child class. The parent class is also known as base
class or supre class. The child class is also known as derived class or sub class.
In the inheritance, the properties and behaviors of base class extended to its derived class, but
the base class never receive properties or behaviors from its derived class.

Polymorphism

Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviours. The java uses method
overloading and method overriding to implement polymorphism.
Abstraction

Abstraction is hiding the internal details and showing only essential functionality. 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 know
about the internal functionality like how wheel system works? how brake system works? how
music system works? etc.

HISTORY 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 also innovated
many new features to solve the fundamental problems which the previous languages could
not solve. 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.

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 using java command.
COPING WITH COMPLEXITY

Asymptotic Notations:
Asymptotic Notations are mathematical notations that allow you to analyze an algorithm’s
running time by identifying its behavior as its input size grows. This is also referred to as
an algorithm’s growth rate.Asymptotic notations are the mathematical notations used to
describe the running time of an algorithm when the input tends towards a particular value
or a limiting value.

There are mainly three asymptotic notations:

Big-Theta Notation (Θ-Notation):


Theta notation encloses the function from above and below. Since it represents the upper
and the lower bound of the running time of an algorithm, it is used for analyzing
the average-case complexity of an algorithm. Theta (Average Case) You add the running
times for each possible input combination and take the average in the average case.

Big-O Notation (O-notation):


Big-O notation represents the upper bound of the running time of an algorithm. Therefore,
it gives the worst-case complexity of an algorithm. It is the most widely used notation for
Asymptotic analysis. It specifies the upper bound of a function. The maximum time
required by an algorithm or the worst-case time complexity. It returns the highest possible
output value(big-O) for a given input. Big-Oh(Worst Case) It is defined as the condition
that allows an algorithm to complete statement execution in the longest amount of time
possible.

Big-Omega Notation (Ω-Notation):


Omega notation represents the lower bound of the running time of an algorithm. Thus, it
provides the best-case complexity of an algorithm. Big - Omega notation is used to define
the lower bound of an algorithm in terms of Time Complexity.
That means Big-Omega notation always indicates the minimum time required by an
algorithm for all input values. That means Big-Omega notation describes the best case of an
algorithm time complexity.
What is Time complexity?
Every algorithm requires some amount of computer time to execute its instruction to perform
the task. This computer time required is called time complexity.
The time complexity of an algorithm can be defined as follows...
The time complexity of an algorithm is the total amount of time required by an
algorithm to complete its execution.
Generally, the running time of an algorithm depends upon the following...

1. Whether it is running on Single processor machine or Multi processor machine.


2. Whether it is a 32 bit machine or 64 bit machine.
3. Read and Write speed of the machine.
4. The amount of time required by an algorithm to
perform Arithmetic operations, logical operations, return value
and assignment operations etc.,
5. Input data

Note - When we calculate time complexity of an algorithm, we consider only input data and
ignore the remaining things, as they are machine dependent. We check only, how our
program is behaving for the different input values to perform all the operations like
Arithmetic, Logical, Return value and Assignment etc.,
Calculating Time Complexity of an algorithm based on the system configuration is a very
difficult task because the configuration changes from one system to another system. To solve
this problem, we must assume a model machine with a specific configuration. So that, we can
able to calculate generalized time complexity according to that model machine.

To calculate the time complexity of an algorithm, we need to define a model machine. Let us
assume a machine with following configuration...

1. It is a Single processor machine.


2. It is a 32-bit Operating System machine
3. It performs sequential execution.
4. It requires 1 unit of time for Arithmetic and Logical operations.
5. It requires 1 unit of time for Assignment and Return value.
6. It requires 1 unit of time for Read and Write operations.
Time Complexity

1. Time complexity of a simple loop when the loop variable is incremented or


decremented by a constant amount:

1. int i = 1;
2. do
3. {
4. i++;
5. }while(i<=n);

Here, i: It is a loop variable.

n: Number of times the loop is to be executed.

In above scenario, loop is executed 'n' times. Therefore, time complexity of this loop is O(n).

2. Time complexity of a loop when the loop variable is divided or multiplied by a


constant amount:

1. int i=1;
2. do
3. {
4. i = i*c;
5. }while(i<=n);

Here, i: It is a loop variable.


c: It is a constant.

n: Number of times the loop is to be executed.

In this case, Time complexity is O(logn).

3. Time complexity of a nested loop.

1. int i=0;
2. do{
3. do{
4. int j =0;
5. j++;
6. }while(j<=i);
7. i++;
8. }while(i<=n-1);

Here, i: It is an outer loop variable.

j: It is an inner loop variable.

n: Number of times the loop is to be executed.

In this case, in each iteration of i, inner loop is executed 'n' times. The time complexity of a
loop is equal to the number of times the innermost statement is to be executed.

1. On the first iteration of i=0, the inner loop executes 0 times.


2. On the first iteration of i=1, the inner loop executes 1 times.
3. On the first iteration of i=n-1, the inner loop executes n-1 times.
4. The number of times the inner loop is executed is equal to the sum of integers(0,1,2,3
?n-1) = n^2/2 - n/2

Time complexity = O(n2).


4.Time complexity of an infinite loop

Infinite loop is executed "Infinite times". Therefore, there is no "algorithm time complexity"
for an infinite loop.

5.Time complexities of different loops.

When there are more than one loop:

1. int i=1;
2. do{
3. i++;
4. }while(i<=m);
5.
6. int j=1;
7. do{
8. j++;
9. }while(j<=n);

Time complexity of different loops is equal to the sum of the complexities of individual loop.

Therefore,

Time complexity = O(m)+O(n)

WHAT IS SPACE COMPLEXITY?


When we design an algorithm to solve a problem, it needs some computer memory to
complete its execution. For any algorithm, memory is required for the following purposes...

1. To store program instructions.


2. To store constant values.
3. To store variable values.
4. And for few other things like funcion calls, jumping statements etc,.

Space complexity of an algorithm can be defined as follows...


Total amount of computer memory required by an algorithm to complete its execution
is called as space complexity of that algorithm.

Generally, when a program is under execution it uses the computer memory for THREE
reasons. They are as follows...

1. Instruction Space: It is the amount of memory used to store compiled version of


instructions.
2. Environmental Stack: It is the amount of memory used to store information of
partially executed functions at the time of function call.
3. Data Space: It is the amount of memory used to store all the variables and constants.

Note - When we want to perform analysis of an algorithm based on its Space complexity, we
consider only Data Space and ignore Instruction Space as well as Environmental Stack.
That means we calculate only the memory required to store Variables, Constants, Structures,
etc.,

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

• Primitive Data Types


• Non-primitive Data Types

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

Data Memory Default


type Meaning size Range Value

byte Whole 1 byte -128 to +127 0


numbers

short Whole 2 bytes -32768 to +32767 0


numbers
Data Memory Default
type Meaning size Range Value

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


numbers

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


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

float Fractional 4 bytes - 0.0f


numbers

double Fractional 8 bytes - 0.0d


numbers

char Single 2 bytes 0 to 65535 \u0000


character

boolean unsigned char 1 bit 0 or 1 0 (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.

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


Primitive Data Type Non-primitive Data Type

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. A variable 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, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are clasiffied as follows.

• Local variables
• Instance variables or Member variables or Global variables
• Static variables or Class variables
• Final variables

Local variables
The variables declared inside a method or a block 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.
Let's look at the following example java program to illustrate local variable in java.
Instance variables or member variables or global variables
The variables declared inside a class and outside any method, constructor or block 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 affects all the methods in the class.
These variables are created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java.
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 can not. 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.

o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory

Understanding the problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects. If we make it static, this field will get the memory only once.

Java static property is shared to all objects.

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }

Output:

111 Karan ITS


222 Aryan ITS
FINAL VARIABLES
A final variable is a variable that declared using final keyword. The final variable is
initialized 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.
Let's look at the following example java program to illustrate final variable in java.

JAVA ARRAY

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.
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.
• Single Dimensional Array
• Multi-Dimensional Array
SINGLE DIMENSIONAL ARRAY IN JAVA

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

Output:

10
20
70
40
50
MULTIDIMENSIONAL ARRAY IN JAVA

In such case, data is stored in row and column-based index (also known as matrix form).

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. We use 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.
Example

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

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

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java


1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example Of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }
14. }
Output:

123
245
445

JAVA OPERATORS

An operator is a symbol used to perform arithmetic and logical operations. Java provides a

rich set of operators.

In java, operators are classified into the following four types.

• Arithmetic Operators

• Relational (or) Comparison Operators

• Logical Operators

• Assignment Operators

• Bitwise Operators

• Conditional Operators

Let's look at each operator in detail.

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
Operator Meaning Example

/ Division 10 / 5 = 2

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

++ Increment a++

-- Decrement a--

Let's look at the following example program.

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 posible 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

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

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

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

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

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5


is
FALSE

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

Look at the following example program.

When we run the above example code, it produces the following output.
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 TRUE otherwise false &
returns FALSE true =>
false

| Logical OR - Returns FALSE if all conditions are FALSE otherwise false |


returns TRUE true =>
true

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

! Logical NOT - Returns TRUE if condition is FLASE and returns !false =>
FALSE if it is TRUE true

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

|| short-circuit OR - Similar to Logical OR (|), but once a decision is false |


finalized it does not evaluate remianing. true =>
true

Look at the following example program.

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 into left- A += 10
hand side variable

-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable

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


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

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


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

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

Look at the following example program.

When we run the above example code, it produces the following output.
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

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A& B
⇒ 16
(10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B


⇒ 29
(11101)
Operator Meaning Example

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is A^ B
1 ⇒ 13
(01101)

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒6
(00110)

<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the A >> 2
specified number of positions ⇒6
(00110)

Look at the following example program.


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;

JAVA EXPRESSIONS
In any programming language, if we want to perform any calculation or to frame any
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 arithmetic

operations, logical operations, and conditional operations, etc.

Operands are the values on which the operators perform the task. Here operand can be a

direct value or variable or address of memory location.


In the java programming language, expressions are divided into THREE types. They are as

follows.

• Infix Expression

• Postfix Expression

• 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.

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

• if-elif statement

• nested if statement

• switch statemen

if statement in java

In java, we use the if statement to test a condition and decide the execution of a block of

statements based on that condition result. The 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.

Let's look at the following example java code.

Java Program

When we run this code, it produce the following output.


In the above execution, the number 12 is not divisible by 5. So, the condition becomes False

and the condition is evaluated to False. Then the if statement ignores the execution of its

block of statements.When we enter a number which is divisible by 5, then it produces the

output as follows.

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.
Let's look at the following example java code.

When we run this code, it produce the following output.

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;
...
}
...
}

Let's look at the following example java code.

When we run this code, it produce the following output.

if-else if statement in java

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

syntax of the 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;
...
}
Let's look at the following example java code.

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.
Let's look at the following example java code.

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

• 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. The syntax and execution flow of while statement is as follows.
Let's look at the following example java code.

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.
Let's look at the following example java code.

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. The for statement has the following syntax and

execution flow diagram.

In for-statement, the execution begins with the initialization statement. After the

initialization statement, it executes Condition. If the condition is evaluated to true, then the

block of statements executed otherwise it terminates the for-statement. After the block of

statements execution, the modification statement gets executed, followed by condition again.
Let's look at the following example java code.

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.

The for-each statement has the following syntax and execution flow diagram.

Let's look at the following example java code.


Jump Statements

In java, the jump statements are used to terminate a block or take the execution control to the

next iteration. Java provides the following jump statements.

• break

• continue

• return

break statement in java


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 statement and a looping
statement like while, do-while, for, and for-each.
The following picture depictes the execution flow of the break statement.

Example:
Continue Statement In Java
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.
When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition. When we use continue statement with for
statement the execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.

Example:
Java Continue Statement with Inner Loop

It continues inner loop only if you use the continue statement inside the inner loop.

ContinueExample2.java

1. //Java Program to illustrate the use of continue statement


2. //inside an inner loop
3. public class ContinueExample2 {
4. public static void main(String[] args) {
5. //outer loop
6. for(int i=1;i<=3;i++){
7. //inner loop
8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){
10. //using continue statement inside inner loop
11. continue;
12. }
13. System.out.println(i+" "+j);
14. }
15. }
16. }
17. }

Output:

11
12
13
21
23
31
32
33

Return Statement In Java

What is a return statement in Java?

In Java programming, the return statement is used for returning a value when the execution of
the block is completed. The return statement inside a loop will cause the loop to break and
further statements will be ignored by the compiler.

Returning a Value from a Method

In Java, every method is declared with a return type such as int, float, double, string,
etc.These return types required a return statement at the end of the method. A return keyword
is used for returning the resulted value.The void return type doesn't require any return
statement. If we try to return a value from a void method, the compiler shows an error.

Following are the important points must remember while returning a value:

o The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float return
type, the value returned should be of float type only.
o The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
o If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.

Syntax:

The syntax of a return statement is the return keyword is followed by the value to be returned.

1. return returnvalue;

The following Java programs demonstrate the use of return statements.

SampleReturn1.java

1. public class SampleReturn1


2. {
3. /* Method with an integer return type and no arguments */
4. public int CompareNum()
5. {
6. int x = 3;
7. int y = 8;
8. System.out.println("x = " + x + "\ny = " + y);
9. if(x>y)
10. return x;
11. else
12. return y;
13. }
14.
15. /* Driver Code */
16. public static void main(String ar[])
17. {
18. SampleReturn1 obj = new SampleReturn1();
19. int result = obj.CompareNum();
20. System.out.println("The greater number among x and y is: " + result);
21. }
22. }

Output:

x=3
y=8
The greater number among x and y is: 8

In the above Java code, the method CompareNum is defined with the int return type. It
compares the x and y values and returns the greater number.

TYPE CONVERSION AND CASTING

Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
target data type may be smaller than the source data type when converting the data type to
another data type, that’s why it is also called narrowing conversion.
Syntax/Declaration:-
target_datatype = (target_datatype)source_variable;
( ): is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting example –

float x;
byte y;
y=(byte)x; //line 3
Example:
double x=9.78;
int y=(int)x;
int y= 9;

In Line 3: you can see that, we are converting float(source) data type into byte(target)
data type.
2. Type conversion : In type conversion, a data type is automatically converted into
another data type by a compiler at the compiler time. In type conversion, the target data
type cannot be smaller than the source data type, that’s why it is also called widening
conversion. One more important thing is that it can only be applied to compatible data
types.
Type Conversion example –
int x=30;// source datatype
float y;// target datatype
y=x; // y==30.000000.

S.NO TYPE CASTING TYPE CONVERSION

In type casting, a data type is Whereas in type conversion, a data type


1. converted into another data type by a is converted into another data type by a
programmer using casting operator. compiler.

Type casting can be applied


Whereas type conversion can only be
2. to compatible data types as well
applied to compatible datatypes.
as incompatible data types.

In type casting, casting operator is


Whereas in type conversion, there is no
3. needed in order to cast a data type to
need for a casting operator.
another data type.

In typing casting, the destination data


Whereas in type conversion, the
type may be smaller than the source
4. destination data type can’t be smaller
data type, when converting the data
than source data type.
type to another data type.

Type casting takes place during the Whereas type conversion is done at the
5.
program design by programmer. compile time.
S.NO TYPE CASTING TYPE CONVERSION

Type casting is also called narrowing Whereas type conversion is also called
conversion because in this, the widening conversion because in this, the
6.
destination data type may be smaller destination data type can not be smaller
than the source data type. than the source data type.

Whereas type conversion is less used in


Type casting is often used in coding
7. coding and competitive programming as
and competitive programming works.
it might cause incorrect answer.

Type casting is more efficient and Whereas type conversion is less efficient
8.
reliable. and less reliable.

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 defines the
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 the class.
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.

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;
}

The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.

• A class is declared by use of the class keyword.


• A class is an entity that determines how an object will behave and what the object will
contain.
• A class is a blueprint from which individual objects are created. It represents the set of
properties or methods that are common to all objects of one type.

• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• The methods and variables defined within a class are called members of the class.

Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
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>( );

The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.

Object And Class Example: Main Within the Class

In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
Here, we are creating a main() method inside the class.

File: Student.java

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main() method
in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.

File: TestStudent1.java

1. //Java Program to demonstrate having the main method in


2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

CONSTRUCTORS IN JAVA
Java constructors or constructors in Java is a terminology used to construct something in
our programs. A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.

What are Constructors in Java?


In Java, Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Note: It is not necessary to write a constructor for a class. It is because the java compiler
creates a default constructor (constructor with no arguments) if your class doesn’t have
any.
How Java Constructors are Different From Java Methods?
• Constructors must have the same name as the class within which it is defined it
is not necessary for the method in Java.
• Constructors do not return any type while method(s) have the return type
or void if does not return any value.
• Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.

Need of Constructors in Java


Think of a Box. If we talk about a box class then it will have some class variables (say
length, breadth, and height). But when it comes to creating its object(i.e Box will now exist
in the computer’s memory), then can a box be there with no value defined for its
dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default constructor).

When Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it could be
the default constructor) is invoked to assign initial values to the data members of the same
class. Rules for writing constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in
which it resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions) that
are executed at the time of Object creation.

There are two rules defined for the constructor.


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there are three
types of constructors in Java are mentioned below:
• Default Constructor
• Parameterized Constructor
• Copy Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler does
not create a default constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor.

// Java Program to demonstrate Default Constructor

// Driver class
class ABC {

// Default Constructor
ABC()
{
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
ABC obj = new ABC();
}
}

Output: Default constructor

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
Output:
111 Karan
222 Aryan

CONSTRUCTOR OVERLOADING IN JAVA

In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.

Now the most important topic that comes into play is the strong incorporation of OOPS
with constructors known as constructor overloading. Just like methods, we can overload
constructors for creating objects in different ways. The compiler differentiates constructors
on the basis of the number of parameters, types of parameters, and order of the parameters.

Example of Constructor Overloading


1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }

Output:
111 Karan 0
222 Aryan 25

DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD IN JAVA

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

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

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

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

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

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

JAVA COPY CONSTRUCTOR

In Java, a copy constructor is a special type of constructor that creates an object using another
object of the same Java class. It returns a duplicate copy of an existing object of the class.

We can assign a value to the final field but the same cannot be done while using the clone()
method. It is used if we want to create a deep copy of an existing object. It is easier to
implement in comparison to the clone() method.

Use of Copy Constructor

We can use the copy constructor if we want to:

o Create a copy of an object that has multiple fields.


o Generate a deep copy of the heavy objects.
o Avoid the use of the Object.clone() method.
Advantages of Copy Constructor
o If a field declared as final, the copy constructor can change it.
o There is no need for typecasting.
o Its use is easier if an object has several fields.
o Addition of field to the class is easy because of it. We need to change only in the copy
constructor.

In this example, we are going to copy the values of one object into another using Java
constructor.

1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }

Output:

111 Karan
111 Karan
Copy Constructor Vs clone() Method

Both the copy constructor and the clone() method are used to create a copy of an existing
object of the class. But the use of copy constructor is easier and better in comparison to the
clone() method because of the reasons given below:

o If we are using the clone() method it is necessary to import the Cloneable The
method may throw the exception CloneNotSupportException. So, handling the
exception in a program is a complex task. While in copy constructor there are no such
complexities.
o We cannot assign a value if the fields are final. While in the copy constructor we can
assign values to the final fields.
o The object returned by the clone() method must be typecast. While in copy
constructor there is no such requirement.

METHOD IN JAVA

In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods. In this section, we will learn what is a method
in Java, types of methods, method declaration, and how to call a method in Java.

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.

Method Declaration

The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method

While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max().
We have used these methods directly without declaration because they are predefined. The
print() method is a method of PrintStream class that prints the result on the console. The
max() method is a method of the Math class that returns the greater of two numbers.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
EvenOdd.java

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd
ACCESS MODIFIERS IN JAVA (ACCESS CONTROL)

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.


The public members can be accessed everywhere.
• The private members can be accessed only inside the same class.
• The protected members are accessible to every child class (same package or other
packages).
• The default members are accessible within the same package but not outside the
package

this KEYWORD IN JAVA

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object. Sometimes a method will need to refer to the object that invoked
it. To allow this, Java defines the this keyword. this can be used inside any method to refer to
the current object. That is, this is always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the current class’ type is
permitted.

this: to refer current class instance variable

This keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}

Output:

111 ankit 5000.0


112 sumit 6000.0

GARBAGE COLLECTION

In java, garbage means unreferenced objects.

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.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

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

How can an object be unreferenced?

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;

2) By assigning a reference to another:


1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
1. new Employee();

finalize() method

Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle
such situations, Java provides a mechanism called finalization. By using finalization, you can
define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector. To add a finalizer to a class, you simply define the finalize( ) method. The
Java run time calls that method whenever it is about to recycle an object of that class. Inside
the finalize( ) method, you will specify those actions that must be performed before an object
is destroyed. The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects. Right before
an asset is freed, the Java run time calls the finalize( ) method on the object.

The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.

gc( ) method

The gc() method is used to invoke the garbage collector to perform cleanup processing that is
destroying the unreferenced objects. The gc() is found in System and Runtime classes.

Simple Example of garbage collection in java


1. public class TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }

Output:

object is garbage collected


object is garbage collected

OVERLOADING METHODS AND CONSTRUCTORS

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java.

1. By changing number of arguments


2. By changing the data type
1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

Output:

22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Output:

22
24.

METHOD BINDING

Binding means an association of method call to the method definition. In other words
Connecting a method call to the method body is known as binding.

There are two types of Binding.

1. Static Binding

2. Dynamic Binding

Static Binding:

Static Binding is the binding that can be done at the compile time is know as static binding.
In static binding the compiler knows that methods cannot be overridden and will be accessed
by the object of the class. It is also know as early binding.

Example program:
class India {

public static void locate() {


System.out.println("We are in India");
}
}

class SubIndia extends India {

public static void locate() {


System.out.println("We are in Delhi");
}
}

public class staticBindingTest {

public static void main(String args[])


{
India superobj = new India();
superobj.locate();
India subobj = new SubIndia();
subobj.locate();

SubIndia subobj2 = new SubIndia();


subobj2.locate(); // method of sub class or child class is called
}
}

Output:
We are in India
We are in India
We are in Delhi

Dynamic binding:

Dynamic binding is also referred to as a run-time polymorphism. In this type of binding, the
functionality of the method call is not decided at compile-time. In other words, it is not
possible to decide which piece of code will be executed as a result of a method call at
compile-time.

Overriding a method is a perfect example of dynamic binding in java.

How does Dynamic Binding Work in Java?

Consider two classes A and B such that A is the superclass of B. Assume B implements a
method already implemented in its parent class, thus overriding it. Now, this means when a
method is called on an object of the subclass type B, the implementation of the method in the
subclass will be used, even if the method is invoked through a reference of the superclass
type A.

We will discuss examples of this mechanism below. To implement Dynamic


Binding or Runtime Polymorphism, following are the conditions:

Conditions:

• Inheritance: There must be a superclass and one or more subclasses that inherit from
the superclass. The superclass should define the method that is overridden in the
subclasses.
• Method Overriding: The subclass must override the method defined in the
superclass. The method signature (i.e., the name and parameter types) must be the
same in both the superclass and the subclass.
• Upcasting: The object of the subclass must be upcast to the type of the superclass.
This is necessary because the reference variable used to call the method must be of
the same type as the superclass.
• Method Invocation: The method must be called on the object of the subclass through
the reference variable of the superclass. The implementation of the method that is
invoked will be determined at runtime based on the actual type of the object being
used.

Limitations :

1. Private methods of the parent class cannot be overridden.


2. Final methods cannot be overridden.
3. Static methods cannot be overridden.
Example Program of Dynamic Binding:

class India {
public void locate() {
System.out.println("We are in India");
}
}
class SubIndia extends India {

public void locate() //Override


{
System.out.println("We are in Delhi");
}
}

public class DynamicBindingTest {

public static void main(String args[]) {


// Method of super class or parent class is called
India superobj = new India();
superobj.locate();

// Method of sub class or child class is called by Parent reference,


// this is called "Dynamic Binding"
India subobj = new SubIndia(); // upcasting
subobj.locate();

SubIndia subobj2 = new SubIndia();


subobj2.locate(); // method of sub class or child class is called
}
}

Output:
We are in India
We are in Delhi
We are in Delhi

Explanation:

• In this code, there is a superclass called India that has a method called locate(), which
simply prints "We are in India". The subclass SubIndia extends India and overrides
the locate() method to print "We are in Delhi".
• In the main() method, an object of India is created and its locate() method is called,
which prints "We are in India".
• Then, an object of SubIndia is created and upcast to the type of India. When
the locate() method is called on this object using the India reference variable, dynamic
binding comes into play and the overridden locate() method in the SubIndia class is
called, printing "We are in Delhi". This is because the actual type of the object is
SubIndia, and so its implementation of the locate() method is used.
• Finally, an object of SubIndia is created directly and its locate() method is called,
which again prints "We are in Delhi".

DIFFERENCES BETWEEN STATIC AND DYNAMIC BINDING


Static Binding Dynamic Binding

It takes place at compile time for which is It takes place at runtime so do it is


referred to as early binding referred to as late binding.

It uses overloading more precisely operator


It uses overriding methods.
overloading method

It takes place using normal functions It takes place using virtual functions

Static or const or private functions use real


Real objects use dynamic binding.
objects in static binding

INHERITANCE CONCEPT
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. With the help of
code re-usability, the commonly used code in an application need not be written again and
again.
The inheritance can be defined as follows.
The inheritance is the process of acquiring the properties of one class to another class.

Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.

There are five types of inheritances, and they are as follows.

• Simple Inheritance (or) Single Inheritance


• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

The following picture illustrates how various inheritances are implemented.

The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.
CREATING CHILD CLASS IN JAVA
In java, we use the keyword extends to create a child class. The following syntax used to
create a child class in java.
Syntax

class <ChildClassName> extends <ParentClassName>{


...
//Implementation of child class
...
}

In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.

OVERRIDING AND EXCEPTIONS

Method Overriding in Java


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.

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which


is already provided by its superclass.
o Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding

1. The method must have the same name as in the parent class.
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class A{
public void number() {
int a=10;
System.out.println("a="+a);
}
}

class B extends A {
@Override
public void number() {
int a=30;
System.out.println("a="+a);
}
}

class Main {
public static void main(String[] args) {
B s1 = new B();
s1.number();
}
}

Output: 30

The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the method
which acquired from parent class according to its requirement.
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.

EXCEPTION IN JAVA

An exception in java programming is an abnormal situation that is raised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.

• When we try to open a file that does not exist may lead to an exception.
• When the user enters invalid input data, it may lead to an exception.
• When a network connection has lost during the program execution may lead to an
exception.
• When we try to access the memory beyond the allocated range may lead to an
exception.
• The physical device problems may also lead to an exception.

Types of Exception
In java, exceptions have categorized into two types, and they are as follows.

• Checked Exception - An exception that is checked by the compiler at the time of


compilation is called a checked exception.
• Unchecked Exception - An exception that can not be caught by the compiler but
occurs at the time of program execution is called an unchecked exception.

• How exceptions handled in Java?


• In java, the exception handling mechanism uses five keywords
namely try, catch, finally, throw, and throws.

PARAMETERS PASSING TO A METHOD IN JAVA


Let’s start this discussion by understanding the storage mechanism of Java. The reference
variables, names of methods and classes are stored in stack and their values are stored in
heap. But, the primitives are stored directly in the stack memory along with their values.
As explained earlier, Java supports only pass-by-value for both primitive and reference types
which means when a method is invoked, a copy of the value of each parameter is passed to
that method.
For primitive types such as int, double and Boolean the value of the parameter is same as the
original value of the variable. For example, if we have a variable ‘x’ with a value of 10, and
we pass ‘x’ as a parameter to a method, then the method receives a copy of original value 10
as its parameter.
Since reference variables are stored in stack, therefore, for reference types such as arrays,
objects and strings the value of the parameter is the reference or address of the given
variable. For example, if we have an array ‘arr’ with elements {1, 2, 3} and we pass ‘arr’as a
parameter to a method, then the method receives the copy of reference or address of ‘arr’ as
its parameter.

Pass by Value or Call by value


There is only call by value in java, not call by reference. If we call a method passing a value,
it is known as call by value. The changes being done in the called method, is not affected in
the calling method.
In this way of passing parameters, a copy of parameter value is passed to the given method.
That method can modify the copy, but it cannot affect the original value of the parameter.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7. public static void main(String args[]){
8. Operation op=new Operation();
9. System.out.println("before change "+op.data);
10. op.change(500);
11. System.out.println("after change "+op.data);
12. }
13. }
Output: before change 50
after change 50

Pass by Reference or Call by Reference


In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed. In
this example we are passing object as a value.
In this way of passing parameters, a reference or an address of the parameter is passed to the
given method. That method can modify the original value of the parameter by using the
reference.

1. class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. op.data=op.data+100; //changes will be in the instance variable. The original value
will be changed as we are trying to pass the objects. Objects are passed by reference.

5. }
6. public static void main(String args[]){
7. Operation2 op=new Operation2();
8. System.out.println("before change "+op.data);
9. op.change(op);// passing the object as a value using pass-by-reference
10. System.out.println("after change "+op.data);
11. }
12. }

Output: before change 50


after change 150

RECURSION IN JAVA

Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }

Java Recursion Example 1: Infinite times

public class RecursionExample1 {


void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
RecursionExample1 obj=new RecursionExample1();
obj.p();
}
}

Output:

hello
hello
...
java.lang.StackOverflowError
Java Recursion Example 2: Finite times

1. public class RecursionExample2 {


2. int count=0;
3. void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }
9. }
10. public static void main(String[] args) {
11. RecursionExample2 obj=new RecursionExample2();
12. obj.p();
13. }
14. }

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

JAVA INNER CLASSES (NESTED CLASSES)

In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer class.

Syntax

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.

class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types −

• Non-static nested classes − These are the non-static members of a class.


• Static nested classes − These are the static members of a class.

Inner Classes (Non-static Nested Classes)

Inner classes are a security mechanism in Java. We know a class cannot be associated with
the access modifier private, but if we have the class as a member of other class, then the
inner class can be made private. And this is also used to access the private members of a
class.

Inner classes are of three types depending on how and where you define them. They are −

• Inner Class
• Method-local Inner Class
• Anonymous Inner Class

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.

Following is the program to create an inner class and access it. In the given example, we
make the inner class private and access the class through a method.

Example

Live Demo
class Outer_Demo {
int num;

// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}

// Accessing he inner class from the method within


void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and
this method is invoked from the main method.

If you compile and execute the above program, you will get the following result −

Output

This is an inner class.


Live Demo

Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.

Example

Live Demo
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;

// method-local inner class


class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class

// Accessing the inner class


MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}

public static void main(String args[]) {


Outerclass outer = new Outerclass();
outer.my_Method();
}
}

If you compile and execute the above program, you will get the following result −

Output

This is method inner class 23

Anonymous Inner Class

It is an inner class without a name and for which only a single object is created. An
anonymous inner class can be useful when making an instance of an object with certain
“extras” such as overriding methods of a class or interface, without having to actually
subclass a class.

// Java program to demonstrate Need for Anonymous Inner class


// Interface
interface Age {
// Defining variables and methods
int x = 21;
void getAge();
}
// Class 1 class implementing methods of Age Interface
class MyClass implements Age {
// Overriding getAge() method
//@Override public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}
// Class 2 Main class
class ABC {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();

// calling getage() method implemented at Class1


// inside main() method
obj.getAge();
}
}
Output:
Age is 21

Here, an object to Age is not created but an object of Myclass is created and copied in the
entire class code as shown above. This is possible only with anonymous inner class. Such a
class is called ‘anonymous inner class’, so here we call ‘Myclass’ as anonymous inner
class.
Now let us do discuss the difference between regular class(normal classes) and Anonymous
Inner class
• A normal class can implement any number of interfaces but the anonymous
inner class can implement only one interface at a time.
• A regular class can extend a class and implement any number of interfaces
simultaneously. But anonymous Inner class can extend a class or can implement
an interface but not both at a time.
• For regular/normal class, we can write any number of constructors but we can’t
write any constructor for anonymous Inner class because the anonymous class
does not have any name and while defining constructor class name and
constructor name must be same.

Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing
Members of the Anonymous Class
Like local classes, anonymous classes can capture variables; they have the same access to
local variables of the enclosing scope:
• An anonymous class has access to the members of its enclosing class.
• An anonymous class cannot access local variables in its enclosing scope that are
not declared as final or effectively final.
• Like a nested class, a declaration of a type (such as a variable) in anonymous
class shadows any other declarations in the enclosing scope that have the same
name.

JAVA STATIC NESTED CLASS

A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.

o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
TestOuter1.java

1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }

Output:

data is 30

In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of the Outer class because the nested
class is static and static properties, methods, or classes can be accessed without an object.

Syntax

class MyOuter {
static class Nested_Demo {
}
}
Key Points to Remember

• Java treats the inner class as a regular member of a class. They are just like methods
and variables declared inside a class.

• Since inner classes are members of the outer class, you can apply any access
modifiers like private, protected to your inner class which is not possible in normal
classes.
• Since the nested class is a member of its enclosing outer class, you can use the dot (.)
notation to access the nested class and its members.
• Using the nested class will make your code more readable and provide better
encapsulation.
• Non-static nested classes (inner classes) have access to other members of the
outer/enclosing class, even if they are declared private.

JAVA STRING CLASS METHODS

The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on
String objects such as trimming, concatenating, converting, comparing, replacing strings
etc.Java String is a powerful concept because everything is treated as a String if you submit
any form in window based, web based or mobile application.

Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method

The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.

1. public class Stringoperation1


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase());//SACHIN
7. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s);//Sachin(no change in original)
9. }
10. }

Output:

SACHIN
sachin
Sachin

Java String trim() method

The String class trim() method eliminates white spaces before and after the String.

Stringoperation2.java

1. public class Stringoperation2


2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }

Output:

Sachin
Sachin

Java String startsWith() and endsWith() method

The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.

Stringoperation3.java

1. public class Stringoperation3


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }

Output:

true
true

Java String charAt() Method

The String class charAt() method returns a character at specified index.

Stringoperation4.java

1. public class Stringoperation4


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0));//S
7. System.out.println(s.charAt(3));//h
8. }
9. }

Output:

S
h

Java String length() Method

The String class length() method returns length of the specified String.

Stringoperation5.java

1. public class Stringoperation5


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }

Output:

Java String replace() Method

The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.

Stringoperation8.java

1. public class Stringoperation8


2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an Island.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
"Kava"
7. System.out.println(replaceString);
8. }
9. }

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

You might also like