0% found this document useful (0 votes)
67 views43 pages

JP Unit 1

This document contains notes for a Java programming course, including objectives, outcomes, and content for 5 units. Unit 1 covers object-oriented concepts like classes, objects, inheritance and polymorphism. It explains that object-oriented programming models the real world as a community of interacting agents (objects). Each object provides services (methods) to other objects. Problems are solved by objects passing messages to request services from other objects.

Uploaded by

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

JP Unit 1

This document contains notes for a Java programming course, including objectives, outcomes, and content for 5 units. Unit 1 covers object-oriented concepts like classes, objects, inheritance and polymorphism. It explains that object-oriented programming models the real world as a community of interacting agents (objects). Each object provides services (methods) to other objects. Problems are solved by objects passing messages to request services from other objects.

Uploaded by

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

JAVA PROGRAMMING NOTES UNIT-1

GURU NANAK INSTITUTE OF TECHNOLOGY

JAVA PROGRAMMING (CS405PC)


COMPLETE 5 UNITS NOTES
II B.Tech - II Semester

C.Sangeetha, Assistant Professor, IT Dept, GNIT 1


JAVA PROGRAMMING NOTES UNIT-1

JAVA PROGRAMMING (CS405PC)


Course Objectives:
 To introduce the object oriented programming concepts.
 To understand object oriented programming concepts, and apply them in solving
problems.
 To introduce the principles of inheritance and polymorphism; and demonstrate how
they
 relate to the design of abstract classes
 To introduce the implementation of packages and interfaces
 To introduce the concepts of exception handling and multithreading.
 To introduce the design of Graphical User Interface using applets and swing controls.

Course Outcomes:
 Able to solve real world problems using OOP techniques.
 Able to understand the use of abstract classes.
 Able to solve problems using java collection framework and I/o classes.
 Able to develop multithreaded applications with synchronization.
 Able to develop applets for web applications.
 Able to design GUI based applications

UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and Communities,
messages and methods, Responsibilities, Classes and Instances, Class Hierarchies-
Inheritance, Method binding, Overriding and Exceptions, Summary of Object-Oriented
concepts. Java buzzwords, An Overview of Java, Data types, Variables and Arrays,
operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors,
Creating Multilevel hierarchy, super uses, using final with inheritance, Polymorphism-ad
hoc polymorphism, pure polymorphism, method overriding, abstract classes, Object
class, forms of inheritance- specialization, specification, construction, extension,
limitation, combination, benefits of inheritance, costs of inheritance.

UNIT - II
Packages- Defining a Package, CLASSPATH, Access protection, importing packages.
Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying
interfaces, variables in interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams,
Reading console Input and Writing Console Output, File class, Reading and writing Files,
Random access file operations, The Console class, Serialization, Enumerations, auto
boxing, generics.

UNIT - III
Exception handling - Fundamentals of exception handling, Exception types,
Termination or resumptive models, Uncaught exceptions, using try and catch, multiple
catch clauses, nested try statements, throw, throws and finally, built- in exceptions,
creating own exception sub classes.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 2


JAVA PROGRAMMING NOTES UNIT-1

Multithreading- Differences between thread-based multitasking and process-based


multitasking, Java thread model, creating threads, thread priorities, synchronizing
threads, inter thread communication.

UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The
Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array
Deque. Accessing a Collection via an Iterator, Using an Iterator, The For-Each
alternative, Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The
Legacy Classes and Interfaces- Dictionary, Hashtable, Properties, Stack, Vector, More
Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner

UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture,
components, containers. Understanding Layout Managers, Flow Layout, Border Layout,
Grid Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners,
Event classes, Handling mouse and keyboard events, Adapter classes, Inner classes,
Anonymous Inner classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets
and Applications, passing parameters to applets. Creating a Swing Applet, Painting in
Swing, A Paint example, Exploring, Swing Controls- JLabel and Image Icon, JText Field,
The Swing Buttons- JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed
Pane, JScroll Pane, JList, JCombo Box, Swing Menus, Dialogs.

TEXT BOOKS:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education
(India) Pvt.Ltd.
2. Understanding Object-Oriented Programming 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. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
3. Object Oriented Programming through Java, P. Radha Krishna, University Press.
4. Programming in Java, S. Malhotra, S. Chudhary, 2nd edition, Oxford Univ. Press.
5. Java Programming and Object-oriented Application Development, R. A. Johnson,
Cengage Learning.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 3


JAVA PROGRAMMING NOTES UNIT-1

UNIT-I
Object-Oriented Thinking- A way of viewing world – Agents and Communities,
messages and methods, Responsibilities, Classes and Instances, Class Hierarchies-
Inheritance, Method binding, Overriding and Exceptions, Summary of Object-Oriented
concepts. Java buzzwords, An Overview of Java, Data types, Variables and Arrays,
operators, expressions, control statements, Introducing classes, Methods and Classes,
String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors,
Creating Multilevel hierarchy, super uses, using final with inheritance, Polymorphism-ad
hoc polymorphism, pure polymorphism, method overriding, abstract classes, Object
class, forms of inheritance- specialization, specification, construction, extension,
limitation, combination, benefits of inheritance, costs of inheritance.

Object-oriented programming has been a hot topic for over a decade, and more recently
Java has become the commonly perceived embodiment of object-oriented ideas. Object-
oriented programming is frequently referred to as a new programming paradigm. The
word paradigm originally meant example, or model.

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


programming, let us consider how we might go about handling a real-world situation
and then ask how we could make the computer more closely model the techniques
employed. Suppose I wish to send flowers to a friend who lives in a city many miles
away. Let me call my friend Sally. Because of the distance, there is no possibility of my
picking the flowers and carrying them to her door myself. Nevertheless, sending her the
flowers is an easy enough task; I merely go down to my local Florist (who happens to be
named Flora), tell her the variety and quantity of flowers I wish to send and give her
Sally's address, and I can be assured the flowers will be delivered expediently and
automatically.
An object oriented program is structured as a community of interacting agents, called
objects. Each object has a role to play. Each object provides a service, or performs an
action, that is used by other members of the community.

The community of agents helping me.

Another example of a real-world situation.


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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 4


JAVA PROGRAMMING NOTES UNIT-1

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, me 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
requests among the members of the community until my request has done. Here, the
members of a community interact with one another by making requests until the
problem has satisfied.
In object-oriented programming, every action is initiated by passing a message to an
agent (object), which is responsible for the action. The receiver is the object to whom the

C.Sangeetha, Assistant Professor, IT Dept, GNIT 5


JAVA PROGRAMMING NOTES UNIT-1

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) is free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.

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.

Summary of Object-Oriented 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.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 6


JAVA PROGRAMMING NOTES UNIT-1

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


 Object
 Class
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

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

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


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

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


For example: phone call, we don't know the internal processing. In the abstraction
concept, we do not show the actual implementation to the end user, instead we provide
only essential things. For example, if we want to drive a car, we do not need to know
about the internal functionality like how wheel system works, how brake system works
and how music system works etc.

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 7


JAVA PROGRAMMING NOTES UNIT-1

Encapsulation: Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are
private here.

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

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


For example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 8


JAVA PROGRAMMING NOTES UNIT-1

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

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

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

Procedural and object oriented programming paradigms

Procedure Oriented Programming (POP) Object Oriented Programming (OOP)

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


designing a program.

Program is divided into small chunks based Program is divided into objects
on the functions. depending on the problem.

Functions are more important than data in The main priority is data rather than
a program. functions in a program.

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

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

Different parts of a program are The functions of the objects are linked
interconnected via parameter passing. via message passing.

Operator overloading is not allowed. Operator overloading is allowed.

Exception Handling is not present. Exception Handling is done with Try and
Catch block.

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 9


JAVA PROGRAMMING NOTES UNIT-1

Java Buzz Words: Java is the most popular object-oriented programming language.
Java has many advanced features, a list of key features is known as Java Buzz Words.
The java team has listed the following terms as java buzz words.

 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic

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

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

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

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


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

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

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


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

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


programs that do multiple operations simultaneously.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 10


JAVA PROGRAMMING NOTES UNIT-1

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


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

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

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

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

An Overview of Java:
Java is a computer programming language. Java was created based on C and C++. Java
uses C syntax and many of the object-oriented features are taken from C++. Before Java
was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk,
etc. These languages had few disadvantages which were corrected in Java. Java also has
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.

History of Java

 The C language developed in 1972 by Dennis Ritchie had taken a decade to become
the most popular language.
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with
included OOP fundamentals and features.
 A project named “Green” was initiated in December of 1990, whose aim was to create
a programming tool that could render obsolete the C and C++ programming
languages.
 Finally in the year of 1991 the Green Team was created a new Programming language
named “OAK”.
 After some time they found that there is already a programming language with the
name “OAK”.
 So, the green team had a meeting to choose a new name. After so many discussions
they want to have a coffee. They went to a Coffee Shop which is just outside of the
Gosling’s office and there they have decided name as “JAVA”.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 11


JAVA PROGRAMMING NOTES UNIT-1

Execution Process of Java Program:


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.

Java 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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 12


JAVA PROGRAMMING NOTES UNIT-1

Primitive Data Types:

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

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

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

Data Memory Default


type Meaning size Range Value

Byte Whole numbers 1 byte -128 to +127 0

Short Whole numbers 2 bytes -32768 to +32767 0

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

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


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

Float Fractional 4 bytes - 0.0f


numbers

Double Fractional 8 bytes - 0.0d


numbers

Char Single character 2 bytes 0 to 65535 \u0000

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

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

Example
public class PrimitiveDataTypes
{
byte i; short j; int k; long l; float m; double n;
char ch; boolean p;
public static void main(String[] args)
{
PrimitiveDataTypes obj = new PrimitiveDataTypes();
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}

C.Sangeetha, Assistant Professor, IT Dept, GNIT 13


JAVA PROGRAMMING NOTES UNIT-1

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.

Example:
public class NonPrimitiveDataTypes
{
String str;
public static void main(String[] args)
{
String name = "BTech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str); //using addition method
System.out.println(wish.concat(name));
}
}

Primitive Vs Non-primitive Data Types

Primitive Data Type Non-primitive Data Type

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

Does not support additional methods Support additional methods

Always has a value It can be null

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

Size depends on the data type Same size for all

Java Variables: A variable is a named memory location used to store a data value. 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; (or)
data_type variable_name = value; (or)
data_type variable_name_1 = value;

C.Sangeetha, Assistant Professor, IT Dept, GNIT 14


JAVA PROGRAMMING NOTES UNIT-1

In java programming language variables are classified as follows.


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

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

Example:
public class LocalVariables
{
public void show()
{
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
System.out.println("Inside display method, a = " + a);
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}

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

Example
public class ClassVariables
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;

C.Sangeetha, Assistant Professor, IT Dept, GNIT 15


JAVA PROGRAMMING NOTES UNIT-1

}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args)
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}

3. Static variables or Class variables


A static variable is a variable that declared using static keyword. The instance
variables can be static variables but local variables cannot. Static variables are
initialized only once, at the start of the program execution. The static variable only
has one copy per class irrespective of how many objects we create.

The static variable is access by using class name.

Example
public class StaticVariablesExample
{
int x, y; // Instance variables
static int z; // Static variable
StaticVariablesExample(int x, int y)
{
this.x = x;
this.y = y;
}
public void show()
{
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args)
{
StaticVariablesExample obj_1 = new StaticVariablesExample(10, 20);
StaticVariablesExample obj_2 = new StaticVariablesExample(100, 200);
obj_1.show();
StaticVariablesExample.z = 1000;
obj_2.show();
}
}
4. 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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 16


JAVA PROGRAMMING NOTES UNIT-1

variable created using final keyword acts as constant. All variables like local,
instance, and static variables can be final variables.

Example
public class FinalVariableExample
{
final int a = 10;
void show()
{
System.out.println("a = " + a);
a = 20; //Error due to final variable cann't be modified
}
public static void main(String[] args)
{
FinalVariableExample obj = new FinalVariableExample();
obj.show();
}
}

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

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

1. One Dimensional Array


2. Multi Dimensional Array

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

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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 17


JAVA PROGRAMMING NOTES UNIT-1

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

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

NullPointerException with Arrays: In java, an array created without size and initialized
to null remains null only. It does not allow us to assign a value. When we try to assign a
value it generates a NullPointerException.

Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = null;
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}

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


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

Example
public class ArrayExample
{
public static void main(String[] args)
{
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}

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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 18


JAVA PROGRAMMING NOTES UNIT-1

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


size = read.nextInt();
short list[] = new short[size];
System.out.println("Enter any " + size + " numbers: ");
for(int i = 0; i < size; i++) // Simple for statement
list[i] = read.nextShort();
for(int i : list) // for-each statement
sum = sum + i;
System.out.println("Sum of all elements: " + sum);
}
}

Multidimensional Array: In java, we can create an array with multiple dimensions. We


can create 2-dimensional, 3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional
array variable, specify each additional index using another set of square brackets. 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.

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.
1. Arithmetic Operators
2. Relational (or) Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Conditional Operators
Let's look at each operator in detail.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 19


JAVA PROGRAMMING NOTES UNIT-1

1. Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like
addition, subtraction, multiplication, division, modulus, increment, decrement, etc.,

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

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

++ Increment a++

-- Decrement a--

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


The relational operators are the symbols that are used to compare two values. That
means the relational operators are used to check the relationship between two values.
Every relational operator has two 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 10 < 5 is FALSE
second value otherwise returns FALSE

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

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

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

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


otherwise returns FALSE

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


otherwise returns FALSE

C.Sangeetha, Assistant Professor, IT Dept, GNIT 20


JAVA PROGRAMMING NOTES UNIT-1

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

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

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

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

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


and returns FALSE if it is TRUE

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

|| short-circuit OR - Similar to Logical OR (|), but once


a decision is finalized it does not evaluate remaining.

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

Operator Meaning Example

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

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

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


value and store the result into left-hand side variable

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


value and store the result into left-hand side variable

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


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

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


variable value and store the remainder into the left-hand

C.Sangeetha, Assistant Professor, IT Dept, GNIT 21


JAVA PROGRAMMING NOTES UNIT-1

Operator Meaning Example

side variable

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

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

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


Operator Meaning Example

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


the bits are 1 otherwise it is 0

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


the bits are 0 otherwise it is 1

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


the bits are same otherwise it is 1

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


complement is negation of the bit
(Flipping)

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


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

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


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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 22


JAVA PROGRAMMING NOTES UNIT-1

Example
public class ConditionalOperator
{
public static void main(String[] args)
{
int a = 10, b = 20, c;
c = (a>b)? a : b;
System.out.println("c = " + c);
}
}

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.

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

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

Infix Expression- The expression in which the operator is used between operands is
called infix expression. The infix expression has the following general structure.

Example

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

Example

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

Example

C.Sangeetha, Assistant Professor, IT Dept, GNIT 23


JAVA PROGRAMMING NOTES UNIT-1

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
 else-if statement
 nested if statement
 switch statement

Iterative Control Statements


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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 24


JAVA PROGRAMMING NOTES UNIT-1

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

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

Java Selection Statements


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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 25


JAVA PROGRAMMING NOTES UNIT-1

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.

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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 26


JAVA PROGRAMMING NOTES UNIT-1

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.

Java Iterative Statements


The java programming language provides a set of iterative statements that are used to
execute a statement or a block of statements repeatedly as long as the given condition is
true. The iterative statements are also known as looping statements or repetitive
statements. Java provides the following iterative statements.
 while statement
 do-while statement
 for statement
 for-each statement

while statement in java


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

Example:
while(num <= 10)
{
System.out.println(num);
num++;
}

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.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 27


JAVA PROGRAMMING NOTES UNIT-1

The do-while statement has the following syntax.


Example:
do
{
System.out.println(num);
num++;
}while(num <= 10);

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

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

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

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

Java Jump Statements:


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

break statement: The break statement in java is used to terminate a switch or looping
statement. That means the break statement is used to come out of a switch statement
and a looping statement like while, do-while, for, and for-each.

continue statement: The continue statement is used to move the execution control to
the beginning of the looping statement. When the continue statement is encountered in a
looping statement, the execution control skips the rest of the statements in the looping
block and directly jumps to the beginning of the loop. The continue statement can be
used with looping statements like while, do-while, for, and for-each.

labeled break and continue statements: The java programming language does not
support goto statement, alternatively, the break and continue statements can be used
with label.

return statement: In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling function.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 28


JAVA PROGRAMMING NOTES UNIT-1

That means the return statement transfer the execution control from called function to
the calling function by carrying a value.

Java 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.

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

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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 29


JAVA PROGRAMMING NOTES UNIT-1

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>( );

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

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


means, every method in java must belong to a class.
Every method in java must be declared inside a class. Every method declaration has the
following characteristics.
 returnType - Specifies the data type of a return value.
 name - Specifies a unique name to identify it.
 parameters - The data values it may accept or recieve.
 { } - Defienes the block belongs to the method.

Creating a method: A method is created inside the class and it may be created with any
access specifier. However, specifying access specifier is optional.
Following is the syntax for creating methods in java.

Syntax
class <ClassName>
{
<accessSpecifier> <returnType> <methodName>( parameters )
{
block of statements;
}
}

Calling a method: In java, a method call precedes with the object name of the class to
which it belongs and a dot operator. It may call directly if the method defined with the
static modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.

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

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


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

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 30


JAVA PROGRAMMING NOTES UNIT-1

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

Example
public class ConstructorExample
{
ConstructorExample()
{
System.out.println("Object created!");
}
public static void main(String[] args)
{
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}

Java String Handling: A string is a sequence of characters surrounded by double


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

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

Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);

The String class defined in the package java.lang package.


The String class implements Serializable, Comparable, and CharSequence interfaces.

The string created using the String class can be extended. It allows us to add more
characters after its definition, and also it can be modified.
Example
String siteName = "JavaProgram.com";
siteName = "JavaProgram.com";

String handling methods:


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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 31


JAVA PROGRAMMING NOTES UNIT-1

System.out.println("Length of title: " + title.length());


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

Inheritance:
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in
another class. The inheritance provides a greate 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.

Types of Inheritance: When deriving a class from a base class, the base class may be
inherited through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above. We hardly use protected or private
inheritance, but public inheritance is commonly used. While using different type of
inheritance, following rules are applied:

1.Single 2.Multiple 3.Multilevel 4.Hierarchial 5.Hybrid

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.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 32


JAVA PROGRAMMING NOTES UNIT-1

Example:
class ParentClass
{
int a;
void setData(int a)
{
this.a = a;
}
}
class ChildClass extends ParentClass
{
void showData()
{
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.setData(100);
obj.showData();
}
}
Java Access Modifiers: In Java, the access specifiers (also known as access modifiers)
used to restrict the scope or accessibility of a class, constructor, variable, method or
data member of class and interface. There are four access specifiers, and their list is
below.

 default (or) no modifier


 public
 protected
 private

In java, we cannot employ all


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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 33


JAVA PROGRAMMING NOTES UNIT-1

Let's look at the following example java code, which generates an error because a class
does not allow private access specifier unless it is an inner class.

Example
private class Sample
{
}

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

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.

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

void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);

C.Sangeetha, Assistant Professor, IT Dept, GNIT 34


JAVA PROGRAMMING NOTES UNIT-1

System.out.println("b = " + b);


System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass
{
void accessData()
{
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}

Java Constructors in Inheritance:


It is very important to understand how the constructors get executed in the inheritance
concept. In the inheritance, the constructors never get inherited to any child class.

In java, the default constructor of a parent class called automatically by the constructor
of its child class. That means when we create an object of the child class, the parent
class constructor executed, followed by the child class constructor executed.

Example1
class ParentClass
{
int a;
ParentClass()
{
System.out.println("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("Inside ChildClass constructor!!");
}
}

C.Sangeetha, Assistant Professor, IT Dept, GNIT 35


JAVA PROGRAMMING NOTES UNIT-1

class ChildChildClass extends ChildClass


{
ChildChildClass()
{
System.out.println("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance
{
public static void main(String[] args)
{
ChildChildClass obj = new ChildChildClass();
}
}

However, if the parent class contains both default and parameterized constructor, then
only the default constructor called automatically by the child class constructor.

Example2
class ParentClass
{
int a;
ParentClass(int a)
{
System.out.println("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass()
{
System.out.println("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass
{
ChildClass()
{
System.out.println("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
}
}

The parameterized constructor of parent class must be called explicitly using the super
keyword.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 36


JAVA PROGRAMMING NOTES UNIT-1

Super keyword: In java, super is a keyword used to refer to the parent class object. The
super keyword came into existence to solve the naming conflicts in the inheritance.
When both parent class and child class have members with the same name, then the
super keyword is used to refer to the parent class version.

In java, the super keyword is used for the following purposes.


 To refer parent class data members
 To refer parent class methods
 To call parent class constructor

The super keyword is used inside the child class only.

super to refer parent class data members: When both parent class and child class
have data members with the same name, then the super keyword is used to refer to the
parent class data member from child class.

To call the parameterized constructor of the parent class, the super keyword must be the
first statement inside the child class constructor, and we must pass the parameter
values.

super to refer parent class method: When both parent class and child class have
method with the same name, then the super keyword is used to refer to the parent class
method from child class.

super to call parent class constructor: When an object of child class is created, it
automatically calls the parent class default-constructor before its own. But, the
parameterized constructor of parent class must be called explicitly using the super
keyword inside the child class constructor.

To call the parameterized constructor of the parent class, the super keyword must be the
first statement inside the child class constructor, and we must pass the parameter
values.

Final keyword: In java, the final is a keyword and it is used with the following things.
 With variable (to create constant)
 With method (to avoid method overriding)
 With class (to avoid inheritance)

Final with variables: When a variable defined with the final keyword, it becomes a
constant, and it does not allow us to modify the value. The variable defined with the final
keyword allows only a one-time assignment, once a value assigned to it, never allows us
to change it again.

Final with methods: When a method defined with the final keyword, it does not allow it
to override. The final method extends to the child class, but the child class cannot
override or re-define it. It must be used as it has implemented in the parent class.

Final with class: When a class defined with final keyword, it cannot be extended by any
other class.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 37


JAVA PROGRAMMING NOTES UNIT-1

Polymorphism:
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behavior.
In java, polymorphism implemented using method overloading and method overriding.

Ad hoc polymorphism: The ad hoc polymorphism is a technique used to define the


same method with different implementations and different arguments. In a java
programming language, ad hoc polymorphism carried out with a method overloading
concept.

In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism.
Every function call binded with the respective overloaded method based on the
arguments.

The ad hoc polymorphism implemented within the class only.


Example
import java.util.Arrays;
public class AdHocPolymorphismExample
{
void sorting(int[] list)
{
Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names)
{
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
}

public static void main(String[] args)


{
AdHocPolymorphismExample obj = new AdHocPolymorphismExample();
int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array
String[] names = {"rama", "raja", "shyam", "seeta"};
obj.sorting(names); // Calling with String array
}
}

Pure polymorphism: The pure polymorphism is a technique used to define the same
method with the same arguments but different implementations. In a java programming
language, pure polymorphism carried out with a method overriding concept.

In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 38


JAVA PROGRAMMING NOTES UNIT-1

When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.

Example
class ParentClass
{
int num = 10;
void showData()
{
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}

class ChildClass extends ParentClass


{
void showData()
{
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism


{
public static void main(String[] args)
{
ParentClass obj = new ParentClass();
obj.showData();

obj = new ChildClass();


obj.showData();
}
}

Java Method Overriding:


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.

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

C.Sangeetha, Assistant Professor, IT Dept, GNIT 39


JAVA PROGRAMMING NOTES UNIT-1

10 Rules for method overriding


While overriding a method, we must follow the below list of rules.
1. Static methods cannot be overridden.
2. Final methods cannot be overridden.
3. Private methods cannot be overridden.
4. Constructor cannot be overridden.
5. An abstract method must be overridden.
6. Use super keyword to invoke overridden method from child class.
7. The return type of the overriding method must be same as the parent has it.
8. The access specifier of the overriding method can be changed, but the visibility must
increase but not decrease. For example, a protected method in the parent class can
be made public, but not private, in the child class.
9. If the overridden method does not throw an exception in the parent class, then the
child class overriding method can only throw the unchecked exception, throwing a
checked exception is not allowed.
10.If the parent class overridden method does throw an exception, then the child class
overriding method can only throw the same, or subclass exception, or it may not
throw any exception.

Java Abstract Class


An abstract class is a class that created using abstract keyword. In other words, a class
prefixed with abstract keyword is known as an abstract class.

In java, an abstract class may contain abstract methods (methods without


implementation) and also non-abstract methods (methods with implementation).

Syntax
abstract class <ClassName>
{
}

An abstract class cannot be instantiated but can be referenced. That means we cannot
create an object of an abstract class, but base reference can be created.

8 Rules for method overriding


An abstract class must follow the below list of rules.
1. An abstract class must be created with abstract keyword.
2. An abstract class can be created without any abstract method.
3. An abstract class may contain abstract methods and non-abstract methods.
4. An abstract class may contain final methods that cannot be overridden.
5. An abstract class may contain static methods, but the abstract method cannot be
static.
6. An abstract class may have a constructor that gets executed when the child class
object created.
7. An abstract method must be overridden by the child class, otherwise, it must be
defined as an abstract class.
8. An abstract class cannot be instantiated but can be referenced.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 40


JAVA PROGRAMMING NOTES UNIT-1

Java Object Class


In java, the Object class is the super most class of any class hierarchy. The Object class
in the java programming language is present inside the java.lang package.

Every class in the java programming language is a subclass of Object class by default.

The Object class is useful when you want to refer to any object whose type you don't
know. Because it is the super class of all other classes in java, it can refer to any type of
object.

Methods of Object class


The following table depicts all built-in methods of Object class in java.

Return
Method Description Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object compares the argument object to calling object. boolean


obj)

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() returns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's void


monitor.

notifyAll() wakes up all the threads, waiting on invoking object's void


monitor.

wait() causes the current thread to wait, until another void


thread notifies.

wait(long,int) causes the current thread to wait for the specified void
milliseconds and nanoseconds, until another thread
notifies.

finalize() It is invoked by the garbage collector before an object void


is being garbage collected.

Java Forms of Inheritance


The inheritance concept used for the number of purposes in the java programming
language. One of the main purposes is substitutability. The substitutability means that
when a child class acquires properties from its parent class, the object of the parent

C.Sangeetha, Assistant Professor, IT Dept, GNIT 41


JAVA PROGRAMMING NOTES UNIT-1

class may be substituted with the child class object. For example, if B is a child class of
A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.

The following are the different forms of inheritance in java.


 Specialization
 Specification
 Construction
 Extension
 Limitation
 Combination

Specialization: It is the most ideal form of inheritance. The subclass is a special case of
the parent class. It holds the principle of substitutability.

Specification: This is another commonly used form of inheritance. In this form of


inheritance, the parent class just specifies which methods should be available to the
child class but doesn't implement them. The java provides concepts like abstract and
interfaces to support this form of inheritance. It holds the principle of substitutability.

Construction: This is another form of inheritance where the child class may change the
behavior defined by the parent class (overriding). It does not hold the principle of
substitutability.

Extension: This is another form of inheritance where the child class may add its new
properties. It holds the principle of substitutability.

Limitation: This is another form of inheritance where the subclass restricts the
inherited behavior. It does not hold the principle of substitutability.

Combination: This is another form of inheritance where the subclass inherits properties
from multiple parent classes. Java does not support multiple inheritance type.

Benefits and Costs of Inheritance in java


The inheritance is the core and more useful concept of Object Oriented Programming. It
provides inheritance; we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.

Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 42


JAVA PROGRAMMING NOTES UNIT-1

 With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
 In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.

Costs of Inheritance
 Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.

C.Sangeetha, Assistant Professor, IT Dept, GNIT 43

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy