0% found this document useful (0 votes)
42 views84 pages

Java Unit I

Java notes jntuh

Uploaded by

naninani102112
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)
42 views84 pages

Java Unit I

Java notes jntuh

Uploaded by

naninani102112
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/ 84

OBJECT ORIENTED PROGRAMMING USING JAVA

UNIT I

Thinking Object-Oriented:

Object-Oriented Programming was introduced by Alan Kay during 1960 – 1967. At


that time it was not so popular. object oriented languages really came to the attention of the
computing public-at-large in the 1980's. But nowadays the software is becoming more
popular and the size of the software has increased.

Object-oriented programming (OOP) is a programming paradigm that uses “Objects


“and their interactions to design applications.

The object oriented Programming Language is based upon the concept of “objects”,
which contains data as attributes in methods.

It simplifies the software development and maintenance.

Object:

Objects are the basic run time entities in an object oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has to
handle.

An object typically has:


1. A state: The properties or attributes of an object at a particular time.
2. Behavior: Methods represent the behavior of an object. Methods also define how the
objects communicate.
3. Identity: Identifies the object by giving it a unique name.

For Example – Consider a Television, It is an object. And the properties related to it are.
It’s With and Height, color, type (Smart TV or CRT TV), etc. And the behavior can be –
we can change the channel, Adjust volumes and settings, switch off, switch on, etc are
lots of behavior are there. The operation on the behavior will affect the
properties. Changing the channel will affect its property.
So, similar things happen in Object-Oriented programming also, that each object has some
properties and behavior associated with it, that are defined in the class.

Why OOPs are Popular in Comparison to Other Types of Programming Principles?


 Object-Oriented Programming Principles is the most popular amongst others
because it relates to real-life objects.
 Every operation that is going to be functional is considered in terms of classes
and objects. That provides a better programming style because you need not write
code that needs to run anytime.
 Instead, you can create classes defining the functionality and call that function by
creating an object of that.
 Languages that support Object-Oriented Programming are – C++, Java,
JavaScript, C#, PHP, etc.

Components of Object-Oriented Programming

1. Objects – Object is the entity that makes the classes to be implemented into the
program. It makes the features, properties, and behaviors of the class to be
implemented. Example – A car is an object that has property color, model, brand
name, fuel type, etc, and behaviors like, it runs. So these properties and behavior
make an object (CAR).
2. Classes – A class can be stated as the blueprint of the object. This states what an
object can do. It contains all the features, attributes, and behavior of what the model
can do. We can say that class contains the definition of the object. Example – Car
color, engine type, etc. And with the definition, we can create any number of objects.
3. Methods – Methods are the attributes of the class which are defined for the specified
behavior of the object. It can also modify the state of the class. Example – Method to
drive a car, It changes the state of the car from parking state to running state.
4. Instances – It is the members of the class who holds some values related to the
objects of the class.

Object-Oriented Paradigm:

 The main necessity behind inventing object oriented approach is to remove the
drawback encountered in the procedural approach.
 Object-oriented programming paradigm methods enable us to create a set of objects
that work together to produce software that is better understandable and models their
problem domains than produced using traditional techniques.
 Programs are divided into objects.
 Focus is on properties and functions rather than procedure.

 Data is hidden from external functions.

 Functions operate on the properties of an object.

 Objects may communicate with each other through a function called messaging.
 Follow the bottom-up approach in oop design

The major aspects of Object Oriented Programming (OOP) paradigm are as follows:

1. Reduced Maintenance :
The primary goal of object-oriented development is the assurance that the system will enjoy a
longer life while having far smaller maintenance costs. Because most of the processes within
the system are encapsulated, the behaviors may be reused and incorporated into new
behaviors.
2. Real-World Modeling :
Object-oriented system tend to model the real world in a more complete fashion than do
traditional methods. Objects are organized into classes of objects, and objects are associated
with behaviors. The model is based on objects, rather than on data and processing.

3. Improved Reliability and Flexibility :


Object-oriented system promise to be far more reliable than traditional systems, primarily
because new behaviors can be “built” from existing objects. Because objects can be
dynamically called and accessed, new objects may be created at any time. The new objects
may inherit data attributes from one, or many other objects. Behaviors may be inherited from
super-classes, and novel behaviors may be added without effecting existing systems
functions.

4. High Code Re usability:


When a new object is created, it will automatically inherit the data attributes and
characteristics of the class from which it was spawned. The new object will also inherit the
data and behaviors from all super classes in which it participates.
PROCEDURAL PROGRAMMING OBJECT-ORIENTED PROGRAMMING
Object oriented programming can be Procedural programming can be described as
described as a programming model which is a programming model which is derived from
based upon the concept of objects. structured programming, based upon the
concept of calling procedures.
Follows a top-down approach Follows a bottom-up approach
Instruction Oriented Data Oriented
The abstraction is at procedure (function) The abstraction is at object (class) level.
level.
The sequence of events in a large program is Entire program is divided into objects.
divided into functions.
Real world is represented by 'procedures' Real world is represented by objects and the
operating on data. operations that can be performed on these
objects.
Data and functions are separate. Data and functions are encapsulated into a
single unit.
Limited and difficult code reusability. Versatile and easy code reusability.
Code is difficult to modify, extend and Code is easy to modify, extend and maintain.
maintain.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected,etc.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is Overloading is possible in object-oriented
not possible. programming.
examples of Procedural Programming examples of Object Oriented languages are
languages are C, COBOL, Pascal. C++, Java, C#.

Advantages of OOPs

1. Re-usability
It means reusing some facilities rather than building them again and again. This is done with
the use of a class.
2. Data Redundancy
This is a condition created at the place of data storage where the same piece of data is held in
two separate places. So the data redundancy is one of the greatest advantages of OOP.
3. Code Maintenance
This feature is more of a necessity for any programming languages; it helps users from doing
re-work in many ways. It is always easy and time-saving to maintain and modify the existing
codes by incorporating new changes into them.
4. Security
With the use of data hiding and abstraction mechanism, we are filtering out limited data to
exposure, which means we are maintaining security and providing necessary data to view.
5. Easy troubleshooting
lets witness some common issues or problems any developers face in their work.
6. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
7. Problems solving
The broken components can be reused in solutions to different other problems
A WAY OF VIEWING THE WORLD:

a) 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 owers 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 owers
and carrying them to her door myself. Nevertheless, sending her the owers is an easy enough
task; I merely go down to my local orist (who happens to be named Flora), tell her the variety
and quantity of owers I wish to send and give her Sally's address, and I can be assured the
owers will be delivered expediently and automatically.

Agents and Communities:

let me emphasize that the mechanism I used to solve my problem was to find an
appropriate agent (namely, Flora) and to pass to her a message containing my request.

It is the responsibility of Flora to satisfy my request. There is some method{some


algorithm or set of operations{used by Flora to do this. I do not need to know the particular
method she will use to satisfy my request; indeed, often I do not want to know the details.
This information is usually hidden from my inspection.
If I investigated however, I might discover that Flora delivers a slightly different
message to another florist in my friend's city. That florist, in turn, perhaps has a subordinate
who makes the flower arrangement. The florist then passes the flowers, along with yet
another message, to a delivery person, and so on. Earlier, the florist in Sally's city had
obtained her flowers from a flower wholesaler who, in turn, had interactions with the flower
growers, each of whom had to manage a team of gardeners.

So, our first observation of object oriented problem solving is that the solution to my problem
required the help of many other individuals. . Without their help, my problem could not be
easily solved. We phrase this in a general fashion as the following:

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.

b) 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 delevery community), tell them
the variety and quantity of food and the hotel name from which I wish to delever 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, which led to still more
requests among the members of the community until my request has done. Here, the members
of a community interact with one another by making requests until the problem has satisfied.

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


agent (object), which is responsible for the action. The receiver is the object to whom the
message was sent. In response to the message, the receiver performs some method to carry
out the request. Every message may include any additional information as arguments.

Responsibilities:

A fundamental concept in object-oriented programming is to describe behavior in


terms of responsibilities. My request for action indicates only the desired outcome.

By discussing a problem in terms of responsibilities we increase the level of


abstraction. This permits greater independence between objects, a critical factor in solving
complex problems. The entire collection of responsibilities associated with an object is often
described by the term protocol.

A traditional program often operates by acting on data structures, for example changing fields
in an array or record. In contrast, an object oriented program requests data structures to
perform a service.

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.

This technique shows classes listed in a hierarchical tree-like structure, with more
abstract classes (such as Material Object or Animal) listed near the top of the tree, and more
specific classes, and finally individuals, are listed near the bottom.

Classes can be organized into a hierarchical inheritance structure. A child class (or
subclass) will inherit attributes from a parent class higher in the tree. An abstract parent class
is a class (such as Mammal) for which there are no direct instances; it is used only to create
subclasses.

Method Binding, Overriding, and Exceptions:

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

 Everything is an object.
 An object is a runtime entity in an object oriented programming
 Computation is performed by objects communicating with each other.
 Objects communicate by sending and receiving messages.
 A message is a request for action bundled with whatever arguments may be necessary
to complete the task.
 Each object has its own memory, which consists of other objects.
 Every object is an instance of a class.
 A class simply represents a grouping of similar objects, such as integers or lists.
 The class is the repository for behavior associated with an object.
 That is, all objects that are instances of the same class can perform the same actions.
 Classes are organized into a singly rooted tree structure, called the inheritance
hierarchy.
 Memory and behavior associated with instances of a class are automatically available
to any class associated with a descendant in this tree structure.

BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING:

1. Objects

2. Classes

3. Data abstraction

4. Encapsulation

5. Inheritance

6. Polymorphism

7. Overloading

8. Dynamic binding

9. Message passing

OBJECTS:

Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program must
handle.
The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.

The term objects means a combination of data and program that represent some real
word entity.

For example: consider an example named kumar. kumar is 25 years old and his salary is
25000. The Kumar may be represented in a computer program as an object. The data part of
the object would be (name: Kumar, age: 25, salary: 25000)

The program part of the object may be collection of programs (retrive of data, change
age, change of salary). In general even any user –defined type-such as employee may be
used. In the Amit object the name, age and salary are called attributes of the object.

CLASS:

A class can be considered as a blue print of object. A group of objects that share
common properties for data part and some program part are collectively called as class.

Class is a collection of objects of similar type. Objects are variables of the type of
class. Once a class has been defined, we can create any number of objects belonging to that
class.
DATA ABSTRACTION :

Abstraction is the process of hiding the internal details of an application from the
outer world. Classes use the concept of abstraction and are defined as size, width and cost and
functions to operate on the attributes.

Types of Abstraction

There are two types of abstraction.

1. Data Abstraction

2. Process Abstraction
DATA ENCAPSULATION :

The wrapping up of data and function into a single unit (called class) is known as
encapsulation.

Data encapsulation combines data and functions into a single unit called class. Data
encapsulation will prevent direct access to data. The data can be accessed only through
methods (function) present inside the class. The data cannot be modified by an external
nonmember function of a class. Data encapsulation enables data hiding or information hiding.

INHERITENCE:

Inheritance is a process of creating a new class from the base class. Inheritance is the
process by which objects of one class acquire the properties of another class. In the concept
of inheritance provides the idea of reusability.
POLYMORPHISIM:

The word “polymorphism” means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form. A
real-life example of polymorphism is a person who at the same time can have different
characteristics.

A man at the same time is a father, a husband, and an employee. So the same person
exhibits different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented
Programming.

Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

OVERLOADING:
Overloading allows objects to have different meaning depending uponcontext. There
are 2 types of overloading namely
1. Operator overloading
2. Function overloading
When an existing operator operates on new data type, it is called operator
overloading. Function overloading means two or more functions have same name ,but differ
in the number of arguments or data type of arguments. Therefore it is said that (function
name) is overloaded. Function overloading therefore is the process of defining same function
name to carry out similar types of activities with various data items.

DYNAMIC BINDING:

Binding is the process of connecting one program to another. Dynamic binding means
code associated with a procedure call is known only at the time of program execution routine.

MESSAGE PASSING:

In OOP, processing is done by sending messages to objects. A message for an object


is request for execution of procedure.

Message Passing in terms of computers is communication between processes.

An object oriented program consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.

Applications of object oriented programming:

1. Real – Time systems.

2. Simulation and modeling

3. Object oriented databases.

4. Hypertext, hypermedia and expertext.

5. Al and expert systems.

6. Neural networks and parallel programming.

7. Decision support and office automation systems.

8. CIM / CAM / CAD system.

OVERVIEW OF JAVA:

Java is a programming language created by James Gosling from Sun Microsystems in 1991.
Java allows to write a program and run it on multiple operating systems.

Java is a class-based object-oriented simple programming language. It is a general-purpose,


high-level programming language that helps programmers and developers to write a code
once and run it anywhere.

Java is considered both a compiled and interpreted language.

Java divided into three categories, they are


 J2SE (Java 2 Standard Edition)- J2SE is used for developing client side applications.
 J2EE (Java 2 Enterprise Edition)- is used for developing server side applications.
 J2ME (Java 2 Micro or Mobile Edition)- is used for developing mobile or wireless
application by making use of a predefined protocol called WAP
Java Terminology

1. Java Compiler: The JDK includes the Java compiler (javac), which converts Java source
code (.java files) into byte code (.class files) that can be executed by the Java Virtual
Machine (JVM).

2. Java Virtual Machine(JVM):

VM (Java Virtual Machine): The JVM is a virtual machine that executes Java bytecode. It
provides an environment for running Java programs and translates the bytecode into machine
code that can be understood by the underlying hardware.

3. Java Development Kit (JDK):

The Java Development Kit (JDK) is a software development environment used for
developing Java applications. It includes a set of tools, libraries, and compilers that are
necessary for writing, compiling, and running Java programs.

4. Java Runtime Environment (JRE):

The JRE is a subset of the JDK and includes the JVM, libraries, and other files necessary for
running Java applications. It does not contain the development tools (such as the compiler)
included in the JDK.

Java Buzzwords or Features of Java

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.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple:

 It is simple because of the following factors:


 It has Rich set of API (application protocol interface).
 It has Garbage Collector which is always used to collect un-Referenced (unused)
Memory location for improving performance of a Java program.
 It contains user friendly syntax for developing any applications.

2. Object-Oriented:

Java is a fully object-oriented programming language. It supports key concepts of


object-oriented programming, including encapsulation, inheritance, and polymorphism.
Object-oriented programming enables modular and reusable code, enhances code
organization, and promotes code maintainability.

3. Platform independent:

A program or technology is said to be platform independent if and only if which can


run on all available operating systems with respect to its development and compilation.
4.Secured:

It is more secured language compare to other language; in this language all code is
converted into byte code after compilation which is not readable by human.

5.Robust:

Simply means of Robust is strong. It is robust or strong Programming Language


because of its capability to handle Run-time Error, automatic garbage collection, lack of
pointer concept, Exception Handling. All these points make it robust Language.

6. Architecture neutral:

Architecture represents processor. A Language or Technology is said to be


Architectural neutral which can run on any available processors in the real world without
considering there architecture and vendor (providers) irrespective to its development and
compilation.

7. Portable:

If any language supports platform independent and architectural neutral feature


known as portable. The languages like C, CPP, and Pascal are treated as non-portable
language. It is a portable language.
8. Dynamic:

It supports Dynamic memory allocation, due to this memory wastage is reduced and
performance of application is improved. The process of allocating the memory space to the
input of the program at a run-time is known as dynamic memory allocation. To allocate
memory space dynamically we use an operator called 'new'. 'new' operator is known as
dynamic memory allocation operator.

9. Interpreted:

It is one of the highly interpreted programming languages.

10. High Performance:

 It has high performance because of following reasons;


 This language uses Byte code which is faster than ordinary pointer code so
Performance of this language is high.
 Garbage collector, collect the unused memory space and improve the performance of
application.
 It has no pointers so that using this language we can develop an application very
easily.
 It support multithreading, because of this time consuming process can be reduced to
execute the program.

11. Multithreaded:

A flow of control is known as thread. When any Language executes multiple threads
at a time that language is known as multithreaded Language. It is multithreaded Language.

12. Distributed:

Using this language we can create distributed application. RMI and EJB are used for
creating distributed applications. In distributed application multiple client system are depends
on multiple server systems so that even problem occurred in one server will never be
reflected on any client system.
APPLICATIONS USING JAVA:

There are mainly 4 type of applications that can be created using java

a. Standalone Application:

It is also known as desktop application or window-based application. An application


that we need to install on every machine such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications.

b. Web Application:

An application that runs on the server side and creates dynamic page, is called web
application. Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web
applications in java.

c. Enterprise Application:

An application that is distributed in nature, such as banking applications etc. It has


the advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.

d. Mobile Application:

An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.

Data Types in Java:


Data type is a special keyword used to allocate sufficient memory space for the data,
in other words Data type is used for representing the data in main memory (RAM) of the
computer.

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

Primitive Data Types:

The primitive types are also commonly referred to as simple types.

The primitive data types include Boolean, char, byte, short, int, long, float and double.

These can be put in four groups:

1. Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.

2. Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.

3. Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.

4. Boolean: This group includes Boolean, which is a special type for representing true/false
values.
Int Data Type:

The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value
is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

int a = 100000, int b = -200000

Float Data Type:

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example:

float f1 = 234.5f

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

char letterA = 'A'


Boolean Data Type:

The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value
is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.

Example:

byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value
is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

int a = 100000, int b = -200000


Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1) (inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example:

long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example:

float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like float.
The double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.

Example:

double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

char letterA = 'A’


Writing and Execution of simple Program

public class HelloWorld

public static void main(String[] args)

System.out.println("Hello world!");

Structure of the Java Program

Example

import java.lang.*; // package detials

class Demo // class Classname

int x=10; // Datamembers

void display() // user defined methods;

System.out.println(“java program structure”); //

public static void main(string args[]) // block of statements;

Demo obj=new Demo();

System.out.println(“x value is”+obj.x);

Obj.display();

}}
A package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by
default and this package is known as default package.

Class is keyword used for developing user defined data type and every java program must
start with a concept of class.

"ClassName" represent a java valid variable name treated as a name of the class each and
every class name in java is treated as user-defined data type.

Data member represents either instance or static they will be selected based on the name of
the class.

User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.

Block of statements represents set of executable statements which are in term calling user-
defined methods are containing business-logic.

The file naming conversion in the java programming is that which-ever class is containing
main() method, that class name must be given as a file name with an extension .java.

LEXICAL ISSUES (JAVA TOKENS)

A java Program is made up of Classes and Methods and in the Methods are the
Container of the various Statements And a Statement is made up of Variables, Constants,
operators etc .

Tokens are the various Java program elements which are identified by the compiler
and separated by delimiters. The delimiters are not part of the tokens. A token is the smallest
element of a program that is meaningful to the compiler. The compiler breaks lines into
chunks of text called tokens.

 Keywords
 Identifiers or names
 Literals
 Separators
 Operators
KEYWORDS:
These are special words defined in Java and represent a set of instructions.
The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:
IDENTIFIERS OR NAMES:
 Identifier is the name of variables, methods, classes etc. Rules for framing Names or
Identifiers.
 It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
 It should not contain white spaces and special symbols.
 It should not be a keyword of Java.
 It should not be Boolean literal, that is, true or false.
 It should not be null literal.
 It should not start with a digit but it can start with an underscore.
 It can comprise one or more unicode characters which are characters as well as digits.
Conventions for Writing Names:
Names of packages are completely in lower-case letters such as mypackage, java.lang.
• Names of classes and interfaces start with an upper-case letter.
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.
LITERALS:
These are values represented by a set of character, digits, etc.
• A literal represents a value which may be of primitive type, String type, or null type.
• The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc.
• A literal is a constant value.

SEPARATORS:
These include comma, semicolon, period(.), Parenthesis (), Square brackets [], etc

OPERATORS: Operators are mostly represented by symbols such as +, -, *, etc


Types of Operators:
VARIABLES:

It is an identifier that denotes a storage location used to store a data value. A variable
provides us with named storage that our programs can manipulate.

A variable name may consists of alphabets, digits or underscore.


As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _) and
dollar characters, subject to the following conditions:

 It should not be a keyword.


 White space is not allowed.
 Variable names can be of any length.
 They must not begin with a digit.

Declaration of Variables:

In Java, variables are the names of storage locations. After designing suitable variable names,
we must declare them to the compiler.

A variable must be declared before it is used in the program.

A variable can be used to store a value of any data type.

The general form of declaration of a variable is:

Variables are separated by commas. A declaration statement must end with a semicolon.
Some valid declarations are:

Example:

int a, b, c; // Declares three ints, a, b, and c.

int a = 10, b = 10; // Example of initialization

byte B = 22; // initializes a byte type variable B.

double pi = 3.14159; // declares and assigns a value of PI.

char a = 'a'; // the char variable a is initialized with value 'a'

There are three kinds of variables in Java:

 Local variables
 Instance variables
 Class/static variables

Example:

class A
{
int data=50; //instance variable
static int m=100; //static variable
void method( )
{
int n=90; //local variable
}
} // end of class

Local Variable:

A variable declared inside the body of the method is called local variable.

Access modifiers cannot be used for local variables.

There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.

Example:

Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to this method only.

public class Test

public void pupAge( )

int age = 0;

age = age + 7;

System.out.println("Puppy age is : " + age);

public static void main(String args[])

Test test = new Test();

test.pupAge();

Output:

Puppy age is: 7

Instance Variable:
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.

Instance variables are created when an object is created with the use of the keyword 'new' and
dest royed when the object is destroyed.

Instance variables can be declared in class level before or after use.

Instance variables have default values. For numbers the default value is 0

Instance variables can be accessed directly by calling the variable name inside the class.

Class/Static variable:

Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.

Static variables are stored in static memory.

Static variables are created when the program starts and destroyed when the program stops.

Static variables can be accessed by calling with the class name . ClassName.VariableName.

JAVA ARRAYS
An array is a collection of similar data types with a contiguous memory location. It is
used to store multiple values in a single variable instead of declaring separate variables for
each value. It is also known as static data structure because size of an array must be specified
at the time of its declaration.

Arrays are indexed, meaning each array element has a specific position (also called
index) that is used to access it. Array starts from zero index and goes to n-
1 where n is length of the array.

There are two types of arrays in Java.

1. One-Dimensional Arrays.
2. Multi-Dimensional Arrays.

One-Dimensional Arrays:
Single dimensional array use single index to store elements.

Syntax:

dataType[] arr;

dataType []arr;

dataType arr[];

Example:
int[] intArray; // Declare an integer array

Example on Single Dimensional Array:

class Testarray1

public static void main(String args[])

int a[]={33,3,4,5};//declaration, instantiation and initialization

for(int i=0;i<a.length;i++)

System.out.println(a[i]);

}}

Output : 33

Multi-Dimensional Arrays
In Java, a multidimensional array is an array of arrays. It is a data structure that allows
you to store multiple arrays in a single array. The most common types of multidimensional
arrays are two-dimensional (2D) and three-dimensional (3D) arrays, but Java also supports
arrays with more than three dimensions. These types of arrays are also known
as jagged arrays.

Syntax

<data-type>[][] <variable-name>

<data-type> <variable-name>[][]

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

Examples on Two Dimensional array

Example 1: program to declare,create,initialize and access the elements of 2-D array

class array2d

public static void main(String args[])


{

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

for(int i=0;i<3;i++)

for(int j=0;j<3;J++)

System.out.print(arr[i][j]+" ");

System.out.println();

}}}

Output:1 2 3

245

445

Jagged Array:

Jagged array is an array that has different numbers of columns elements. In java, a
jagged array means to have a multi-dimensional array with uneven size of columns in it.

int[ ][ ] arr = new int[3][ ];

arr[0] = new int[3];

arr[1] = new int[4];

arr[2] = new int[5];

Rules for creating an Array

 At the time of array creation compulsory we should specify the size otherwise we will
get compile time error.
 It is legal to have an array with size zero in java.
 The allowed data types to specify array size are byte, short, char, int. By mistake if we
are using any other type we will get compile time error.
 The maximum allowed array size in java is maximum value of int size [2147483647].

Example 2 : program for Addition of two matrix

class twodarrayaddition
{

public static void main(String args[])

//creating two matrices

int a[][]={{1,3,4},{3,4,5}};

int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices

int c[][]=new int[2][3];

//adding and printing addition of 2 matrices

for(int i=0;i<2;i++)

for(int j=0;j<3;j++)

c[i][j]=a[i][j]+b[i][j];

System.out.print(c[i][j]+" ");

System.out.println();//new line

}}}

Output : 2 6 8

6 8 10

TYPE CONVERSION
Type conversion is a process in which the data type is automatically converted into
another data type.

The compiler does this automatic conversion at compile time. This type of type
conversion is also called Widening Type Conversion/ Implicit Conversion/ Casting Down.

For type conversion to take place, the destination data type must be larger than the source
type. In short, the below flow chart has to be followed.
In this case, as the lower data types with smaller sizes are converted into higher ones with a
larger size, there is no chance of data loss. This makes it safe for usage.

TYPE CASTING
Type casting is a process in which the programmer manually converts one data type
into another data type. For this the casting operator (), the parenthesis is used. Type casting is
also called Narrowing Type Casting/ Explicit Conversion/ Casting Up.

This case, as the higher data types with a larger size are converted into lower ones
with a smaller size, there is a chance of data loss.

Java Expressions

An expression is a series of variables, operators, and method calls that evaluates to a single
value.

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

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

Infix Expression

The expression in which the operator is used between operands is called infix expression.

Postfix Expression

The expression in which the operator is used after operands is called postfix expression.
Prefix Expression

The expression in which the operator is used before operands is called a prefix expression.

OPERATORS

Java supports a rich set of operators. An operator is a symbol that tells the computer
to perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They usually form a part of mathematical or logical
expressions.

Java operators can be classified into a number of related categories as below:

 Arithmetic Operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 Conditional operators
 Bitwise operators
 Special operators

Arithmetic Operators:

Arithmetic operators are used to construct mathematical expressions as in algebra.


Java provides all the basic arithmetic operators. These can on any built-in numeric data type
of Java.
Relational Operators

We often compare two quantities, and depending on their relation, take certain
decisions. For example, we may compare the age of two persons, or the price of two items,
and so on. These comparisons can be done with the help of relational operators.

a < b or x < 20

Logical Operators

The logical operators && and | | are used when we want to form compound conditions by
combining two or more relations. An example is:

a > b && x == 10

An expression of this kind which combines two or more relational expressions is termed as a
logical expression or a compound relational expression.

Assignment Operators:
Assignment operators are used to assign the value of an expression to a variable. We
have seen the usual assignment operator, ‘=’. In addition, Java has a set of ‘shorthand’
assignment operators which are used in the form

where v is a variable, exp is an expression and op is a Java binary operatory. The


operator op = is known as the shorthand assignment operator.

Increment and Decrement Operators:

Java has two very useful operators not generally found in many other languages. These are
the increment and decrement operators.

++ and ––

Conditional Operator

The character pair ? : is a ternary operatory available in Java. This operator is used to
construct conditional expressions of the form

where exp1, exp2, and exp3 are expressions.

The operator ? : works as follows: exp1 is evaluated first. If it is nonzero (true), then the
expression exp2 is evaluated and becomes the value of the conditional expression. If exp1 is
false, exp3 is evaluated and its value becomes the value of the conditional expression. None
that only one of the expressions (either exp2 or exp3) is evaluated. For example, consider the
following statements:

a = 10; b = 15; x = (a > b) ? a : b;

In this example, x will be assigned the value of b. This can be achieved using the if….else
statement as follows:

if(a > b)

x = a;

else

x = b;

Bitwise Operators:

Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left. Bitwise
operators may not be applied to float or double.

Special Operators(Miscellaneous Operators)

Java supports some special operators of interest such as instanceof operatory and member
selection operator (.).

The instanceof is an object operator and returns true of the object on the left-hand side is an
instance of the class given on the right-hand side. This operator allows us to determine
whether the object belongs to a particular class or not.

Example: person instanceof student

CONTROL STATEMENTS

A programming language uses control statements to control the flow of execution of a


program. In Java programming, we can control the flow of execution of a program based on
some conditions. Java control statements can be put into the following three categories:
SELECTION STATEMENTS( CONDITIONAL STATEMENT):

The Java selection statements allow your program to choose a different path of
execution based on a certain condition. Java selection statements provide different type of
statements such as:

1. if statement.

2. if-else statement.

3. if-else-if ladder statement.

4. nested if statement.

if Statement:

if statement in Java is a simple decision-making statement. Java if statement is used to


decide whether a certain statement or block of the statement will be executed or not. If a
certain condition is true, then the block of statement is executed, otherwise not.

Syntax:

if(condition)

Statement(s);

Flowchart:
Example

public class IfStatementExample

public static void main(String args[])

int num=70;

if( num < 100 )

System.out.println("number is less than 100");

}}

Output:

number is less than 100

if-else Statement:

if statement is used to decide whether a certain statement or block of the statement


will be executed or not. If a certain condition is true, then the block of statement is executed,
otherwise not. But, if you want to do something else if the condition is false then we should
use else statement. We can use else statement with if statement to execute the block of code
when the condition is false.

Syntax:

if(condition)

{
//code for if statement

else{

//code for else statement.

Example of if-else statement

public class IfElseExample

public static void main(String args[])

int num=120;

if( num < 50 )


{

System.out.println("num is less than 50");

else

System.out.println("num is greater than or equal 50");

}}}

Output:

num is greater than or equal 50

if-else-if Statement:

if-else-if statement is used when we need to check multiple conditions. As soon as


one of the conditions controlling the if is true, the statement associated with that if is
executed, If none of the conditions is true, then the final else statement will be executed. The
final else acts as a default condition; that is, if all other conditional tests fail, then the last else
statement is performed.

Syntax

if(condition1)
{
//statement1;
}
else if(condition2)
{
//statement2;
}
else if(condition3)
{
//statement3;
}
.........
.........
.........
Else
{
//default statement;
}

Example:
public class IfElseIfExample
{
public static void main(String args[])
{
int num=1234;
if(num <100&&num>=1)
{
System.out.println("Its a two digit number");
}
else if(num <1000&&num>=100)
{
System.out.println("Its a three digit number");
}
else if(num <10000&&num>=1000)
{
System.out.println("Its a four digit number");
}
else if(num <100000&&num>=10000)
{
System.out.println("Its a five digit number");
}
Else
{
System.out.println("number is not between 1 & 99999");
}
}
}

Output:

Its a four digit number

Nested if statement:

When there is an if statement inside another if statement then it is called the nested if
statement.

Syntax:

if(condition1){

//code to be executed for condition1

if(condition2){

//code to be executed for condition2

Example

public class NestedIfExample


{
public static void main(String args[])
{
int num=70;
if( num < 100 )
{
System.out.println("number is less than 100");
if(num > 50)
{
System.out.println("number is greater than 50");
}}}}

Decision Making Statement:( Switch Case statement)

Switch case statement is used when we have number of options (or choices) and we may need
to perform a different task for each choice.

A switch statement can work with byte, short, char, and int primitive data types. It also works
with enumerated types and the String class.

The value of the expression is compared with each of the literal values in the case statements.

If a match is found, the code sequence following that case statement is executed. If none of
the constants matches the value of the expression, then the default statement is executed.
The default statement is optional.

The break statement is used inside the switch to terminate a statement sequence.

Syntax

switch(expression)
{
case value1:
//statement sequence
break;
case value2:
//statement sequence
break;
.......
.......
.......
case valueN:
//statement sequence
break;
default:
//default statement sequence
}
Example

class WeekDays
{
public static void main(String s[])

int day = 2;
switch(day)

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

default:

System.out.println("Invalid");

break;

}}}
Iteration statement (Looping Statement):

Java Iteration statements allow program execution to repeat one or more statements. java
Iteration statements provide different type of statements such as:

1. For loop.
2. While loop.
3. Do While loop.

1. For loop.
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
The for loop in java is used to iterate a part of the program several times.
The Java for loop consumes initialization, condition, and increment/decrement in one line.

Syntax

for(initialization; condition; incr/decr){

//body of the loop.

initialization: The initialization expression initializes the loop;

condition: In this step, we can check the condition. If the condition is true, then the body of
the loop is executed otherwise not.

increment/decrement: In this step, we can increment or decrement the value of a variable.

class ForLoop
{
public static void main(String args[]){
System.out.println("The values from 1 to 10 is: ");

// initialization; condition; incr/decr.


for(int i = 1; i<=10; i++)
{
System.out.println(i);
}
}
}

While Loop:

The while loop in java is the most fundamental looping statement. Java while
loop repeats a statement or a block while a particular condition is true. You can use a while
loop if the number of iteration is not fixed.

Syntax

while(boolean condition)
{
//body of the loop.
}

class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
}}}
Output:
10
9
8
7
6
5
4
3
2

Do While loop:

do-while loop is similar to while loop. In while loop, condition is evaluated before the
execution of loop’s body but in do-while loop condition is evaluated after the execution of
loop’s body.

Do
{
statement(s);
}
while(condition);

class DoWhileLoopExample
{
public static void main(String args[])
{
int i=10;
do
{
System.out.println(i);
i--;
}
while(i>1);
}}
Output:
10
9
8
7
6
5
4
3
2
Jump Statements:
Java Jump statements transfer the control to other parts of the program. java Jump
statements provide different type of statements such as:

1. break statement.

2. continue statement

break statement

Java break statement can be used to terminate the loop. It can be used inside a loop. We can
use a break statement in all types of loops such as: while loop, do-while loop, and for loop.
When a break statement is encountered inside a loop, the loop is terminated and the program
control goes to the next statement following the loop.

public class BreakExample3


{
public static void main(String args[])
{
int num=2;
switch (num)
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");

break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}}}

continue statement:

Continue statement is mostly used inside loops. Whenever it is encountered inside a loop,
control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration.

public class ContinueExample


{
public static void main(String args[])
{
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.print(j+" ");
}}}
Output: 0 1 2 3 5 6

Introducing Classes:
Class fundamentals
How to create classes by using the following basics:
 The parts of a class definition
 Declaring and using instance variables
 Defining and using methods
 Creating Java applications, including the main() method and how to pass arguments to
a Java program from a command line

What is a class in Java?


A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity.
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Syntax to declare a class:
Class
{
field;
method;
}
Declaration of Object and its initialization
To create an object of the class we use new keyword as shown below syntax
classname objectname=new classname( );

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method

3. By constructor

Object and Class Example: Initialization through reference:

class Student

int id;

String name;

class TestStudent2

public static void main(String args[])

Student s1=new Student();

s1.id=101;

s1.name="Sonoo";

System.out.println(s1.id+" "+s1.name);//printing members with a white space

}}

Output: 101 Sonoo

Object and Class Example: Initialization through method


class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);
}
}
class TestStudent4{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}}
Output:
111 Karan
222 Aryan

Object and Class Example: Initialization through a constructor


class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s)
{
id=i;
name=n;
salary=s;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}}
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
DIFFERENCE BETWEEN OBJECT AND CLASS
OBJECT CLASS
Object is an instance of a class. Class is a blueprint or template from which
objects are created.
Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair
etc.
Object is a physical entity. Class is a logical entity.
Object is created through new keyword Class is declared using class keyword
e.g. Student s1=new Student(); e.g. class Student{}
Object is created many times as per Class is declared once.
requirement.
Object allocates memory when it is created. Class doesn't allocated memory when it is
created.

Method in Java
A method is a block of statements. A method is like a function which is used to expose the
behavior of an object. Every method is used to perform a specific task. a method defined as a
behavior of an object.
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.

Advantage of Method

 Code Reusability
 Code Optimization

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.

Syntax:

class <ClassName>

<accessSpecifier> <returnType> <methodName>( parameters )

{
...

block of statements;

...

//Java Program to demonstrate the working of a banking-system

//where we deposit and withdraw amount from our account. //Creating an Account class
which has deposit() and withdraw() methods

class Account

int acc_no;

String name;

float amount;

//Method to initialize object

void insert(int a,String n,float amt){

acc_no=a;

name=n;

amount=amt;

//deposit method

void deposit(float amt){

amount=amount+amt;

System.out.println(amt+" deposited");

//withdraw method

void withdraw(float amt){

if(amount<amt){
System.out.println("Insufcient Balance");

}else{

amount=amount-amt;

System.out.println(amt+" withdrawn");

}}

//method to check the balance of the account

void checkBalance(){System.out.println("Balance is: "+amount);}

//method to display the values of an object

void display(){System.out.println(acc_no+" "+name+" "+amount);}

//Creating a test class to deposit and withdraw amount

class TestAccount{

public static void main(String[] args){

Account a1=new Account();

a1.insert(832345,"Ankit",1000);

a1.display();

a1.checkBalance();

a1.deposit(40000);

a1.checkBalance();

a1.withdraw(15000);

a1.checkBalance();

}}

Output:

832345 Ankit 1000.0

Balance is: 1000.0

40000.0 deposited

Balance is: 41000.0


15000.0 withdrawn

Balance is: 26000.0

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. The string values are organized as an array
of a character data type.

The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.

Creating String object in java


we can use the following two ways to create a string object.

 Using string literal

Using new keyword

String literal:

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 = "Welcome";

String str2 = "Welcome";

Using New Keyword

String str1 = new String("Welcome");

String str2 = new String("Welcome");

STRING HANDLING METHODS:


METHOD DESCRIPTION RETURN VALUE
compareTo(String) Compares two strings Int
concat(String) Concatenates the object string String
with argument string.
toLowerCase() Converts a string to lower case String
letters
toUpperCase() Converts a string to upper case String
letters
replace(String, String) Replaces the first string with String
second string

INHERITANCE:
Inheritance can be defined as the process where an object of a class acquires
characteristics from the object of another class.

Inheritance is a process of defining a new class based on an existing class by


extending its common data members and methods.

The process by which one class acquires the properties(data members) and
functionalities (methods) of another class is called inheritance.

The class, which is inherited by the other classes, is known as superclass or base class
or parent class and the class, which inherits the properties of the base class, is called sub class
or derived class or child class. The sub-class can further be inherited to form other derived
classes.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

Reusability: As the name specifes, reusability is a mechanism which facilitates you to reuse
the felds and methods of the existing class when you create a new class. You can use the
same felds and methods already defned in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and felds

}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

TYPES OF INHERITANCE

 Single level inheritance


 Multiple Inheritance
 Multi-level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Single level inheritance

This type of inheritance occurs for only a single class. Only one class is derived
from the parent class. In this type of inheritance, the properties are derived from a single
parent class. As the properties are derived from only a single base class the reusability of a
code is facilitated along with the addition of new features.

Syntax of Single Inheritance

class base class


{
.... methods
}
class derivedClass name extends baseClass
{
methods ...
}

Example:

class Employee
{
void salary()
{
System.out.println("Salary= 200000");
}}
class Programmer extends Employee // Programmer class inherits from Employee
class
{
void bonus()
{
System.out.println("Bonus=50000");
}}
class single_inheritance
{
public static void main(String args[])
{

Programmer p = new Programmer();


p.salary(); // calls method of super class
p.bonus(); // calls method of sub class
}}

Output:
Salary= 200000

Bonus=50000

Multiple Inheritance
Multiple inheritances is a type of inheritance where a subclass can inherit features
from more than one parent class.

In multiple inheritances the newly derived class can have more than one superclass.

Java does not support multiple inheritance. This means that we can not use multiple
inheritance in java but a class can inherit properties from many classes in java using
interfaces.

Class C is derived from the two classes Class A and Class B. In other words it can be
described that subclass C inherits properties from both Class A and B.

Multi-level Inheritance
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.
In the multilevel inheritance in java, the inherited features are also from the
multiple base classes as the newly derived class from the parent class becomes the base
class for another newly derived class.

package com.techvidvan.inheritance;
//Base class
class Person
{
public void show()
{
System.out.println("Student inheriting properties from Person");
}
}
class Student extends Person
{
public void show1()
{
System.out.println("I am a Student who belongs to Person class");
}
}
//child class
class EngineeringStudent extends Student
{
// defining additional properties to the child class
public void show2()
{
System.out.println("Engineering Student inheriting properties from Student");
}
}
public class MultilevelDemo
{
public static void main(String args[])
{
EngineeringStudent obj = new EngineeringStudent();
obj.show();
obj.show1();
obj.show2();
}
}

Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance in Java where multiple derived classes
inherit the properties of a parent class. It allows all the child classes to inherit methods and
fields from their parent class.

Syntax

Class P {
// fields and methods
}

class C1 extends P {
// fields and methods
}

class C2 extends P {
// fields and methods
}

class C3 extends P {
// fields and methods
}
Hybrid Inheritance
Hybrid inheritance is a combination of more than two types of inheritances single
and multiple. It can be achieved through interfaces only as multiple inheritance is not
supported by Java. It is basically the combination of simple, multiple, hierarchical
inheritances.

class C
{
public void disp()
{
System.out.println("C");
}
}

class A extends C
{
public void disp()
{
System.out.println("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}

Output: D

ADVANTAGES OF INHERITANCE:
 Code reusability - public methods of base class can be reused in derived classes
 Data hiding – private data of base class cannot be altered by derived class
 Overriding- With inheritance, we will be able to override the methods of the base
class in the derived class

USING SUPER
 super keyword is similar to this keyword in Java.
 It is used to refer to the immediate parent class of the object.
Super keyword used in 3 levels:
It can be used to refer immediate parent class instance variable when both parent and
child class have member with same name
It can be used to invoke immediate parent class method when child class has
overridden that method.
super() can be used to invoke immediate parent class constructor.

Use of super with variables:


Example:
class SuperCls
{
int x = 20;
}
class SubCls extends SuperCls
{
int x = 80;
void display()
{
System.out.println(“Super Class x: “ + super.x); //print x of super class
System.out.println(“Sub Class x: “ + x); //print x of subclass
}}
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}}
Sample Output:
Super Class x: 20
Sub Class x: 80

Use of super with methods:


The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class (Method Overriding).
Example:
class SuperCls
{
int x = 20;
void display() //display() in super class
{
System.out.println(“Super Class x: “ + x);
}}
class SubCls extends SuperCls
{
int x = 80;
void display() //display() redefined in sub class – method overriding
{
System.out.println(“Sub Class x: “ + x);
super.display(); // invoke super class display()
}}
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}}
Sample Output:
Sub Class x: 80
Super Class x: 20

Use of super with constructors:


The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();

 super() if present, must always be the first statement executed inside a subclass
constructor.
 When we invoke a super() statement from within a subclass constructor, we are
invoking the immediate super class constructor

Example:
class Vehicle
{

Vehicle( )
{
System.out.println("Vehicle is created");
}}
class Bike extends Vehicle
{
Bike()
{
super( ); //will invoke parent class constructor
System.out.println("Bike is created");
}}
class SuperClassConst
{
public static void main(String args[])
{
Bike b=new Bike();
}}

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

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

}}

THE FINAL KEYWORD IN JAVA


The final keyword in Java indicates that no further modification is possible. Final is a
keyword in java used for restricting some functionalities. We can declare variables, methods and
classes with final keyword.

Using final with inheritance

Final can be used with:

Class

Methods

Variables

Class declared as final:

Method declared as final


Example

Variable declared as final


this keyword in java
Here is given the 6 usage of java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method(implicitly)
3. this() can be used to invoke current class constructor
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display( )
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=newStudent(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000

CONSTRUCTORS IN JAVA
 Constructors are used to initialize the state of an object when it is created.
 Constructors are invoked while creating objects, usually after the new keyword. Every
time an Object is created using the new() keyword, at least one constructor is called.
 It is called when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
public class MyClass
{
//This is the constructor
MyClass()
{
} .. }

Rules for creating Java 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 Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Default Constructor:
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{}

Example:
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}}

Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide diferent values to distinct objects.
Example
class Student4
{
int id;
String name;
Student4(int i,String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]) //creating objects and passing values
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display(); //calling method to display the values of object
s2.display();
}}

CONSTRUCTOR OVERLOADING
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.
Example
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor

COPY CONSTRUCTOR
There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

//Java program to initialize the values from one object to another object.
class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n)
{
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}}
Output:
111 Karan
111 Karan

DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD IN JAVA


CONSTRUCTOR METHOD
A constructor is used to initialize the state of A method is used to expose the behavior of
an object. 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 constructor name must be same as the The method name may or may not be same
class name. as the class name.
CREATING MULTILEVEL HIERARCHY

How to create a multilevel hierarchy in Java


In simple inheritance, a subclass or derived class derives the properties from its parent
class, but in multilevel inheritance, a subclass is derived from a derived class. One class
inherits the only single class. Therefore, in multilevel inheritance, every time ladder increases
by one. The lowermost class will have the properties of all the superclass.
Person

Employee

Manager

Example:
class A
{
A( )
{
System.out.println("A constructor");
}
void Amethod( )
{
System.out.println("method of A");
}}
class B extends A
{
B( )
{
System.out.println("B constructor");
}
void Bmethod( )
{
System.out.println("method of B");
}
void welcome( )
{
System.out.println("class B-welcome method");
}}
class C extends B
{
C( )
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");
}
public static void main(String args[])
{
C oc=new C( );
oc.Amethod( );
oc.Bmethod( );
oc.welcome( );
}}
Output:
A constructor
B constructor
C constructor
method of A
method of B
method of A

POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java:
1. Compile-time polymorphism or Ad hoc polymorphism
2. Runtime polymorphism. Or Pure polymorphism
Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
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) foe two parameters, and
b(int,int,int) for three parameters then it may be difficult foe you as well as other
programmers to understand the behavior of the method because its name differs.
Example:
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}}
Output:
30
60

Runtime Polymorphism (or Dynamic polymorphism)


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.
Method Overriding:
If subclass (child class) has the same method as declaeed in the paeent class, it is known as
method overriding in Java.

Example
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}}
Output: Bike is running safely

DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD


OVERRIDING
METHOD OVERLOADING METHOD OVERRIDING
Method overloading is a compile-time Method overriding is a run-time
polymorphism. polymorphism.
Method overloading helps to increase the Method overriding is used to grant the
readability of the program. specific implementation of the method
which is already provided by its parent class
or super class.
It occurs within the class. It is performed in two classes with
inheritance relationships.
Method overloading may or may not require Method overriding always needs
inheritance. inheritance.
Static binding is being used for overloaded Dynamic binding is being used for
methods. overriding methods.
Private and final methods can be overloaded. Private and final methods can’t be
overridden.

STATIC VS DYNAMIC BINDING

STATIC BINDING DYNAMIC BINDING


It happens at the compile time. It happens at the run time.
It is also called early binding. It is also called late binding.
It can be achieved during normal function It is achieved with the use of virtual
calls, function overloading and operator functions.
overloading.
Execution becomes faster than dynamic As the function call is resolved at run time,
binding because the function call gets sometimes it leads to slower code execution.
resolved before run time.
It provides less flexibility compared to the It provides more flexibility as different types
dynamic binding. of objects at runtime can be handled by a
single function call making the source code
more readable.
ABSTRACT CLASSES

A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body). It needs to be extended and
its method implemented.

Syntax:

abstract class classname

}
ABSTRACT METHOD

A method that is declared as abstract and does not have implementation is known as
abstract method. The method body will be defined by its subclass.

Syntax:

abstract returntype functionname (); //No definition

THE OBJECT CLASS

The Object class is the parent class of all the classes in java by default (directly or
indirectly). The java.lang.Object class is the root of the class hierarchy. Some of the Object
class are Boolean, Math, Number, String etc.

FORMS OF INHERITANCE:

All objects eventually inherit from Object, which provides useful methods such as
equals and toString.

Inheritance gets used for a number of purposes in typical object-oriented programming:

specialization -- the subclass is a special case of the parent class

specification -- the superclass just specifies which methods should be available but doesn't
give code. This is supported in java by interfaces and abstract methods.
construction -- the superclass is just used to provide behavior, but instances of the subclass
don't really act like the superclass.

extension -- subclass adds new methods, and perhaps redefines inherited ones as well.

limitation -- the subclass restricts the inherited behavior.

combination -- multiple inheritance. Provided in part by implementing multiple interfaces.

FORMS OF INHERITANCE (- INHERITANCE FOR SPECIALIZATION -)

Most commonly used inheritance and sub classification is for specialization. Always
creates a subtype, and the principles of substitutability is explicitly upheld. It is the most ideal
form of inheritance.

An example of subclassification for specialization is; public class PinBallGame extends


Frame {

// body of class

Specialization

1.By far the most common form of inheritance is for specialization.


 Child class is a specialized form of parent class
 Principle of substitutability holds
2.A good example is the Java hierarchy of Graphical components in the AWT:
 Component
 Label
 Button
 TextComponent
 TextArea
 TextField
 CheckBox
 ScrollBar

FORMS OF INHERITANCE (- INHERITANCE FOR SPECIFICATION -)

This is another most common use of inheritance. Two different mechanisms are
provided by Java, interface and abstract, to make use of subclassification for specification.
Subtype is formed and substitutability is explicitly upheld.

Mostly, not used for refinement of its parent class, but instead is used for definitions
of the properties provided by its parent.

class FireButtonListener implements ActionListener


{

// body of class

class B extends A {

// class A is defined as abstract specification class

Specification

The next most common form of inheritance involves specification. The parent class
specifies some behavior, but does not implement the behavior

 Child class implements the behavior


 Similar to Java interface or abstract class
 When parent class does not implement actual behavior but merely defines the
behavior that will be implemented in child classes

Example, Java 1.1 Event Listeners:

ActionListener, MouseListener, and so on specify behavior, but must be subclassed.

FORMS OF INHERITANCE (- INHERITANCE FOR CONSTRUCTION -)

Child class inherits most of its functionality from parent, but may change the name or
parameters of methods inherited from parent class to form its interface.

This type of inheritance is also widely used for code reuse purposes. It simplifies the
construction of newly formed abstraction but is not a form of subtype, and often violates
substitutability.

Example is Stack class defined in Java libraries.

Construction

The parent class is used only for its behavior, the child class has no is-a relationship to
the parent.

 Child modify the arguments or names of methods

An example might be subclassing the idea of a Set from an existing List class.

 Child class is not a more specialized form of parent class; no substitutability

FORMS OF INHERITANCE (- INHERITANCE FOR EXTENSION -)


Subclassification for extension occurs when a child class only adds new behavior to
the parent class and does not modify or alter any of the inherited attributes.

Such subclasses are always subtypes, and substitutability can be used.

Example of this type of inheritance is done in the definition of the class Properties
which is an extension of the class HashTable.

Generalization or Extension

The child class generalizes or extends the parent class by providing more functionality

 In some sense, opposite of subclassing for specialization

The child doesn't change anything inherited from the parent, it simply adds new features

 Often used when we cannot modify existing base parent class

Example, ColoredWindow inheriting from Window

 Add additional data fields


 Override window display methods

FORMS OF INHERITANCE (- INHERITANCE FOR LIMITATION -)

Subclassification for limitation occurs when the behavior of the subclass is smaller or
more restrictive that the behavior of its parent class.

Like subclassification for extension, this form of inheritance occurs most frequently
when a programmer is building on a base of existing classes.

Is not a subtype, and substitutability is not proper.

LIMITATION

 The child class limits some of the behavior of the parent class.
 Example, you have an existing List data type, and you want a Stack
 Inherit from List, but override the methods that allow access to elements other than
top so as to produce errors.

FORMS OF INHERITANCE (- INHERITANCE FOR COMBINATION -)

This types of inheritance is known as multiple inheritance in Object Oriented Programming.

Although the Java does not permit a subclass to be formed be inheritance from more than one
parent class, several approximations to the concept are possible.

Example of this type is Hole class defined as;


class Hole extends Ball implements PinBallTarget{

// body of class

Combination

 Two or more classes that seem to be related, but its not clear who should be the parent
and who should be the child.
 Example: Mouse and TouchPad and JoyStick
 Better solution, abstract out common parts to new parent class, and use subclassing
for specialization.

THE BENEFITS OF INHERITANCE

 Software Reusability (among projects)


 Increased Reliability (resulting from reuse and sharing of well-tested code)
 Code Sharing (within a project)
 Consistency of Interface (among related objects)
 Software Components
 Rapid Prototyping (quickly assemble from pre-existing components)
 Polymorphism and Frameworks (high-level reusable components)
 Information Hiding

THE COSTS OF INHERITANCE

 Execution Speed
 Program Size
 Message-Passing Overhead
 Program Complexity (in overuse of inheritance)

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