KEMBAR78
Java Unit-1 | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
18 views92 pages

Java Unit-1

The document discusses the evolution of software programming, contrasting Procedure-Oriented Programming (POP) with Object-Oriented Programming (OOP). It highlights the key concepts of OOP, including encapsulation, inheritance, and polymorphism, and outlines the benefits and applications of OOP. Additionally, it provides an overview of Java, its development milestones, and its features, emphasizing its object-oriented nature and platform independence.
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)
18 views92 pages

Java Unit-1

The document discusses the evolution of software programming, contrasting Procedure-Oriented Programming (POP) with Object-Oriented Programming (OOP). It highlights the key concepts of OOP, including encapsulation, inheritance, and polymorphism, and outlines the benefits and applications of OOP. Additionally, it provides an overview of Java, its development milestones, and its features, emphasizing its object-oriented nature and platform independence.
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/ 92

Unit-I

1. Fundamentals of Object-Oriented Programming


Software Evolution: -
Earnest Tello, a well-known writer in the field of artificial intelligence, compared the evolution of
software technology to the growth of a tree. Like a tree, the software evolution has had distinct
phases or “layers” of growth. These layers were built up one by one over the last five decades,
with each layer representing an improvement over the previous one as shown in the below figure.

1,0

Machine language

Assembly Language

Procedure-Oriented

Object-Oriented Programming

Fig : Layers of Computer Software


Since the invention of the computer, many programming approaches have been tried. These includede
technique such as modular programming, top-down programming, bottom-up programming and
structured programming

C is a structured programming became very popular and was the main technique of the
.
1980s. Structured programming was a powerful tool that enabled programmers to write moderately
complex programs fairly easily. However, as the programs grew later, even the structured approach
failed to show the desired results in terms of bug-free, easy to maintain and reusable programs.
Object oriented programming (OOP) is an approach to program organisation and development that
attempts to eliminate some of the drawbacks in pop and introducing the new concepts. It is a new way
of organizing and developing programs.
Procedure Oriented Programming (POP):-
Conventional programming, using high level languages such as COBOL, FORTRAN and C is
commonly known as procedure-oriented programming. In the procedure-oriented approach, the
problem is viewed as a sequence of things to be done such as reading, calculating and printing.
A number of functions are written to accomplish these tasks.
The primary focus is on functions, the below figure explains the technique of hierarchical
decomposition has been used to specifies the task to be completed for solving a problem.

Main Program

Function-1 Function-2 Function-3

Function-4 Function-5

Function-6 Function-7 Function-8

Figa.procedure oriented programming

Procedure-oriented programming basically consists of functions. Each function can perform


particular task to follow the computer.
In multifunction program many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data as shown below figure.

Global Data Global Data

Function-1 Function-2 Function-3

Local Data Local Data Local Data

Fig b. Relationship of data and functions in pop


Some Characteristic are exhibited by procedure-oriented programming
1. Emphasis on doing algorithms
2. Large programs can be divided into smaller programs known as function.
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Employees follow top-down approach in program design.

Object Oriented Programming (OOP):-


The major objective of object-oriented approach is to eliminate some of the flaws are
encountered in the procedural approach. Oop treats data as a critical element in the program
development and does not allow from one function to another function.
Oop allows us to decompose a problem into a number of entities is called as object and then build
data and functions around the system. The combination of data and methods make up an object
as shown in the below figure.

Method
Metho

Dat
a
Metho Metho
d d

Fig a) object=Data +methods


The Data of an object can be accessed only by the methods associated with that object.
Some of the features of object-oriented paradigm are:
➢ Emphasis is on data rather than procedure.
➢ Programs are divided into what are known as objects
➢ Methods that operate on the data of an object are tied together in the data structure.
➢ Data is hidden and can’t be accessed by external functions.
➢ Objects may communicate with each other through methods.
➢ New data and methods can be easily added whenever necessary.
➢ Follows bottom-up approach in program design.
Our definition of oop is: oop is an approach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand.
Difference between pop and oop:-
Procedure oriented programming Object oriented programming
1) POP follows a top-down
1) OOP takes a bottom-up
approach
approach in designing a
2) Program is divided into small
program.
chunks based on the functions.
2) Program is divided into objects
3) Each function contains different data.
depending on the problem.
4) Follows a systematic approach to
3) Each object controls its own
solve the problem.
data.
5) Functions are more important than
4) Focuses on security of the data
data in a program.
irrespective of the algorithm.
6) Data hiding is possible in OOP. 5) The main priority is data rather than
7) Inheritance is not allowed functions in a program.
8) Operator overloading is not 6) No easy way for data hiding
allowed. 7) Inheritance is allowed in oop.
9) Example for the pop Pascal,
8) Operator overloading is
COBOL, FORTRAN and c. allowed.
9) Example for the oop c++,
java,.net and python.

Basic Concepts of Object Oriented Programming (Principles of oops):-


To understand some of the concepts used extensively in oop. We shall now discuss the general
concepts of oop which form the heart of java language.
They are
1. Objects and classes
2. Data Abstraction and Encapsulation
3. Inheritance
4. Polymorphism
5. Dynamic Binding
6. Message communication
1. Objects and Classes:
Objects are the basic runtime entities in an object-oriented system. They may represent
a person, a place, a bank account, a table of data or any item. They may also represent user defined
data types such as vectors and lists. Any programming problem is analysed in terms of objects and
the nature of communication between them. An object takes up space in the memory and has an
associated address like a structure in c. The below figure shows represent an object in the object-
oriented analysis and design.

Person
Object
Name
Data
BasicPay

Salary()
Methods

Tax()

Fig. a. Representation of an object

When a program is executed the objects interact by sending message to one another. Each object
contains data and code to manipulate the data. A class is thus a collection of objects of similar
type. For example mango, apple, orange are the members of the class fruit. Classes are user
defined data types and behave like the built-in types of programming language.
Fruit *mango
Will create an object mango belonging to the class fruit.

2)Data Abstraction and Encapsulation:


The wrapping of data and methods into a single unit (called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class.
The data is not accessible to outside the world and only those methods can access it. These
methods provide the interface between the objects data and program.
Encapsulation makes it possible for objects to be treated like „black boxes‟, each performing a
specific task without any concern for internal implementation as shown below figure.
Data
Information “in” and Information “out”
Method
s

Fig. b. Encapsulation-Objects as “black boxes”

Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight, cost and methods that operate on these methods.
3) Inheritance:- Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concepts of hierarchical
classification.
For example the bird robin is a part of the class flying bird, which is again a part of the class bird.
As illustrated in the below figure.

Bird
Attribut
es:
Feather
s Lay

Flying
N
Bird
Attributes on
: Fly
ing
Bir
d
Attr
Robin Swallo Pengui Kiwi
w n
Attributes Attributes Attributes Attributes
: : : :

Fig. c. Property Inheritance


The concept of inheritance provides the idea of reusability. This means we can add additional
features to an existing class without modifying it. This is possible by deriving a new class from
the existing one. The new class will have the combined features of the both classes.
4. Polymorphism:
Polymorphism is another important oop concept. Polymorphism means the ability to take more
than one form. For example, an operation may exhibit different behaviours in different instances.
The behaviour depends on types of data used in operation.
For example, consider the operation of addition of two numbers; the operation will generate a
sum. If the operands are strings, then the operation would produce a third string by
concatenation.

Shape
Draw()

Circle Object Box Object Triangle


Draw (circle) Draw (box) Object
Draw (triangle)

Fig d. Polymorphism
In the above figure, a single function name can be used to handle different number and different types
of arguments. Polymorphism plays an important role in allowing objects having different internal
structure to share the same external interfaces.
5. Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means the code associated with a given procedure call, it will be executed until the
time of the call at run time. It is associated with polymorphism and inheritance.
6. Message Communication:
An oop consists of a set of objects that communicate with each other. The process of programming
in an object oriented language.
Therefore, involves the following basic steps:

1. Creating classes that define objects and their behaviour.


2. Creating objects from class definitions.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people pass message to one another.

Obj
ect1

Obj
Obj ect2
ect5

Obj Obj
ect4 ect3

A message for an object is request for execution of a procedure and therefore we will invoke a
method in the receiving object that generates the desired result as shown in the below figure.

Method()

Sending object receiving object


Message passing involves specifying the name of the objects, the name of the method and the
information to be sent.
Benefits of oops:-
Oop offers several benefits to both the program designer and the user. Object oriented contributes
to the solution of many problems associated with the development and quality of software products.
The principal advantages are:-
➢ Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
➢ The principle of data hiding helps the programmer to build secure programs that cannot
be accessed other part of the program.
➢ It is possible to have multiple objects to communicate without any interface.
➢ It is easy to partition the work in a project based on objects.
➢ Object oriented systems can be easily upgrade from small to large systems.
➢ Software complexity can be easily managed.
Applications of oops:-
Applications of oop are beginning to gain importance in many areas. The
promising areas for application of oop include:
 Real-time systems
 Simulation and modeling
 Object oriented databases
 Hypertext, hypermedia and expert text
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAD/CAD systems.
It is believed that the richness of oop environment will enable the software industry to improvement
not only the quality of software but also its productivity. Object oriented technology is certainly
changing the way software engineers think, analyse, design and implement systems today.

What is java:-
Java is a general purpose; object oriented programming language developed by sun Microsystems
of USA in 1991. Originally called Oak by James Gosling, one of the inventors of the language.
Java was designed for the development of software for consumer electronic devices like TVs,
VCRs, toasters and such other electronic machines.
The goal of the java team to develop the language is a simple, portable and highly reliable. The
Patrick Newton discovered that the existing languages like c and c++ had limitations in terms of
both reliability and portability. However, they modeled their new language java on c and c++ but
removed a number of features of c and c++ that were considered as sources of problems and thus
made java a really simple, reliable, portable and powerful language.
Java Milestones:

Year Development
1990 Sun Microsystems decided to develop special software
that could be used to manipulate consumer electronic devices.
1991 The team announced a new language named “oak”
1992 using hand-held devices with a tiny touch-sensitive screen.
1993 The World Wide Web
1994 The team developed a web browser called “HotJava” 1995
Oak was renamed “java”.
1996 Sun Releases java development kit 1.0
1997 Sun Releases java development kit 1.1(JDK1.1)
1998 Sun Releases Software Development kit (SDK1.2)
1999 Sun Releases J2SE (Java 2 Standard Enterprise) and J2EE (Java 2
Enterprise Edition).
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. This is known as J2SE5.0
Features of java:-
Sun Microsystems officially describes java with the following features.
i) Compiled and interpreted
ii) Platform independent and portable
iii) Object oriented
iv) Robust and Secure
v) Distributed
vi) Simple, small and familiar
vii) Multithreaded and interactive
viii) High performance
ix) Dynamic and Extensible
x) JDBC RowSet
i) Compiled and Interpreted:
Usually a computer language is either compiled or interpreted. Java combines both these
approaches. Thus making a two-stage system. First java compiler translates source code into byte
code instructions. Byte codes are not machine instructions and therefore in the second stage java
interpreter generates machine code that can be directly executed by the machine that is running
the java program. We can say that java is both compiled and interpreted language.
ii) Platform Independent and Portable:
java is a platform independent and portable language. Java programs can be easily moved from
one computer system to another, anywhere and anytime. Changes and upgrades in operating
systems, processors and system resources will not force any changes in java programs.
Java ensures portability in two ways. First java compiler generates byte code instructions
that can be implemented on any machine. Secondly the sizes of the primitive data types are
machine independent.
iii) Object oriented:
Java is a true object-oriented language. Almost everything in java is
an object. All program code and data reside within objects and classes. The object model in java
is simple and easy to extend.
iv) Robust and Secure:
Java is a robust and secured language. It provides many safe guards
to ensure reliable code. It has strict compile time and run time checking for data types. It is designed
as a garbage-collected relieving the programmers virtually all memory management problems.
Java also incorporates the concept of exception handling mechanism which captures the
error and eliminated any risk of crashing the system.
Security becomes an important issues for a language that is used for programming on internet.
Threat of viruses and abuse of resources are everywhere. Java was provided the security from
viruses.
v) Distributed:
Java is designed as a distributed language for crating applications on networks. It has the ability to
share both data and programs. Java applications can open and access remote objects and internet
has easily in a local system. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
vi) Simple, Small and familiar:
Java is a small and simple language. Many features of c and c++ that are either redundant or
sources of unreliable code are not a part of java. For example java does not use pointers, pre-
processor header files, goto statement and many others. It also eliminates operator overloading
and multiple inheritance.
Familiarity is another striking feature of java. Java uses many constructs of c and c++ and
therefore java code is same as c++ code. In fact java is a simplified version of c++.

vii) Multi-threaded and interactive:


Multithreaded means handling multiple tasks are executed simultaneously. Java supports
multithreaded programs. This means the we need not wait for the application to finish one task
before beginning another. For example we can listen music at the same time typing the typing
master and download videos from the internet. These programs are executed simultaneously. This
feature greatly improves the interactive performance of graphical applications.
Java runtime comes with tools that support multi process synchronization and construct
smoothly running interactive systems.
viii) High Performance:
Java performance is impressive for an interpreted language, mainly due to the use of intermediate
byte code. According to sun, java speed is comparable to the native c/c++.
ix) Dynamic and Extensible:
Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods
and objects. Java can also determine the type of class through a query. Java programs support
functions written in other languages such as c and c++. These functions are known as native
methods.
x) JDBC Row Set:
Java supports JDBC (java data base connectivity) Row set to send data in a tabular format
between the remote components of a distributed enterprise applications. JDBC Row Set contains
cached row set and web row set objects. How java differs from c and c++:-
Java was modelled after c and c++ languages, it differs from c and c++ in many ways. Java does
not incorporate a number of features available in c and c++.
Java and c:
Java is a lot like „c‟ but the major difference between java and c is that Java is an
object-oriented language and has mechanism to define classes and objects
The java team did not include some of the „C‟ features in java.
➢ Java does not include the „c‟ unique statements keywords sizeof and typedef.
➢ Java does not contain the data types struct and union.
➢ Java does not define the type modifiers keywords auto, extern, register, signed and
unsigned.
➢ Java does not support an explicit pointer type.

➢ Java does not have a pre-processor and therefore we cannot use


“#include”,”#define” and “#ifdef” statements.
➢ Java requires that the functions with no arguments must be declared with empty
parenthesis.
➢ Java adds new operators such as instanceOf and >>>.
➢ Java adds labelled break and continue statements.
➢ Java adds many features required for object oriented programming.
Java and C++:
Java is a true object oriented programming language while c++ is basically c with object
oriented extension. That is exactly the increment operator ++ indicates. Java appears to be
similar to c++ when we consider only the extension part of c++.
Java team did not include some of the features in java.
➢ Java does not support operator overloading.
➢ Java does not have template classes as in c++.
➢ Java does not support multiple inheritances of classes. This is accomplished
using a new feature called “interface”.
➢ Java does not support global variables. Every variable and method is declared with
in a class.
➢ Java does not use pointers.
➢ Java has replaced the destructor function with a finalize() function.
➢ There are no header files in java
➢ Java also adds some new features while c++ is a superset of c, java is neither a
superset nor a subset of c or c++.
➢ Java may be considered as a first cousin of c++ and a second cousin of c as
illustrated in the below figure.

C++

java
c

Fig(a):Overlapping of c,c++ and Java.


Java Program:-
Java is a general purpose object oriented programming language. We can develop two types of
java programs.
❖ Standalone applications
❖ Web applets
Standalone applications are programs written in java to carry out certain tasks on a standalone local
computers.
Executing a standalone java program involves two steps.
❖ Compiling source code into byte code using javac compiler.
❖ Executing the byte code program using java interpreter.

Java
Source
code

Java
Compiler

Java Java
Enable Interprete

Output Outpu
t
Fig.a) Two ways of using java
Applets are small java programs developed for internet applications. An applet located on a distant
computer (server) can be downloaded via internet and executed on a local computer using java
enabled browser.
Standalone programs can read and write files and perform certain operations that applets cannot
do. An applet can only run with in a web browser.
Simple java program:-
The best way to learn a new language is to write a few simple example programs and execute
them. We begin with a many simple program that prints a line of text as output.
Example:-
class sampleone {
public static void main(String args[]) { System.out.println(“java is
better than c++”);
}
}
Class declaration:
The first line “class sampleone” declares a class which is an object oriented construct. As stated
earlier java is a true object oriented programming and therefore everything must be placed inside
a class. Class is a keyword and declares that a new class definition follows. Sampleone is a java
identifier that specifies the name of the class to be defined. A class name is same as the variable
name.
Opening Braces:
Every class definitions in java begins with an opening brace “{“ and ends with a matching closing
brace “}”. This is similar to c++ class construct.
The Main Line:
The third line
public static void main(String args[])
defines a method name main. Conceptually this is similar to the main() function in c and c++.
Every java application program must include the main method. This is the starting point for the
interpreter to begin the execution of the program. A java application can have many number of
classes but only one of them must include the main method.
Note: Java applets will not use the main method at all.
The main line contains a number of keywords public, static and void.
Public:
The keyword public is an access Specifier that declares the main method as unprotected and
therefore making it accessible to all other classes.
Static:
The main must always be declared as static since the interpreter uses this method before any
objects are created.
Void:
The type modifier void states that the main method does not return any value but simply prints
some text to the screen.
String args[]:
Here, String args[] declares a parameter named args, which contains an array of objects of the class
type String.
The Output Line:
The only executable statement in the program is
System.out.println(“java is better than c++.”);
This is similar to the printf() statement of c or cout<<construct of c++. Since java is a true object
oriented language, every method must be part of an object. The println() method is a member of
the out object, which is a static data member of System class. This line prints the string. Java is
better than c++.
Java program structure:-
A java program may contain many classes of which only one class defines a main
method. Classes contain data members and methods that operate on the data
members of the class. Methods may contain data type declarations and executable
statements. To write a, java program we first define classes and then put them
together. A java program may contain one or more sections as shown in the below
figure.
Documentation Section Suggested
Package Statement Optional
Import Statement Optional
Interface Statement Optional
Class Definition Optional

Main method class Essential


{
Main method Definition
}

Fig(a) General structure of a java program.


i)Documentation Section:
The documentation section comprises a set of comment lines giving the name of the program, the
author and other details which the programme would like to refer to at a later stage. Comments
must explain why and what of classes and how of algorithms. In addition to the two styles of
comments discussed earlier, java also uses a third style of comment /** */ known as
documentation comment. This form of comment is used for generating documentation
automatically.

ii) Package Statement:


The first statement allowed in a java file is a package statement. This statement declares a package
name and informs the compiler that the classes defined here belong to this package.
Example:-
Package student;
The package statement is optional i.e our classes do not have to be part of package.

iii) Import Statement:


The next thing after a package statement may be a number of import statements. This is similar to
the “#include” statements in c.
Example:-
import Student.Test;
This statement instructs the interpreter to load the test class contained in the package student. Using
import statement, we can have access to classes that are part of other named package.
iv) Interface statement:
An interface like a class but includes a group of method declarations. This is also an optional section
and is used only when we wish to implement the multiple inheritance feature in the program.
Interface is a new concept in java.
v) Class Definition:
A java program may contain multiple class definitions. Classes are the primary and essential
elements of a java program. These are used to map the objects of real world problems.
vi) Main method class:
Since every standalone java program requires a main method as its starting point, this class is the
essential part of a java program. A simple java program may contain only this part.
The main method creates objects of various classes and establishing communication between them.
On reaching the end of main, the program terminates and the control passes back to the operating
system.

Java Tokens:-
A java program is basically a collection of classes. A class is defined as a set of declaration
statements and methods containing executable statements. Most statements contain expressions
which describes the actions carried out on data. The smallest individual units in a program are
known as tokens. The compiler recognizes them for building up expressions and statements.
Tokens
Variable Section

Declaration
Statement

Method1 Tokens Method Section

Expressions
& statements

Tokens
Method2

Fig(a) Elements of java class.


In simple terms, a java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens. They are
i) Reserved keywords
ii) Identifiers
iii) Literal
iv) Operators
v) Separators
i) Reserved keywords:
Keywords are the reserved words by the java compiler. Keywords are an essential part of a
language definition. They implement specific features of the language. Java language has reserved
50 words as keywords. Since keywords have specific meaning in java. We cannot use them as
names for variables, classes, methods and
so on. All keywords are to be written in lower case letters. Since java is a case sensitive.
Java keywords
abstract continue for new switch
assert default goto package synchronization
boolean do if private this
break double implements protected throw byte
else interface public throws
case enum import return transient
catch extends instanceof short try
char final int static void
class finally long strictfp volatile
const float native super while
ii)Identifiers:
Identifiers are the programmer designed tokens. Identifiers are the names of classes, methods,
variables, objects, labels, packages and interfaces in a program.
Java identifiers follow the following rules:
1) They can have alphabets, digits, underscore and dollar sign characters.
2) They must not begin with a digit
3) Upper and lower case letters are distinct.
4) They can be of any length
5) Identifiers must be meaningful, short enough to be quickly and easily typed. for example:
sum, average, Total Marks etc.
iii) Literals:
Literals in java are a sequence of characters (digits, letters and other characters) that
represents constant values to be stored in variables.
Java language specifies five major types of literals. They are
a) Integer Literals
b) Floating point literals
c) Character literals
d) String literals
e) Boolean literals
iv) Operators:
An operator is a symbol that takes one or more arguments and operates on
them to produce a result.
v) Separators:
separators are symbols used to indicate where groups of code are divided and
arranged. They basically define the shape and function of our code.
Java separators:-
Parenthesis () →used to create the method
Braces {} → used to define scope of methods, classes and
local variables.
Brackets [] → used to define an array
Semicolon; → Terminates a statement
Comma, → Used to separate variables
Period. → Used to separate package names from sub
packages and classes.
Implementing a java program:-
Implementation of a java application program involves a series of steps. They are
i) Creating the program
ii) Compiling the program
iii) Running the program
i) Creating the program:-
When we create a program using any text editor. Assume that we have entered the following
program.
Class test
{
Public static void main(String k[])
{
System.out.println(“java is better than c++”);
}
}
We must save this program in a file called test.java. Ensuring that the file name contains the class
name properly. This file is called the source file.
Note:- Java source files will have the extension .java.
ii) Compiling the program:-
To compile the program, we must run the java compiler „java‟ with the name of the source file on that
command line as shown below.
Javac test.java
If everything is ok, the javac compiler creates a file called „test.class‟ containing the byte code of the
program.
iii) Running the program:-
We need to use the java interpreter to run a standalone program. At the command prompt type „java
test‟. Now the interpreter looks for the main method in the program and begins execution from
here. When executed our program displays the following

Java is better than c++.


Source code

Java Compiler

Byte code

Windows ABC Macintosh


Interpreter Interpreter Interpreter

Machine Machine Machine


Code Code Code

Windows Windows Windows


Computer Computer Computer

Fig(a) Implementation of a java program.


The compiler converts the source code files into byte code files. These codes are machine
independent and therefore can be run on any machine.
Java interpreter reads the byte code files and translates them into machine for the specific machine
on which the java program is running.
Java virtual machine (JVM)?
All language compilers translate source code files into machine code for a specific computer. Java
compiler also does the same thing. Java compiler produces an intermediate code known as byte code
for a machine that does not exist. This machine is called as the java virtual machine and it exists only
inside the computer memory. It is simulated computer within the computer and does all major
functions of a real computer. The process of compiling a java program into byte code which is also
referred to as virtual machine code.

Java program Java Compiler Virtual Machine


Source Code Byte Code
Fig(a):Process of Compilation.
The virtual machine code is not machine specific. The machine specific code known as machine code
is generated by the java interpreter by acting as an intermediary between the virtual machine and the
real machine as shown in below figure.
Byte Code Java Interpreter Machine Code
Virtual Machine Real Machine
Fig(b):Process of converting byte code into Machine code.
From the below figure how java works on typical computer. The java object frame work acts as
the intermediary between the user programs and the virtual machine which in terms acts as the
intermediary between the operating system and the java object frame work.

Operating System

Java Virtual Machine

Java Object Frame Work(API)

Compiler Interpreter

User Application Program

Use
r
Fig(c): Layers of Interaction for java program.
Constants in Java:-Constants in java refers to fixed value that does not change during the
execution of a java program. Java supports several types of constants as shown in the below figure.

Java Constants

Numerical Constants Character Constants

Integer Real(float) Character String


Constants Constants Constants Constants
Fig(a):Java Constants
Integer constant:-
An integer constant refers to a sequence of digits. There are three types of integer constants
namely
❖ Decimal integer
❖ Octal integer
❖ Hexadecimal Integer
Decimal integer Constants:-
Decimal Integer constants are the sequence of digits from 0 to 9 without decimal, fractional and
other symbols. Integer constants may be positive or negative. The default assume as the positive.
For example
123, 125, 156,-25 etc.
Octal Integer Constants:-
An Octal Integer constant are the sequence of digits from 0 to 7. Octal Integer constants always
start with 0. The example of valid integer constants in octal notation are 024, 0576, 0123,etc.
Hexadecimal Integer constants:-
Hexadecimal integer constants consist of digits 0 to 9 and alphabets “a” to “f” or “A” to “F”. These
constants are preceded by 0x or 0X. Letter “A” to “F” represents the numbers 10 to 15.
The valid examples of hexadecimal integer constants are 0x23, 0X5B, 0x9F,etc.
Real constants:-
Integer constants are unfit to represents the many quantities. Such as distance, height, temperature,
prices and so on. These quantities are represented by numbers containing fractional parts like
163.163 such numbers are called real or floating point constants.
Example of real constants is 163.1632, -361.361, 0.163.
A real number may also be expressed in exponential notation. For example the value 163.163 may
be written as 1.63163e2 in exponential notation, e3 means multiply by 103.
The general form is :

Mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is
an integer with an optional plus or minus sign.
Single character constants:-
A character, number and symbol are enclosed within a single quotation marks are known as single
character constant.
Examples of single character constants are „G‟,‟K‟,‟1‟,‟6‟,‟;‟,‟@‟,etc.
String constants:-
A group of characters are enclosed within a double quotation marks are known as the string
constant.
Examples of string constants are “suresh”,”163”,”INDIA”,etc.
Backslash character constants:-
Java supports some special backslash character constants that are used in output methods. For
example the symbol „\n‟ stands for new line character. A list of such back slash character
constants is given in below table.

Constants Meaning

‘\b’ back space

‘\f’ form feed

‘\n’ newline

‘\r’ carriage return

‘\t’ horizontal tab

‘\’’ single quote

‘\”’ double quote

‘\\’ backslash

Data types in java:-


Every variable in java has a data type. Data type specifies the size and type of values that can be
stored. Java language is rich in its data types. This enables the programmer to select appropriate
data as per the need of the application program. Data types in java are mainly classified into two
types.
i) Primitive data type
ii) Non-primitive data types
Primitive data types are the built in types. They are integer, floating point, character and
Boolean.
Non-primitive data types are the reference types. We are discussing only primitive data types.
Data types in java under various categories as shown in the below figure.

Data Types in Java

Primitive Non-Primitive

Numeric Non-Numeric Class Arrays

Integer Floating Point Character Boolean Interface

Fig(a): Data Types in java


Integer data types:-
Integer data types can hold whole numbers such as 123, -19, and 5639. The size of the values that
can be stored depends on the integer data types. Java supports four types of integer data types.
They are byte, short, int and long as shown in the below figure.
Integer

byte short int long

Fig(b):Integer Data types


Java does not support the concept of unsigned types and therefore all java values are signed i.e
they can be positive or negative.
Integer data types of the memory size and range of all the 4 integers as shown in the below table.
Size and range of integer types
Type Size Minimum Value Maximum value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes -2,147,483,648 -2,147,483,647
long 8 bytes - 9,223,372,036,854,775,80
9,223,372,036,854,775,808 7
We can make integers long by appending the letter L or l at the end of the number.
For Example 163L or 163l.
Floating point data type:-
Integer types can hold only whole numbers and therefore we use another type known as floating
point type. Floating point types can hold numbers containing fractional parts such as 163.163 and
-0.4321.
Floating point types are two types in java. They are namely float and double as shown in the below
figure.

Floating point

float double

Fig(c):Floating point Data type


The float type values are single precision numbers while the double type represents double
precision numbers. Floating point numbers are treated as double precision quantities. To force
them to be in single precision mode we must append f or F. Example: 16.3f or 16.3F
Double precision types are used when we need greater precision of floating point numbers. All
mathematical functions such as sin, cos and sqrt return double type values. The size and range of
floating point types as shown in the below table.
Size and range of floating point types
Type size Minimum value Maximum value
float 4 bytes 3.4e-038 3.4e+038
double 8 bytes 1.7e-308 1.7e+308

Character data type:-


In order to store character constants in memory , java provides a character data type called
“char”. The character type assumes a size of two bytes but basically, it can hold only a single
character.
Example: char c=‟A‟;
Boolean data type:-
Boolean type is used when we want to test a particular condition during the execution of the
program. There only two values that a Boolean type can take true or false. Boolean type is denoted
by the keyword “Boolean” and use only one bit of storage.
Variable:-
A variable is an identifier that denotes a storage location used to store data values. A variable
may take different values at different times during the execution of the program. A variable name
can be chosen by the programmer in a meaningful way. Some examples of variable names are
Average, height, Total-Marks student-name etc.
A variable name may consists of alphabets, digits, the underscore and dollar sign($).
Rules for defining a variable is as follows
❖ They must not begin with a digit
❖ Upper and lower cases are distinct. i.e the variable „TOTAL‟ is not the same as
„total‟.
❖ It should not be a keyword.
❖ White spaces are not allowed.
❖ Variable names can be of any length.
Declaration of variables:-
In java, variables are the names of storage locations. After designing suitable variable
names, we must declare them to the compiler.
Declaration denotes three things:
➢ It tells the compiler what the variable name is.
➢ It specifies what type of data, the variable will hold.
➢ The place of declaration decides the scope of the variables.
A variable must be declared before it is used in the program. The general form of declaration of a
variable is:
Type variable1, variable2, variable3, ............................................................ variableN

Variables are separated by commas. A declaration statement must end with a semicolon (;).
Some valid declarations are: int
count;
float x,y;
double pi;
byte b;
char c1,c2,c3;

Giving values of variables:-


A variable must be given a value after it has been declared but before it is used in an expression.
Giving values to a variable in two ways.
1. By using an assignment statement
2. By using a read statement
Assignment statement:-
A simple method of giving value to a variable is through the assignment statement as follows.
Variable Name=value;
For example:-

Length=3;
Height=5;
Gender=‟F‟;
We can also string assignment expression as shown below.
X=Y=Z=6;
It is also possible to assign a value to its variable at the time of its declaration. This takes
the form.

Data type variable name=value;

For example:
int a=6; long
L=500;
float bc=0.52; char
gender=‟F‟;
The process of giving initial values to variables is known as the initialization.
//demonstrate for variable initialization import java.io.*;
class assignment
{
public static void main(String k[])
{
byte b=10; //variable initialization short s=125;
int i=100;
long l=12345L; float f=12.56F;
double d=12.56;
System.out.println(“Varible initialization is:”);
System.out.println(“b:”+b+”s:”+s+”i:”+i+”l:”+l+”f:”+f+”d:”+d);
Read Statement:-
We may also give values to variables interactively through the keyboard using the “nextType()”
method.
//demonstrate for giving the values to variable from the keyboard.
import java.io.*;
import java.util.Scanner; class keyboard
{
public static void main(String k[])
{
Scanner obj=new Scanner(System.in);
byte b; //variable declaration
short s;
int i;
long l;
float f;
double d;
System.out.println(“Enter byte value:”);
b=obj.nextByte();
System.out.println(“Enter short value:”);
s=obj.nextShort();
System.out.println(“Enter int value:”);
i=obj.nextInt();
System.out.println(“Enter Long value:”);
l=obj.nextLong();
System.out.println(“Enter Float value:”);
f=obj.nextFloat();
System.out.println(“Enter Double value:”);
d=obj.nextDouble();
System.out.println(“b:”+b+”s:”+s+”i:”+i+”l:”+l+”f:”+f+”d:”+d);
}
}

Java Variables:-
Variable is name of reserved area allocated in memory. The value of a variable can change its
value in the execution time. Java variables are classified into three types:
1. Local Variables: A variable which is declared inside the method is called local variable.
2. Class Variables (Static Variables): Class variables also known as static variables are
declared with the static keyword in a class, but outside a method, constructor or a block.
3. Instance Variables (Non-static Variables): A variable which is declared inside the class but
outside the method, is called instance variable. It is not declared as static.
Symbolic Constants:-
We often use certain unique constants in a program. These constants may appear repeatedly in a
number of places in the program. One example of such constant is 3.142, representing the
mathematical value of the constant “pi”. Another example is the total number of students whose
mark sheets are analyzed by a test analysis program. The number of students says 50 may be used
for calculating the class total, class average, standard deviation etc.
A symbolic constant is declared as follows:

final type symbolicname=value;

Valid examples for symbolic constants


final int STRENGTH=100; final
int PASS_MARKS=50; final float
PI=3.14159;
Note:-
1. Symbolic names is same as the variable names but they are written in capital letters only.
2. They cannot be declared inside a method. They should be used only as class data members in
the beginning of the class.

Type Casting:-
To convert the one type variable into another type of variable is called as type casting. We often
encountered situations where there is a need to store a value of one type into a variable of another
type.
In such situations we must cast the value to be stored by proceeding it with the type name in
parenthesis.
Java supports the two types of casting. They are
i) implicit or automatic or narrowing type casting
ii) explicit or winding type casting
i) implicit or automatic or narrowing type casting:-
To convert the small type into largest type is called as implicit or automatic or narrowing type
casting. Java does the conversion of the assigned value automatically this is known as automatic
type conversion. Automatic type conversion is possible only if the destination type has enough
precision to store the source value.
For example „int‟ is large enough to hold a byte value.
byte b=100;
int i=b; //automatic type conversion long
l=i;
float f=l;
double d=f;
ii) Explicit or winding type casting:-
To convert largest type into smallest type is called as Explicit or winding type casting.
The syntax is:
type variable1=(type)variable2;

The process of converting one data type to another data type is called as type casting.
Example:-
double d=100.501;
float f=(float)d;
long l=(long)f;
int i=(int)l;
byte b=(int)i;
Casting into a smaller type may result in a loss of data.
The below table shows which are guarantee to result in no loss of information.
Casts those results in no loss of information:-
From To
byte short, char, int, long, float, double.
Short int, long, float,double.
Char int, long, float,double
int long, float, double
long float,double
float double

//demonstrate for typecasting

import java.io.*;
class typecasting{
public static void main(String
k[]){ byte b=75;
int a=b; //automatic type casting
double d=100.501;
float f=(float)d; short
s=(short)f;
System.out.println(“b:”+b+””+”a:”+a+””+”d:”+d+””+”f:”+f+””+”s:”+s);
}}
Q7) Explain getting values of variables?
A computer program is written to manipulate a given set of data and to display or print the results.
Java supports two output methods that can be used to send the results on the screen.
* Print() method // print and wait
* Println() method //print a line and move to next line.
The print() method sends information into a buffer. This buffer is not flushed until a new line
character is sent. The print() method prints output on one line until a new line character is
encounter able.
For example the statements
System.out.print(“hello”);
System.out.print(“java!”);
Will display the words hellojava! On one line and waits for displaying further information
on the same line.
The println() method takes the information provided and displays it on a line followed by a
line feed.
This means that the statements
System.out.println(“hello”);
System.out.println(“java”);
Will produce the following output Hello
Java!
Operators and Expressions
An operator is a symbol that tells to the computer to perform mathematical or logical
expressions.
An operator is a symbol that is used for to operate the two operands. For example we can take an
expression a+b.
Where „a‟ and „b‟ are the two operands And „+‟ is
an operator.
Java is a rich set in operators. Java supports a various types of operators. They are
i) Arithmetical operators
ii) Relational operators
iii) Logical operators
iv) Bitwise operators
v) Assignment operators
vi) Increment and decrement operators
vii) Conditional operator
viii) Special operators
i) Arithmetical operators:-
Arithmetical operators to perform the arithmetical calculations such as addition, subtraction,
multiplication, division and modulo division.
Arithmetical operators are the +,-,*,/ and %. The below table explains the arithmetical operators.

Operator meaning Description Result

+ Addition 10+20 30
_ Subtraction 20-10 10
* Multiplication 10*20 200
/ Division 10/2 5
% Modulo Division 10%2 0
Note:-
The division operator(/) returns the quotient value and modulo division returns the
remainder value.
Arithmetical operators are the three types namely
a) Integer arithmetic
b) Real arithmetic
c) Mixed mode arithmetic
Integer arithmetic operators both operands are the integer values. The result will produce is an
integer value.
Example:- 12+13;
Real arithmetic operators are the both operands are floating point values. The result will produce on
real values.
Example:- 14.13+0.23;
Mixed mode arithmetic operators are the one value is integer and another one is the real value the
result will produce real value.
Example:- 9.1+46;
//demonstrate for arithmetical operators
class arithmetical
{
int a=10+20;
int b=15-10;
int c=a*b;
doule d=12.50;
double e=d+c;
int f=a/b;
int g=a%b;
System.out.println(“a=”+a);
System.out.println(“b=”+b);
System.out.println(“c=”+c);
System.out.println(“d=”+d);
System.out.println(“e=”+e);
System.out.println(“f=”+f);
System.out.println(“g=”+g);
}
}
ii) Relational Operators:-
Relational operators compare the two values depending on their relationship. If their relationship
is true then the return value is „true‟. If their relationship is false then the return value is „false‟. The
relational operators are <,>,<=,>=,== and !=. The below table explains the relational operators.

Operator Meaning Description Result


< Less than 10<20 1
> Greater than 10>20 0
<= Less than or equal to 10<=20 1
>= Greater than or equal to 10>=20 0
== Equal to 10==20 0
!= Not equal to 10! =20 1

Relational operators is most powerful to implement a logical conditions are checked.


//demonstrate for relational operators
class relational
{
public static void main(String k[])
{
int a=10,b=20; System.out.println(“Relational operators:-“);
System.out.println(“Less than=“+(a<b));
System.out.println(“Greater than=“+(a>b));
System.out.println(“Less than or equal to=“+(a<=b));
System.out.println(“Greater than or equal to=“+(a>=b));
System.out.println(“Equal to=”+(a==b));
System.out.println(“Not equal to=“+(a!=b));
}
}
iii) Logical operators:-
The logical operators check the two expressions. If their expression is true then the return value is one.
If their expression is false then the return value is zero. The logical operators are &&,|| and !.
The below table explains the logical operators.

Operator Meaning Description Result


&& Logical AND (10<20)&&(10<30) 1

|| Logical OR (10<20)||(10>30) 1

! Logical NOT !(10<20) 0

The logical Boolean operators &&,|| are used when we want to combine two or more relations.
The logical ! operator inverts the Boolean state: ! true= false and ! false=true. The following
table shows the effect of each logical operation.

A B A&&B A||B

T T T T

T F F T

F T F T

F F F F
The logical AND (&&) operator returns the true when both expressions are true, otherwise false.
The logical OR (||) operator returns the false when both expressions are false, otherwise true.
The logical NOT (!) operator is reverse the given expression.
//demonstrate for the logical operators
class logical
{
public static void main(String k[])
{
int a=10,b=20,c=30;
System.out.println(“The Logical Operators are:”);
System.out.println(“Logical AND=”+(a<b)&&(a<c));
System.out.println(“Logical OR=”+(a<b)||(a>c));
System.out.println(“Logical AND=”+(!(a<b)));
}
}
iv) Bitwise Operators:-
The bitwise operators to manipulate the data in a bit level. Java defines several bitwise
operators which can be applied to the integer types long, int, short, char and byte.
These operators act upon the individual bits of their operands.

The below table explains the bitwise operators.

Operator Meaning

~ Bitwise Unary NOT


& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Bitwise Left shift
>> Bitwise Right Shift
>>> Shift right zero file

//demonstrate for bitwise operators class


bitwise
{
public static void main(String k[])
{
int x=2,y=3;
int a=2,b=8;
int l,r;
l=(a<<2); //left shift
r=(b>>2);//right shift
System.out.println(“Bitwise operators:”);
System.out.println(“Bitwise AND:”+(x&y));
System.out.println(“Bitwise OR:”+(x|y));
System.out.println(“Bitwise Exclusive OR:”+(x^y));
System.out.println(“Bitwise Unary NOT:”+(~x));
System.out.println(“Left shift:”+l);
System.out.println(“Right shift :”+r);
}
}
v) Assignment operators:-
The assignment operator is the single equal sign, =. The assignment operator works in java much
as it does in any other computer languages. Java provides special operators that can be used to
combine arithmetic operation with an assignment.
It has the general form:-
Variable=expression; a= a+4;

In java we can rewrite this statement as shown here.


a+=4;
//demonstrate several assignment operators
class assignment
{
public static void main(String k[])
{
int a=1,b=2,c=3;
a+=5;
b*=4;
c+=a*b
;
c%=6;
System.out.println(“a:”+a+””+”b:”+b+””+”c:”+c);
}
}
vi) Increment/Decrement operators:-
The „++‟ and „--„ are java‟s increment and decrement operators. The increment operator increases its
operand by one. The decrement operator decreases its operand by one.
For example an expression x=x+1; can be written like this by use of the increment operator x++;
Similarly x=x-1; statement is equivalent to x--;
These operators are unique in that they appear both in postfix form where they preceded the
operand there is no difference between the prefix and postfix forms. For example x=42;
y=++x;
y is said to 43 as you expect because the increment occurs before x is assigned to y
//demonstrate for increment and decrement operators
class increment
{
public static void main(String k[])
{
int x=10,y=20,z;
x+
+;
y--;
z=x*y; System.out.println(“x=”+x+””+”y=”+y+””+”z=”+z);
}
}

vii) conditional or Ternary operator:-


Java includes a special ternary operator that can replace certain types of if then else
statements. This operator is the? And it works in java much like it does in c and c++.
The general form is:
(Condition) ?Expression1:Expression2;
Condition is any relational expression that evaluates to a Boolean value. If a condition is true
then the expression1 will be executed. If a condition is false then the expression2 will be
executed.
//demonstrate for conditional operator
class conditional
{
public static void main(String k[])
{
int a=10,b=30,c=25;
int big; big=(a>b)&&(a>c)?a:(b>c)?b:c;
System.out.println(“big=”+big);
}
}
viii) Special operators:-
Java supports the some special operators like member selection (or) dot operator (.) and
„instanceOf‟ operator.
The „instanceOf‟ is an object reference operator and returns true if the object in the left hand side is
an instance of that class given on the right hand side.
For example:- person p;
The dot (.) operator is used to access the „instanceOf‟ the variables and methods of class objects.
For example:- person p;
p.age; //reference to variable
p.salary(); //reference to the method salary.
Precedence rules and Associativity:
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator. For example, x = 7 + 3
* 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets
multiplied with 3 * 2 and then adds into 7.

In the following table, operators with the highest precedence appear at the top of the table;
those with the lowest appear at the bottom. Within an expression, higher precedence operators will
be evaluated first.

Category Operator Associativity

Postfix ➢ () [] . (dot operator) Left to right

Unary ➢ ++ - - ! ~ Right to left

Multiplicative ➢ */ Left to right

Additive ➢ +- Left to right


Shift ➢ >> >>> << Left to right

Relational ➢ > >= < <= Left to right

Equality ➢ == != Left to right

Bitwise AND ➢ & Left to right

Bitwise XOR ➢ ^ Left to right

Bitwise OR ➢ | Left to right

Logical AND ➢ && Left to right


Logical OR ➢ || Left to right

Conditional ?: Right to left

= += -= *= /= %= >>= <<= &= ^=


Assignment |= Right to left

Flow of control- Branching, Conditional, loops:


Decision Statement:-
When a program breaks the sequential flow and jumps to another part of the code it is called
branching. When the branching is based on a particular condition. It is known as conditional
branching. Java language possesses such decision making capabilities and supports the following
statement knows as control or decision making statements. They are
i) If statement
ii) Switch statement
Decision making with if statement :-
The if statement is a powerful decision making statement and is used to control the flow of
execution of statement. The if statement may be implemented in different forms. Depending on
the complexity of conditions to be tested. They are
➢ Simple if statement
➢ If else statement
➢ Nested if else statement
➢ Else if ladder statement
Simple if statement:-
• The simple if statement is a one way decision statement and is used to check the condition.
• The general from of a simple if statement is If (test
expression)
{
Statement - block;
}
Statement – x;
• The statement block may be a single statement or group of statements.
• If the test expression is true then the statement- block will be executed. Otherwise the
statement – block will be skipped and the execution will jump to the statement – x
• It should be remembered that when the condition is true, both the statement block and the
statement-x are executed in the sequence
• The below diagram explains the simple if statement

Entry

Test True
Condition

False
Statement-block

Statement-X

Fig (a) flow chart of simple if statement


//Demonstrate simple if statement
class simpleif
{
public static void main(String k[ ])
{
int x=1;
if(x<=10)
{
System.out.println(“x=”+x);
}
}
}
If-else statement:-
• The if else statement is an extension of the simple if – statement
• The if-else statement is a two way decision statement and is used in conjunction
with an expression. It takes the following form:
if (test expression)
{
True-block statements(s);
}
else
{
false-block statements(s);
}
Statement-x;

• If the test expression is true then the true block statement is executed. Otherwise
the false block statements are executed.
• In either case, either true block or false block will be executed, not both.
• In both the cases the control is transferred subsequently to the statement-x,
• The below diagram explains the if - else statement.

Entry

True Test False


Condition

True block statement False block statement

Statement-X

Fig(b): flow chart of if else statement


• For example if else statement counts the even and odd numbers in a list of numbers
//demonstrate if else statement to determine even or odd number import
java.io.*;
import java.util.Scanner
class ifelsetest
{
public static void main (string args [ ])
{
Scanner s=new Scanner(System.in);
int num; num=s.nextInt();
if(num%2==0)
{
System. out.println(“The Given Number is Even” );
}
else
{
System.out.println(“The Given Number is Odd”);
}
}
}
Nested if else Statement:-
If statement contains another if is called as nested if else statement. In the nested if else contains
one or more conditions are checked. The below form shows the nested if else statement:

if(testcondition-1)
{
if(testcondition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-X

If a test condition-1 is false then the statement-3 will be executed otherwise it continues to
perform second test.If condition-2 is true then the statement-1 will be executed otherwise
the statement-2 will be executed and then the control is transferred to the statement-x.
• The below diagram explains the nested if-else statement
Entry

False True
Test
Condition-1?

False True
Test
Statement-3 Condition-2?

Statement-2 Statement-1

Statement-X

Fig(c): flow chart for nested if else statement.


//demonstrate nested if else class
nestedifelse{
public static void main(String k[])
{
int a=321,b=712,c=478;
System.out.println(“Largest value”);
if (a>b)
{
if (a>c)
{
System.out.println(a);
}
else
{
System . out. println(c);
}
}
else
{
If(b>c)
{
System.out.println(b);
}
else
{
System . out.println(c);
}
}
}
Else if ladder Statement:-
The else if ladder statement is used to check a multiple logical conditions .A multiple decision is
a chain of ifs m which the statement associated with each else is an if. It takes the following form

if (condition1)
{
Statement-1;
}
else if(condition2)
{
Statement-2;
}
else if (condition 3)
{
Statement-3;
}
else if (condition n)
{
Statement-n;
}
else
{
default –statement;
}
Statement - x;

This construct is known as the else if ladder. The conditions are evaluated from the top down
words.
• As soon as the true conditions are found, the statement associated with it is executed and
the control is transferred to the statement – x.
• When all the n-conditions become false then the final else containing default statement
will be executed.
• The below figure shows the logic of execution of else – if ladder statement.

F
Con
-
1
T F
Con
-
Statement-1 2

Statement-2 T Con F
-
3
Statement-
3 T F
Con
-
n
Statement-n Default-
statement

Statement-x

//demonstrate else if ladder. Statement class


elseifladder{
public static void main(string args[]){ char
ch=‟o‟;
if(ch==‟a‟||ch==‟A‟)
{
System.out.println(“Your character is Vowel:”+ch);
}
else if(ch==‟e‟||ch==‟E‟)
{
System.out.println(“Your character is Vowel:”+ch);
}
else if(ch==‟i‟||ch==‟I‟)
{
System.out.println(“Your character is Vowel:”+ch);
}
else if(ch==‟o‟||ch==‟O‟)
{
System.out.println(“Your character is Vowel:”+ch);
}
else if(ch==‟u‟||ch==‟U‟)
{
System.out.println(“Your character is Vowel:”+ch);
}
else
{
System.out.println(“Your character is Consonant:”+ch);
}
}
}
Switch statement:-Java has a built in multi way decision statement known as switch. The
switch statement tests the value of a given variable against a list of case of values when a match
is found a block of statements associated with that case is executed. The general form of the switch
statement is as shown below.
switch(expression)
{
case value-1:
Block-1;
break;
case value-2:
Block-2;
break;
default
default-block;
break;
}Statement - x ;
The expression is an integer expression or characters. The value1, value 2 are constant or
expressions and are known as case labels each of these values should be unique in switch
statement.
• The block 1, block 2 are statement lists and may contain zero or more statements.
• There is no need to put braces around these blocks but it is important to note that code
labels end with a colon (:)
• When the switch is executed, the value of the expression is evaluated and compared against
that values value 1, value 2 and so on. If a case is found whose values matches with the
value of the expression then the block of statements that follows the case are executed.
• The breaks statement at the end of each block signals, the end of particular case and causes
an exit from the switch statement, transferring the control to the statement
• The default is an optional case when present it will be executed if all case values are
unmatched.
• The selection process of switch statement is illustrated in the flow chart as shown in the
below figure.

Entry

Switch
Expressio
n

Expression=Value1 Block-1

Expression=Value2 Block-2

(No Match) default Default block

Statement-X

//demonstrate switch statement import


java.io.*;
import java.util.Scanner;
class value{
public static void main (string args[]){
Scanner s=new Scanner(System.in); int
num;
System.out.println(“Enter any number from 0-9”);
num=s.nextInt();
Switch(num)
{
case 0:
System.out.println(“ Zero”);
break;
case 1:
System.out.println(“One”);
break;
Case 2 :
System.out.println(“Two”);
break;
case 3 :
System .out.println(“Three”);
break;
case 4:
System .out.println(“Four”);
break;
case 5:
System .out.println(“Five”);
break;
case 6:
System .out.println(“Six”);
break;
case 7:
System .out.println(“Seven”);
break;
case 8:
System .out.println(“Eight”);
break;
case 9:
System .out.println(“Nine”);
break;
default:
System out println (“ Invalid Digit”);
}
}}
Looping Control Statements in Java:-
A loop is defined as a block of statements which are repeatedly executed until the certain
condition is satisfied.
• The statements in the block may be executed any number of times, from zero to infinite
number.
• If a loop continues forever, it is called an infinite loop.
• Java supports such looping features which enables us to develop consists programs
containing repetitive process, without using unconditional branching statements.
• In general there are two types of loops are available.
They are
o Entry controlled loop
o Exit controlled loop
• The entry controlled loop verifies the condition first and exit controlled loop verifies the
condition at the end of the execution
• They can be represented as below.

Entry

False Body of Loop


Test
Conditi
o
True
Test True
Body of Loop Conditio
n

False
Fig(a) Entry Controlled Loop Fig(b) Exit Controlled Loop.
• A looping process in general would include the following three steps.
i. Initializing the variables
ii. Test the condition for execution
iii. Increment or decrement
• The java language provides for three constructs for performing loop operations.
They are
➢ While loop
➢ Do-while loop
➢ For-loop
While loop:-
• The while loop is an entry controlled loop statement.
• The while loop is java most fundamental looping statement.
• It repeats a statements or block while its controlling expression is true
• The general form of while is
Initialization;
While (test condition)
{
Body of the loop
}
• The condition may be any Boolean expression. The body of the loop will be executed as
long as the condition expression is true.
• When the condition becomes false then the control exit from the loop and control passes
to the next line of code immediately following the loop
• The body of the loop may have one or more statements. The brasses are needed only
if the body contains two or more statements.
• The flow chart explains the while loop.
Initialization

Test False
Condition

True
Body of the Loop

Incr/Decr

Fig (a) process of while loop construct


//demonstrate while loop
import java.io.*;
class while loop
{
public static void main (String k[ ])
{
int n=10; // initialization while(n>0)
// test condition
{
System.out.println(“tick:”+n); //body of loop
n--; //updation
}
}
}
Do-while:-
A do-while loop is an exit control loop. If the conditional expression controlling a while loop is
initially false, then the body of the loop will not be executed at all.
• However sometimes is must to execute the body of a while loop at least once, even if
the conditional expression is false to begin with
• The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop
• The condition must be a Boolean expression
• The general from of the do – while Initialization;
do
{
Body of the loops;
}while(test condition);
• On reaching the do statement, the program precedes to evaluate the body of the loop first.
• At the end of the loop, the test condition in the while statement is evaluated.
• If the condition is true, the program continues to evaluate the body of the loop once
again.
• This process continues as long as the condition is true
• When the condition becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the while statement.
• Since the test condition is evaluated at the bottom of the loop, the do-while constructs
provides an exit controlled loop and therefore the body of the loop is always executed at
least once.

Initialization

Body of the Loop

True Test
Condition
?

False

Exit
Process of do-while loop construct
//demonstrate do while
class dowhile
{

public static void main (String k[ ])


{
int x=10; //initialization

do
{
System.out.println (“x=”+x); //body of the loop x--;
}
}
}
For loop:-
• For loop is another entry controlled loop that provides a more consist loop control
structure.
• For loop provides specific locations to contain an initialization statement, test condition
and an increase / decrease statement in a single line.
• So this loop is specially designed to perform a repetitive action. With a counter which
is initialized and increased on each iteration.
• The general form of the for loop is
for ( initialization; test condition; increment/decrement)
{
Body of the loop;
}
• The execution of the for statement is as follows :
→Initialization of the control variables is done first, using the assignment statement such
as i=1 and count=0.
The variables I & count are known as loop control variables
→The value of the control variable is tested using the test condition. The test condition is a
relational expression such as i<10 that determines ------------------------------------ loop will exit.
If the condition is true the body of the loop is executed otherwise the loop is terminated
and execution continues with the statement that immediately follows the loop
→When the body of the loop is executed, the control is transferred to the for statement after
revaluating to the last statement in the loop. Now the control variable is incremented using an
assignment statement such as i=i+1; and the new value of the control variable is again tested, if the
condition is satisfied, the body of the loop will again executed.
→This process continues till the value of the control fails to satisfy the test condition.
Initialization

Test
False
Conditio
n?

True
Body of the loop

Increment/Decrement

Exit
//demonstrate for loop
import java.io.*;
class for loop
{
public static void main ( String k[ ])
{
int sum=0;
for (int i=0; i<10; i++)
{
System.out.println (“i:”+i);
sum=sum+i;
}
System.out.println (“sum:”+sum);
}
}
Nested – for loop:-
• Java supports the nested for loop. A loop contains another for loop is called as the nested
for loop i.e., one for statement with in another for statement is called in java.
• We have used this concept similarly for loops. The general form of the nested for loop is
for(int i=0; i<10; i++)
{
for(int j=0; j<5; j++)
{
Body of the loop; inner for loop Outer for Loop
}

}
• In the nested for loop the counter variable or the outer for loop is checked. It the condition
is true, and then the inner for loop is executed.
• The inner for loop is executed until the certain condition is satisfied. If a condition false
then control back to the outer or statement.
• In the outer for loop the value is updated and checks the test condition. If a condition is
true, then the inner for loop is executed. This process is repeatedly as long as test condition
is true of the outer for loop. Otherwise the outer for loop is an exit.
• Example for the nested for loop
import java.io.*;
class nested{
public static void main (String k[]){ for(int
i=0; i<10; i++)
{
System.out.println(“i:”+i); for
(int j=0; j<=i, j++)
{
System.out.println(“j:”+j);
}
}
}}
Enhanced for loop:-
The enhanced for loop is also called for each loop.
• The enhanced for loop is an extended feature introduced with the J2SE 5.0 release
• This feature helps us to retrieve the array of elements efficiently rather than using array
indexed.
• They can also use this feature to eliminate the iterators in a for loop and to retrieve the
elements for a collection
• The enhanced for loop takes the following for
(type Identifier: expression)
{
// statement;
}
• Where type represents the data type or object
• Identifiers refer to the name of the variable and expression is an array name.
//demonstrate enhanced for loop import
java.io.*;
import java .util.*;
class enhancedfor{
public static void main (String k[ ]){
String states[ ]={“AP”,”TS”,”TM”,”MP”,”UP”};
for (int i=0; i<5; i++)
{
System.out.println(“Normal for Loop:states:”+ states[i]);
}
for(String i: states)
{
System.out.println(“Enhanced for loop:states:”+i);
}
}
}
Jump statements in Java?
Loops perform a set of operations repeatedly until the control variable fails they satisfy
the test condition.
• The number of times a loop is repeated is decided in advanced and the test condition. Is
written to achieve this.
• Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to
leave the loop as soon as certain condition occurs.
• Java permits a jump from one statement to the end or beginning of a loop as well as a jump
out of a loop.
• Java supports two jump statements.
• They are 1.Break
2.Continue;
Using break:-
• The break statement is used to break the condition if the condition is true.
• It is used inside any conditional loop statement.
• In java the break statement has three uses.
→First it terminates a statement sequence in a switch statement
→Second it can be used to exit a loop
→Third it can be used as a civilized form of go to

Condition Break
?

//using break to exit a loop


import java.io.*;
class break loop
{
public static void main (String k[ ])
{
for (int i=0; i<100; i++)
{
if(i==10)
break ;
System.out.println(“i:”+i);
}
System.out.println (“loop is completed”);
}
}
Using Continue:-
• The continue statement is used to skip the rest of the loop in the current iteration as if the
end of the statement block had been reached, causing it to jump to the start of the iteration.
• Here is an example program that uses to cause two numbers to be printed.
Condition? Continue

Remaining Loop

//demonstrate continue
import java.io.*; class
continue loop{
public static void main(String k[ ]){ for
(int i=0; i<10; i++)
{
System.out.println (i+” “); if (
i%2==0)
continue;
System.out.println(“ “);
}
}
}
Classes, objects and methods
Introduction:- Java is a true objected oriented language and therefore the structure of all java
programs is classes.
• Anything we wish to represent in a java program must be encapsulated in a class that
defines the state and behaviour of the basic program components known as objects
• Classes create objects and objects use methods to communicate between them.
Class:- A class is a collection of members that provide a convenient method for packing
together a group of logically related data items and functions that work on them. In java the data
items are called fields and the functions are called methods.
Defining a class:-
• A class is a user defined data type with a template that serves to define its properties.
• Once the class type has been defined, we can create “variables” of that type using
declarations that are similar to the basic type declaration.
• In java, these variables are termed as instances of classes which are the actual objects.
• The basic form of a class definition is
• class classname [extends super classname]
{
[Fields declaration;]
[methods declaration;]
}
• Everything inside the square brackets is optional.
• Class name and super class name are any valid java identifier.
• The keywords extends indicates that the properties of the super class name class are
extended to the class name class.
Fields declaration:-
• Data is encapsulated in a class by placing data fields inside the body of the class definition.
• These variables are called instance variables because they are created whenever an
object of the class is instantiated.
• We can declare the instance variables exactly the same way as we declare the local
variables.
Example :-
class Rectangle
{
int length;
int width;
}
• The class rectangle contains two integer type instance variables.
• Remember these variables are only declared and therefore no storage space has been
created in the memory
• Instance variables are also known as member variables
Method declaration:-
• A class with only data fields has no life.
• Methods are necessary to manipulate the data.
• Methods are declared inside the class but immediately after the declaration of instance
variables.
• The general form of a method declaration is
type methodname(parameter list)
{
Method body ;
}
• The type specifies type of value, the method would return.
• The method name must be valid identifier or otherwise void.
• Void means the function should not return any value
• The parameter list is always enclosed within the parenthesis.
• The body is actually describes the operations performed on the data.
• Let us consider the rectangle class again and add a method getdata( ) to it.
class Rectangle
{
int
length;
int
width;
void getdata(int x, int y) //method declaration
{
length =
x; width
= y;
}
}
Method declaration has four basic parts.
→The name of the method (methodname)
→The type of the value the method returns (type)
→A list of parameters (parameter list)
→The body of the method

Creating objects:-
• An object in java is essentially a block o memory that contains space to store all the instance
variables.
• Creating an object is also referred to as instantiating object.
• Objects in java are created using the new operator. The new operator creates an object of
the specified class and returns a reference to that object.
• Here is an example of creating an object of type rectangle
Rectangle rectl; //a declare the object
rectl = new Rectangle(); // instantiate the object.
• The first statement declares a variable to hold the object reference and the second one
actually assigns the object reference to the variable.
• The variable rectl is now an object of the rectangle class as shown in the below figure.
Action Statement Result
Rectangle rect1; rect1
Declare Null

Instantiate rect1=new Rectangle(); • rect1

rect1 is a reference to
Rectangle object
a rectangle object.
Fig(a):creating object reference
• Both statements can be combined into one as shown in the below
rectangle rectl = new Rectangle ();
• The method Rectangle() is the default constructor of the class”.
• We can create any number of objects of Rectangle
Eg :- Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
• It is important to understand that each object has its own copy of the instance
variables of its classes.
R1

Rectangle Object

R2
Both R1,R2 refer to the same object
• It is also possible to create two one more reference t the same object as shown below.
Rectangle R1= new rectangle ();
Rectangle R2 = R1;
Accessing class members:-Now that we have created objects, each containing its own set of
variables, we should assign values to these variables in order to use them in our program.
• Remember all variables must be assigned values before they are used.
• Since we are outside the class, we con not access the instance variables and the methods
directly.
• To do this I we must use the concerned object and the dot operator as shown in the below.
Objectname.variablename = value;
Objectname.methodname(parameter list);
• Here object name is the name of the object, variable name is the name of the instance
variable inside the object that we wish to access
• Method name is the method that we wish to call and parameter list is a comma separated
list of actual a values that must match in type and member with the parameter list of the
method name declare in the class.
• The instance variables of the rectangle class may be assigned values as follows.
rect1.length = 15;
rect1.width =10;
rect2.lenght=20;
rect2.breadth=12;
• Now that the objects rectl and rect2 store different values as shown below
rect1
rect1.length 15
rect2.width 10
rect2
rect2.leangth 20
rect2.width 12

• This is one way of assigning values to the variables in the objects.


• Another way and more continent way of assigning values to the instance variable is to use
a method that is declare inside the class
• In our case, the method get data can be used to do this work. We can call the get data
method on any rectangle object to set the values of both length and breadth.
• There is the code segment to achieve this.
• Rectangle rect1= new Rectangle();
rect1.getdata (15,10); //calling the method using object
//demonstrate for defining class, creating objects and accessing class members.
import java.io.*;
class Rectangle
{
int length; //instance
variables int width;
void getdata(int x, int y) //method declaration
{
length = x; width = y;
}
int Area()
{
return(length*width);
}
}
class rectdemo
{ //main method class public static void
main(String args[])
{
Rectangle rect1=new Rectangle(); //object is created
int A1= rect1.Area();
rect1.getdata(10,15); //accessing class members using object rect1.
System.out.println(“Area1=”+A1);
}
}
Constructor:-
Java supports a special type of method is called as a constructor. That enables an object to
initialize itself when it is created.
Advantages:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.

Rules/Properties/Characteristics of a Constructor:
▪ Constructor name must be similar to name of the class.
▪ Constructor should not return any value even void also (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
▪ Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
▪ Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
▪ Constructors will not be inherited at all.
▪ Constructors are called automatically whenever an object is creating.

// demonstrate to implement constructor.


import java.io.*;
class Rectangle
{
int length;
int width;
Rectangle (int x, int y) //constructor method
{
length =x;
width=y;
}
int rectArea()
{
return(length*width);
}
}
class condemo
{
public static void main(String args[])
{
Rectangle r= new Rectangle (10,15);// calling constructor
int A=r.rectArea();
System.out.println(“Area of the Rectangle is:”+A);
}
}
Types of Constructors:
Based on creating objects in JAVA we have two types of constructors. They are
default/parameter less/no argument constructor and parameterized constructor. Default
Constructor:
This constructor will not take any parameters. Whenever we create an object only
with default constructor, defining the default constructor is optional. If
we are not defining default constructor of a class, then JVM will call automatically
system defined default constructor (SDDC). If we define, JVM will call
user/programmer defined default constructor (UDDC).
The general format is
class <clsname>
{
clsname ( )

{ //default constructor Block of


statements;
..……………………;
...……………………;
}
………………………;
………………………
}
Parameterized Constructor:
This constructor takes some parameters. Whenever we create an object using parameterized
constructor, it is mandatory for the JAVA programmer to define parameterized constructor
otherwise we will get compile time error. The general format is
class <clsname> {
…………………………;
…………………………;
<clsname> (list of parameters) { //parameterized constructor
Block of statements (s);
}
…………………………;
…………………………;
}
Ex:
class Test
{
int a, b;
Test ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
a=10;
b=20;
System.out.println ("VALUE OF a = "+a);
System.out.println ("VALUE OF b = "+b);
}
}
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
}
Method overloading:-
In java it is possible to create methods that have the same name, but different parameter
lists and different definitions is called as method over loading.
➢ Method overloading used when objects are required to perform similar tasks but using
different input parameters
➢ When we call a method in an object, java matches up the method name is first and then the
number and type of parameters to decide which one of the definitions to execute
➢ To create the overload method, all we have to do is to provide several different method
definitions in the class, all with the same name, but with the different parameter lists
➢ The difference may either be in the number or type of arguments
Note:- methods return type doesn‟t play any role in this
➢ Here is an example of creating an overload method.
// demonstrate method overloading
import java.io.*;
class overloading
{
void test()
{
System.out.println(„‟No Parameters‟‟);
}
void test(int a)
{
System.out.println(„‟a=”+a);
}
void test(int a, int b)
{
System.out.println(“a=”+a+””+”b=”+b);
}
void test(double a)
{
System.out.println(a*a);
}
}
class overloaddemo
{
public static void main(String k[])
{
overloading ov=new overloading();
ov.test();
ov.test(5);
ov.test(3,5);
ov.test(6.1);
}
}
this Keyword:-
“this” is an internal or implicit object created by JAVA for two purposes. They are
1. „this‟ object is internally pointing to current class object.
2. Whenever the formal parameters and data members of the class are similar, to differentiate
the data members of the class from formal parameters, the data members of class must be
proceeded by “this”.

Ex: Demo on ‘this’ Keyword


class Account
{
int a;
int b; //here a,b are instance variable
public void setData(int a,int b) // here a,b are local variables
{
this.a=a;
this.b=b;
}
public void showData()
{
System.out.println("Value of A="+a);
System.out.println("Value of B="+b);
}
Class TDemo
{
public static void main(String args[])
{
Account obj=new Account();
obj.setData(2,3);
obj.showData();
}
}

Static members:-
1) Java static variable
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable


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

Example of static variable


//Java Program to demonstrate the use of static variable
class Student
{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor Student(int r, String n)

rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1

public static void main(String args[])

{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
2) Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student
{
int rollno; String name;
static String college = "ITS";
//static method to change the value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n)
{
rollno = r; name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");

Student s3 = new Student(333,"Sonoo");


//calling display method
s1.display();
s2.display();
s3.display();
}
}

Static methods have several restrictions: -


→They can only call other static methods
→They can only access static data
→They cannot refer to this or super in any way
Java Garbage Collection: -
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
An object be unreferenced in many ways:
o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.
By nulling a reference:

Employee e=new Employee();

e=null;
By assigning a reference to another:
Employee e1=new Employee(); Employee
e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
1) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize()
{

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
public static void gc(){}
Simple Example of garbage collection in java

public class TestGarbage1

{
public void finalize()
{
System.out.println("object is garbage collected");

public static void main(String args[])

TestGarbage1 s1=new TestGarbage1(); TestGarbage1


s2=new TestGarbage1();
s1=null; s2=null; System.gc();
}
}

Array:-
• An array is a group of contiguous or related data items that share a common name.
• For instance we can define an array name salary to represent a set of salaries of a group of
employees
• A particular value is indicated by writing a number called index number or subscript in the
brackets after the array name
• For example salary [10] represent the salary of 10th employee
Advantages:
1) Array can store multiple values of same data type.
2) All the elements in array are accessible by using single name (array name). It overcomes
the name conflict problem.
3) It is a capable of storing many elements at a time.
4) The memory locations of elements in the array are sequential.
5) Sorting and searching becomes easy.
Disadvantages:
1) Memory wastage will be there.
2) To delete an element in array. We need to traverse throughout an array.
3) The size of the array is fixed while declaration itself.
4) The size can‟t be increased / decreased dynamically.
How to create an array:-
• Like any other variable, array must be declared and created in the computer memory before
they are used.
• Creation of an array involves three steps
I. Declaring the array
II. Creating memory locations
III. Putting-values into the memory locations(initialization)
Declaration of arrays:-
• Arrays in java may be declared in two forms.
Form1
Type array name [ ];

Form 2
Type [ ] array name;

Examples:-
int number [ ]; float
average [ ]; int [ ]
counter; float [ ]
marks;
• Remember we do not enter the size of the array in declaration
• Array name is an any valid java identifier

Creation of Arrays:-
• After declaring an array, we need to create it in the memory
• Java allows us to create arrays using new operator only as shown below.

Array name = new type[size];

Example:-
number = new int [5];
average = new float [ 10 ];
• These lines create necessary memory locations for the arrays number and average and
designate them as int and float respectively
• Now the variable number refers to an array of 5 integers and average refers to an
array of 10 floating point values.
• It is also possible to combine the two steps declaration and creation into one as shown
below.
int number [ ]= new int [5];
• The below figure shows the creation of an array in the memory.
Statement Result
int number[ ]; number
• Points no where
number=new int[5]; number

number[0]
number[1]
number[2]
number[3]
number[4]

Fig(a) Creation of an array in memory


Initialization of arrays:-
• The final step is to put values into the array created. This process is known as
initialization.
• This is done using the array subscript as shown below.

Array name[subscript] = value;


Example:-
number[0] =10;
number[1] =20;
number[2]=30;
number[3]=40;
number[4]=50;
• Java creates arrays starting with the subscript 0 and ends with a value one less than the
size specified.
• They can also initialize arrays automatically in the same way as the ordinary variables
when they are declared as shown below.

Type array name [ ] = {set of values};

Example:-
int number[ ] = {10,20,30,40,50};
• The array initialize is a list of values separated by comma and surrounded by
curly braces.
• The compiler allocates enough space for all the elements specified in the list that no size
is given
Array length:-
• In Java all arrays store the allocated size in a variable named length. We can obtain the
length of the array using a length
▪ Example:- int a[size]=a. length;
• This information will be useful in the manipulation of arrays when their sizes are not
down (or) given.
Types of arrays:-
• Java supports the two types of arrays mainly. The two dimensional array supports the arrays
of arrays is called multidimensional array or variable size array. They are
I. Single dimensional array
II. Two dimensional array
III. Variable size array.
1. Single (or) one dimensional array:-
A list of items can be given one variable name using only one subscript. Such a variable is called
a single subscripted variable or a one dimensional array.
The below form shows the single dimensional array:
Type array name[ ] = new type [size];
Example:-
int number [ ] = new int [5];
//demnonstrate for single Dimensional array.
class singled
{
public state void main (String args[ ])
{
int temp=0;
int number[ ] = {35,50,85, 25,15
};
int n=number.length;
//display array elements
for (int i=0; i<n; i++)
{
System.out.println (“ ”+number[i];
}
//sorting
for(int i=0; i<n; i++)
{
for (int j=i+1; j < n; j++)
{
if(number [i] < number[ j] )
{
temp= number[i];
number[i] = number [ j ]
number[ j ] = temp;
}
}
}
//sorting elements are
for (int i=0; i<n; i++)
{
Systems.out.println(number[i]);
}
}
}
2. Two dimensional arrays:-
• A list of items can be given one variable name using two subscripts or two indexes is called
two dimensional array.
• A two dimensional array a table of values will may have to be stored.
• For creating two dimensional arrays. We must follow the same steps as that of simple
arrays.
• We may create a two dimensional array like this.
int ARRAY[ ][ ];
ARRAY = new int [3] [4];
(or)
int ARRAY[ ][ ] = new int[3][4];
• This creates a table that can store 12 integer values, 3 across & 4down. The first index
selects the row and second index selects the columns with in that row as shown in below.
Column0 Column1 Column2 Column3

[0][0] [0][1] [0][2] [0][3]


Row0→
10 20 30 40
[1][0] [1][1] [1][2] [1][3]
Row1→ 50 60 70 80

[2][0] [2][1] [2][2] [2][3]


Row2→ 90 100 110 120

Fig (b): Representation of a two dimensional array in Memory.


• Like the one-dimensional arrays, two dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed with braces.
int number [ ][ ]={{1,2,3,4}, {2,3,4,1}, {3,4,1,2}}.
//demonstrate for two
dimensional array
class twod
{
public static void main(String args[ ])
{
int number[ ][ ] = { {1,2,3,4} , {2,3,4,1} , {3,4,1,2}};
for(int i=0;i<3; i++)
{
for(int j=0; j<4; j++)
{
System.out.println(number[i][ j ]);
}
System.out.println(“ln”);
}
}
}
3. Variable size array:-
• Java treats multidimensional array as “arrays of arrays”.
• It is possible to declare a two dimensional array as follows. +
int x[ ][ ] = new int[3][ ];
x[ 0 ] = new int [2];
x[1 ] = new int [4];
x[ 2 ] = new int [3];
• These statements create a two dimensional array as having different lengths for each row
as shown in the below figure.

X[0] X[0][1]
1][3]
X[1] X[

X[2]

X[2][2]
Fig(c)Variable size array
COMMAND LINE ARGUMENTS:
A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ).
Example
The following program displays all of the command-line arguments
public class CommandLine {

public static void main(String args[]) { for(int i = 0;

i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);

Inheritance:-
Introduction:-
Reusability is yet another aspect of oop paradigm. It is always nice if we could reuse something
that already exists rather than creating the same all over again.
• Java supports this concept.java classes can be reused in several ways.
• This is basically conveyed creating new classes, reusing the properties of existing ones.
Inheritance:-
❖ The mechanism of deriving a new class from an old one is called as inheritance.
❖ The old class is known as the base class or super class or parent class and the new class is
called the sub class or derived class or child class.
❖ The inheritance allows sub-classes to inherit all the variable and methods of their parent
classes.
Types of inheritance:-
Inheritance may take different forms
i. Single inheritance (only one super class)
ii. Multiple inheritance (several super classes)
iii. Hierarchical inheritance (one super class, many sub class)
iv. Multilevel inheritance (derived from a derived class)
These forms of inheritance are shown in the below figure.

A Base/Super/Parent A

B Derived/Sub/Child B C D

a)Single Inheritance b)Hierarchical Inheritance


A A B

B
C

c)Multilevel Inheritance d) Multiple Inheritance


• Java dose not directly implement multiple inheritance. However this concept is
implemented using a secondary inheritance part in the form of interfaces.
Defining a sub-class:-
• A sub class is defined as follows.
class subclassname extends super classname
{
Variable declaration;
Method declaration;
}
• The keyword extends signifies that the properties of the super class name are extended to
the sub class name.
• The sub class will now contain its own variables and methods as well those of the super
class.
• This kind of situation occurs when we want to add some more properties to an existing
class.
Sub class constructor:-
• A sub class constructor is used to construct the instance variable of both the sub class and
the super class.
• The sub class constructor uses the keyword “super” to invoke the constructor method of the
super class.
• The keyword super is used subject to the following conditions.
→ Super may only be used within a sub class constructor method.
→ The call to super class constructor must appear as the first statement with in the sub class
constructor
→ The parameters in the super call must match the order and type of the instance
variable declared in the super class.
Single inheritance:-
• A super class has only one sub class is called as inheritance.
• Java support this concept and uses it extensively in building its class library
• This concept allows us to build a chain of classes as shown below figure.

• The class A serves as a base class for the derived class B class A
//super class
{

}
class B extends A // subclass.
{

}
//demonstrate for single inheritance import
java.io.*;
class Room
{
int length;
int breadth;
Room (int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return (length*breadth);
}
}
class Bedroom extends Room
{
int height;
Bedroom (int x , int y, int z)
{
super (x,y); //send x and y values to super class height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class sidemo
{
public static void main(Sting args[])
{ Bedroom b=new Bedroom (10,15,20);
int a=b.area();
int v=b.volume();
System.out.println (“area=”+a);
System.out.println (“volume=”+v);
}
}
Multiple inheritances:-
• A sub class has the several super classes is called as the multiple as the multiple
inheritance.

A B

• Java does not directly implement multiple inheritances. However this concept is
implemented using a secondary inheritance path in the form of interface
Multilevel inheritance:-
• A common requirement in object oriented programming is the use of a derived class
as a super class is called multilevel inheritance.
• Java supports this concept and uses it extensively in building its class library.
• This concept allows us to build a chain of classes as shown in below figure

Grandfather A super class

Father B Intermediate super class

Child C sub class

• The class A serves as base class for the derived class B. which in turn serves as a base
class for the derived class C
• The chain ABC is known inheritance path
• A derived class with multilevel base classes is declared as follows.
Class A
{

}
Class B extend A // first level
{

}
Class C extends B //second level
{

}
• This process may be extended to any number of levels.
• The class C can inherit the member of both A and B as in the below figure.

Class C members
Class B members
Class A members

Fig(a) C contains B which contains A.


// demonstrate for multilevel inheritance
class BC
{
BC()
{
System.out.println(“I am in base class “);
}
}
class IBC extends BC
{
IBC()
{
System.out.println(“ I am in intermediate base class”);
}
}
class DC extends IBC
{
DC()
{
System.out.println (“ I am in derived class ");
}
}
class multileveldemo
{
public static void main (String k[])
{
DC.obj1=new DC();
}
}

Hierarchical inheritance:-
• In an inheritance a super class has many sub classes is called as hierarchical inheritance.
• In hierarchical inheritance the sub classes can access the all properties of the super class
• The below figure shows the hierarchical inheritance.

B C D
Fig(a) : Hierarchical inheritance
• Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below the level.
• As an example for an hierarchical classification of account for in a commercial
bank
• This is possible because all the accounts possess certain common features as show below
figure.

Account

Savings Current

Fixed-Deposit

Short Medium Long

Fig(b):Hierarchical classification on bank accounts.


// demonstrate for hierarchical inheritance class
A{
void method()
{
System.out.println(“method A”);
}
class B extends A
{
void methodB()
{
System.out.println(“ method B”);
}
}
class c extends A
{
void methodC()
{
System.out.println(“ method C”);
}}
class hierarchicaldemo{
public static void main(String k[]){
A a= new A();
B b=new B();
C c=newC(); a.methodA();
b.methodB();
c.methodC();
} }
Method Overriding:-
This is possible by defining a method in the subclass that has same name, same arguments and
same return type as a method in the super class.
• Then when that method is called ,the method defined in the subclass is invoked and
executed instead of the one in the super class
• This is known as methods overriding
(or)

• If at all a parents class method is redefined under the child class with the same name, same
arguments and same return type is called as method overriding
• Example program for the method overriding
// demonstrate for method overriding
class A
{
int x;
A(int x) // constructor
{
this.x=x;
}
void display()
{
System.out.print(“super:x”=+x);
}
}
class B extends A
{
int y;
B(int x, int y)//child class constructor
{
Super (x);
this.y=y;
}
void display()
{
System.out.println(“super:x”+x);
System.out.println(“super:y”+y);
}
}
class method
{
public static void main (sting args[])
{
B b=new B(10,15);
b.display();
}
}
final variables, final methods and final class:-
Final variables and methods:-
• All method and variables can be overriding by default in subclasses.
• If we wish to prevent the subclasses from overriding the member of the subclass.
We can declare then as final using the keyword final as a modifier
Example :-
final int SIZE=100;
final void display ()
{

}
• Making a method final ensure that the functionality defined in this method will never be
altered in anyway.
Example:-
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda(); honda.run();
}
}

Output: Compile Time Error


Final classes:-
• Sometimes we may like to prevent a class being further subclasses for security
reasons.
• A class that cannot be sub classed is called a final class
• This is achieved in java .using the keyword final as following. final class
A
{

}
final class B extends some class
{
}
• Any attempt to inherit these classes will cause an error and the compiler will not allowed
it .Declaring a class final .prevent any unwanted extension to the class

final class Bike


{
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda(); honda.run();
}
}

Abstract class:-
• A class which contain the abstract keyword in its declaration is known as abstract class
• Abstract class may or may not contain methods i.e., methods without body and methods
end with a semicolon (;).
• Example: public void get ();

• But, if a class has at least one abstract method then the class must be declared
abstract.
• If a class is declared abstract cannot be instantiated
• To use an abstract class, provide implementation to the abstract method in it
Abstract method:-
• If you want a class contain a particular method but you want the actual implemental of that
method to be determined by child classes, we can declare the method in the parent class as
abstract.
• Abstract keyword is used to declare the method as abstract
• We have to place the abstract keyword before the method name in the method
declaration
• An abstract method contains a method signature but no method body
• Instead of curly braces an abstract method we have a semicolon() at the end
• Example program for abstract class & method
// demonstrate for abstract classes and method abstract
class shape
{
abstract void draw();
}
class rectangle extends shape
{
void draw()
{
System.out.println (“draw rectangle”);
}
}
class circle extend shape
{
void draw()
{
System.out.println(“Draw circle”)
}
}
class abstracttest
{
public static void main (String k[]){ Shape
s=new circle( );
s.draw( );
}
}

You might also like