Study Note
On
Introduction
In computer science there is single static word, change. Programming language also has changed
since inception. Initially we used top-to-bottom approach where flow of control moves down from first line
of program to last. Now we have Object Oriented Programming (OOP) where you can run any part of
program. In our daily life we use some word with particular meaning. The collection of those words forms
language. Languages may differ from country to country but everywhere they follow a rule called
Grammar.
Language gives instruction and CPU carries it out. CPU reads codes given by user using specific
language and runs them if they are syntactically correct. Instructions can be given in two ways a)
Interactive and b) Collective. In interactive way user types a command and get its output. Every time you
have to give order one by one and wait for completion of one task before going to another. Instead, you
can also store instructions to be executed in a file and run it once. Thus it becomes easier for user to get
same output every day without writing same code repeatedly. Storage of multiple commands in a file for
joint execution is called program.
Program is a set of instruction logically arranged in a file and executes jointly to solve desired
problem. This file may be repeatedly executed as many times as needed. So we can say that Command(s)
Program(s) File(s) Package(s) Software. During writing program you need to use a language. We
use English-like command to code a program and it is called High Level Language but computer can
understand binary language only. Since it is not easy to cope with binary language 2nd generation or
Assembly language was developed.
In Assembly language some integer replaced core binary digits. For example 65 take place of
0100001 to represent character A. This is known as ASCII (American standard Code for Information
Interchange). Assembly language was developed along with Assembler to translate it into binary.
The use of Assembly Language was also unable to spread computers popularity because here also
user needs to remember numbers. Hence third generation or High level language was invented with
English command with each command replacing multiple task of Low Level Language. High Level
Language was also needed to be translated into binary. Therefore scientists invented two translating
software like a) Interpreter and b) Compiler.
Interpreter read one line of program at a time, convert it to binary and execute the line. Hence
there is no need to store translated version of source code. This translation and execution stops either at
end of source code or on first error line. FoxPro, FORTRAN, Basic are example of Interpreter based
language. Compiler read entire program and convert every line into binary and create an object file with
translated version of source code. This object file gets executed only if there is no error in program.
Otherwise compiler produces list of errors with line numbers. C, C++ are example of compiler based
programming language.
Approach
Approach means way of writing program and also way of its execution. There are different
approaches of writing program. Some of them are a) Procedural and b) Object Oriented.
Procedural approach is top-to-bottom approach in which flow of control of program moves
downfrom first to last line of source code and runs all error free lines. Until recent days program were
taught of as series of procedures or subroutines that acts on data. Procedure is a set of logically arranged
command which has no physical link with data that it is handling. Data part remains separate from
procedure part and trick in this programming is to keep track of which function calls which one and which
data was changed by that call.
Object Oriented approach deals with object. An object is binding of procedure or method as well as
its related data together. Object is self-contained entity with unique identity and properties. Object
oriented approach provides technique for managing enormous complexity, re-use software component
and club data with module that handles it. C, C++, Java, Visual Basic are object oriented programming
language. The following picture depicts an object where data is covered by data-handling procedures. This
concept is also called Encapsulation where private data is covered by public functions that makes data
inaccessible without using functions (like a capsule whose medicines are covered by plastic coats).
Feature of Object Oriented Program
By: Sourav Sengupta Page # 2
The above picture demonstrates stage of object and changing forms of its properties. There is a
glass with water in first picture. Here Glass is object in which weight is a property that has a value (say
200 ml) and due to kick event occurs on glass by a lady, weight of the glass reduces to 100 ml. So glass
object changes its weight property based on an event (kick). Let us see the features or principle of OOP:
Object: It is an identifiable entity with characteristics and behavior. Every object has four key point
like i) Identity (name of object), ii) State (objects relation to its method – suppose growth is method of tree
object and for this method height property of tree changes), iii) Characteristics/Attributes (properties of
objects like weight, height, colour etc. whose values varies from time to time), iv) Behaviour/ Method
(functionality of object like run, eat, sleep).
Class and Object: A class is a blueprint where from object derives. It define characteristic and
behavior of group of real life entity. An object is an instance of a class that has a state which is defined by
class structure. Object is an identifiable entity with characteristics and behavior. For example if car is a
class with characteristic colour and speed then a Toyota of red color and 80 KM/Hr. speed is an object of
that class.
State and Behaviour: Each leaving or non-leaving thing are example of object. Object has an
outlook called its state. On the other hand every object performs some action which is its Behaviour. The
state of an object controls its behaviour and behaviour in turns brings changes in its state. Suppose a
pencil has height state and drawing behaviour and due to drawing height of pencil reduces. In above
picture data represent state and procedure represent behaviour.
Method: The function related to object is method. Method deals with data and represents
behaviour of object. For example function Move, Halt, Accelerate are methods representing car’s behavior.
Every method can accept data from another method which is known as argument and every method can
return data back to its calling method which is called return value.
Abstraction: It means representing essential features of an object which are meaningful and
essential for particular application. It is art of representing essential features without including
background details. For example on switch board only switches are exposed which are needed for
operation but wirings are hidden. Abstraction is idea of showing best features of object and hiding rest
ones.
It refers to the ability to make a class abstract in Java. An abstract class is one that cannot be
instantiated/ objectified. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of abstract class. A
parent class contains common functionality of a collection of child classes but parent class itself is too
abstract to be used on its own. Use abstract keyword to declare a class abstract.
Inheritance: Inheritance deals with carrying qualities of parent classes to their child. If any object
or sub class is created out of a class then it occupies the basic features of that class. By basic features we
refer to class variable and methods. If a student is admitted to class X then he gets the syllabus and study
books of that class automatically.
Encapsulation: Encapsulation is one major OOP feature. It is the way to implement abstraction. It
is a mechanism to wrap up state and behavior (data and function) of an object together into a single unit.
This refers to the concept of data hiding. In encapsulation, the variables of a class will be hidden from
other classes, and can be accessed only through the methods of their current class. Therefore, it is also
known as data hiding. To achieve encapsulation in Java − Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Polymorphism: This word came from Latin word poly and morphos which means many forms. If
one function or operator performs more than one operation within a Java class then it is called
polymorphism. The ability to take more than one form or the ability to perform more than one task by
By: Sourav Sengupta Page # 3
same item is polymorphism. Function overloading is the example of polymorphism in Java. There are two
types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.
Java - Past, Present, Future
Java programming was introduced in 1991 by Green Team from sun micro system lab. James
Gosling and Mike Sheridan gave name of programming as Greentalk. Later on they developed more
improved version and gave name as Oak and then same concept has been included in Netscape. Gosling
was very fond of coffee, that is why he choose logo of Java as coffie cup. The developer claim that Java
programming is simple and portable, multithreaded, interpreted, platform independent, dynamic,
architecturally neural, object oriented and robust.
High level language need to be translated into machine language and for this translation there are
two modes available like compiler and interpreter. Compiler will translate entire program and produce
machine code. Interpreter will run one statement at a time. Machine level programming is the first
generation programming language, assembly language was second generation and third generation
programming language is high level codes. Java is third generation programming language.
Java was developed as part of research project going to develop software for electronics devices
like TV, VCRs, toasters etc. Java’s goals at that time were to be small, fast, efficient, and easily portable to
wide range of hardware devices. Later Sun released Java Developer’s Kit (JDK) which include tools for
developing Java applications and applets.
What’s in store for future? In addition to final Java release from Sun other companies have
announced support for Java in their own browser. For example Netscape Corporation incorporated Java
capabilities into 2.0 version of their Netscape Navigator web browser. Java is both programming language
and platform because like other programming language we can use Java to write various type of computer
application. Java platform is designed to deliver and run highly interactive, dynamic and secure
applications on networked computer system. There are two major types of Java program like application
and applet. Applet runs on web browser and application creates stand alone exucatible file.
Java programs are platform independent because they are compiled to form bytecode (set of
pseudo machine language instructions understood by Java Virtual machine). Java virtual machine is an
abstract machine designed to be implemented on top of existing processor. It hides underlying operating
system from Java and then interpreted by special Java interpreter for specific platform. Actually this Java
interpreter is known as Java Virtual Machine or JVM.
BlueJ
BlueJ is a Java™ development environment specifically designed for teaching. It was designed and
implemented by the BlueJ team at Deakin University, Melbourne, Australia and University of Kent at
Canterbury, UK. BlueJ is distributed in three different formats like Windows, Mac OS and Other operating
system. The prerequisites to install BlueJ are that you must have JDK (Java Development Kit) 1.4 or later
installed in your system. The distribution file for Windows systems is called bluejsetup-xxx.exe, where xxx
is version number. For example, the BlueJ version 2.0.0 distribution is named bluejsetup-200.exe. While
executing this installer, it lets you select directory to install. It will also offer option of installing shortcut in
start menu and on desktop. After installation is finished you will find the program bluej.exe in BlueJ’s
installation directory.
To start BlueJ programming select the BlueJ.Exe file. This software will provide you an interface to
write program which looks like…
In this window you have to create project from Project New Project menu. You can also start your
working with existing projects also by opening it from Project Open Project menu. After creating or
opening project in BlueJ you will get an interface like following where you have to create classes for
writing program. BlueJ projects, like standard Java packages, are directories containing files included in
the project. Press New Class button for creating classes for writing program.
By: Sourav Sengupta Page # 4
Features of Java
Java programs are both compiled and interpreted
Platform independent and portable.
Object oriented, simple and small.
Interactive
Dynamic and Extensible and
Distributed
Dynamic and Extensible
Familier, Simple and Small
Java and C
The main difference between Java and C is that Java is OOP language and has mechanism to define
class and objects. Java doesnot include C keywords goto, sizeof and typedef. It donot has datatype lieke
struct, enum and union. It donot support pointer type data. Java donot have a pre-processor and we
cannot use #define, #include and #ifdef commands. Java adds new operators like instanceof and >>>. It
has labelled break and continue statement.
Java and C++
Java doesnot support operator overloading or template class like C++. Java has replaces
desctructor function with finalize(). It introduces the concept of interface. There are no header files in Java.
Java donot support virtual function.
Java Environment
It includes large set of development tools and lots of classes and funtions. The development tools
are part of system known as Java Development Kit or JDK. The class and methods are parts of the Java
Standard Libirary or JSL which is also called Application Programming Interface or API. JDK collects tools
used for developing and running Java program. JDK includes a) appletviewer, b) javac (java compiler), java
(java interpreter), javap (java disassembler), javah(for C header files), Javadoc (for creating HTML
documents) and jdb (debugger). API includes lots of classes and methods grouped into several packages
like language support package, utility package, IO package, Networking package Applet and Awt package.
Java Character Set
The smallest units of Java language are the characters used to write Java tokens. These are
Unicode character set. The Unicode is a 16 bit character coding system and currently supports more than
34000 defined characters. The ASCII characters is a subset of Unicode character set of Java.
First Java Program
This can be your first java program which will display message “Hello World” on screen. In this
program we are using a class called ClassIX within which there is a function called main(). Every class and
function of java begins with a opening curly brace like { and ends with a closing brace like } and every
executable and complete command line of a program ends with a semi colon (;). System.out.println()
function is used to display text.
Java Token
The smallest individual independent unit of a program is called token. They are used as building
blocks of a program. There are five tokens available in java like keyword, identifiers, literals, punctuators,
& operators.
Keyword are pre-defined or reserved words in programming language. Each keyword is meant to perform
specific function. Since keywords are referred names for a compiler they can’t be used as variable names
because by doing so, we are trying to assign a new meaning to keyword which is not allowed. There are 3
reserved words in Java that are not a keyword which are true, false and NULL. List of keywords are of Java
are:
abstract assert boolean break implements protected
byte case catch char interface static
class const continue default package synchronized
do double else enum return transient
extends final finally float super while
for goto if strictfp throw switch
import instanceof int this void throws
long native new try public volatile
By: Sourav Sengupta Page # 5
private short
Final Keyword
Java supports final class, Method and variables. We know that in Java we can do inheritance by
creating subclasses of parent class but if we use Final keyword to create a class then that class will be
blocked and cannot be inherited. A final variable cannot be reinitialized again. So finalization is the last
step in case of creating a class, method or variables. A variable declared as final but not initialized during
declaration time is called blank or uninitialized variable. These variables can be initialized later on but for
once only.
The final keyword in java is used to restrict user. This keyword strops value changes in a variable,
stops function overloading and stops inheritance of a class. To create a final class we have to write final
class <class name>. In case we do not want to make sub class of a class or further use of a variable
then we can create a sub class or a sub method (function).
A final method is inherited but you cannot be overridden. It is possible to overload a final method.
A final variable can be passed as parameter or arguments also to a method. This parameter is
called final parameter and its value cannot be changed in the called function.
Abstract Keyword
The abstract keyword of java is used to achieve abstraction in Java. It is a non-access modifier
which is used to create abstract class or method. The role of abstract class is to contain abstract method.
However it can also contain non abstract method. We cannot declare abstract method in non-abstract
class. Rules for using abstract keyword:-
Abstract keyword cannot be used with variables and constructor.
If a class is declared as abstract then it cannot be instantiated. Means no object of the class
follows.
If a method is abstract then it does not contain a body. We cannot use abstract keyword with the
final keyword.
We cannot declare abstract method as private or static It can only be used with class or method,
not with variable. An abstract class can contain constructor and static methods. An abstract class can
contain final method.
Literal is source code representation of fixed value. They are represented directly in the code
without any computation. Literals can be assigned to any primitive type variable. Character literals are
also known as escape sequence as their effects are printed on screen, not the value. Java language
supports few special escape sequences for String and char literals like:
Notation Character represented
\n Newline
\r Carriage return
\b Backspace
\s Space
\t Tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character
\uxxxx Hexadecimal UNICODE character
Operator: Every programming language performs mathematical or comparative task in its
program. For these operations we need the help of some symbols which are known as operators. An
operator is a symbol that takes one or more arguments and operates on them to produce a result. In Java
there are various types of operators like Arithmetic Operators, Logical operators, Relational operators etc.
Arithmetic Operator:
Operator Description
+ Addition - Adds values on either side of the operator
- Subtraction - Subtracts right hand operand from left hand operand
* Multiplication - Multiplies values on either side of the operator
/ Division - Divides left hand operand by right hand operand
% Modulus - Divides left hand operand by right hand operand and returns remainder
++ Increment - Increase the value of operand by 1
-- Decrement - Decrease the value of operand by 1
Relational Operators:
Operator Description
== Checks if the value of two operands are equal or not, if yes then condition becomes
true.
!= Checks if the value of two operands are equal or not, if not then condition becomes
true.
> Checks if value of left operand is more than value of right operand, if yes then its
true.
By: Sourav Sengupta Page # 6
< Checks if value of left operand is less than value of right operand, if yes then its true.
>= Checks if value of left operand is greater than or equal to value of right operand.
<= Checks if value of left operand is less than or equal to value of right operand.
Bitwise Operators:
Operator Description
& Binary AND Operator copies a bit to the result if it exists in both operands.
| Binary OR Operator copies a bit if it exists in either operand.
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
~ Binary Ones Complement Operator is unary and has the effect of 'flipping'
bits.
<< Left Shift Operator. The left operand value is moved left by number of bits
specified by right operand.
>> Right Shift Operator. The left operands value is moved right by number of bits
specified by right operand.
>>> Shift right zero fill operator. The left operands value is moved right by number
of bits specified by the right operand and shifted values are filled up with
zeros.
Logical Operators:
Operator Description
&& Logical AND operator. If both operands are true then condition becomes true.
|| Logical OR Operator. If any of two operands are true then condition becomes
true.
! Logical NOT Operator. Use to reverses logical state of its operand. If condition
is true
then Logical NOT operator will make false.
Assignment Operators:
Operator Description Example
= Assigns values from right side operands to left side operand
C = A + B assign value of A + B
into C
+= Unary Add operator, It adds right operand to left operand
and assign result to left operand C += A is equivalent to C = C + A
-= Unary Subtract operator, It subtracts right operand from left
operand and assign result to left operand C -= A is equivalent to C = C - A
*= Unary Multiply operator, It multiplies right operand with left
operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Unary Divide operator, It divides left operand with right
operand and assign result to left operand C /= A is equivalent to C = C / A
%= Unary Modulus operator, It takes modulus using two operands
and assign the result to left operand C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= Unary exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= Unary inclusive OR and assignment operator C |= 2 is same as C = C | 2
Ternary Operator: Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as : variable x = (expression) ? value if
true : value if false
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is
of a particular type (class type or interface type). instanceOf operator is written as:
( Object reference variable ) instanceOf (class/interface type). The Precedence of Java Operators are:
Category Operator Associatively
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
By: Sourav Sengupta Page # 7
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right
to left
Comma Left to right
Identifier are used as general terminology for naming of variables, functions, classes and arrays.
These are user defined names consisting of an arbitrarily long sequence of letters and digits with either a
letter or the underscore as a first character. Identifier names must differ in spelling and case from
keywords. Once declared, you can use identifier in program statements to refer to the associated value.
Variable
Every programming language deal with provision of storing inputs coming from the users either for
time being or permanently. To store data or information within computer you need to reserve some
memory space either inside internal memory of computer or in Hard Disk. This memory space used for
holding data within internal memory is reserved by specific name as given by user. We indicate entitled
memory area as Variable and entitled memory area of Disk as File.
In Java also, variable is a place to store information temporarily until program is not terminated or
the machine has not been switched off. It is a location inside computer in which we can store data which
can be retrieved later on. Your computer memory can be viewed a series of cubbyholes. Each hole of
memory is numbered sequentially. This numeric references are known as memory address. A variable
reserves one or more cubbyholes in which you can store data. The variable name given by programmer
(such as name, age) is like a label on any one of these holes. This label helps you to find the data easily
without knowing its memory address. Storing data inside a variable is the static way of data reservation
because for using a variable you need to specify workspace of that variable in memory beforehand and
this is done by mentioning the data type of a variable. There are three types of variables in java: local,
instance and static
1) Local Variable: A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't even aware that the
variable exists. A local variable cannot be defined with "static" keyword.
2) Instance Variable: A variable declared inside the class but outside the body of the method, is
called instance variable. It is not declared as static. It is called instance variable because its value is
instance specific and is not shared among instances.
3) Static variable: A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Data Type
Variable is a named memory location associated with a memory address to store one data of
specific data type. Therefore as programmer you have to specify type or nature of data to be entered
within a variable. Data Type indicates the kind of data item user is allowed to place in a variable. It is like
the rooms of a Hotel. A Hotel may have deluxe room or ordinary room for different types of customer. This
is called room type. Similarly every variable do not store all kind of data like characters or number. Java
provides two different categories of data type like a) Fundamental/ Primitive and b) Derived/Non-Primitive.
The Fundamental data type is basic level of data representation and used in almost every Java
program. The examples of some fundamental datatype provided by Java language are a) int (whole
number), (b) float (fractional number with 8 decimal point), (c) double (fractional number with 16 decimal
point), d) char (single character), e) void (NULL / Empty character) etc.
The char variable has 1 byte data storage capacity. That means you can store from –128 to 127
(ASCII) in character variable. The short variable has 2 bytes capacity of data storage. That means you
have 2 x 8 = 16 bits available space for an short variable and in each bit area you can store either 0 or 1,
hence the maximum, possible data for the variable should be 2 16 = 65556 apx. But in each data-type
(other than character) one bit is always reserved for storing numeric operators like +, - etc. This bit is
called sign bit. So capacity of short data type gets reduced from 216 to 215 (32768). So an short variable
can store values ranging from –32767 to 32768. The users can however use a type modifier (a key word
used before data-type to change its storage capacity) called unsigned to convert a sign bit into data bit.
Hence storage capacity of unsigned short datatype becomes 2 16 as the sign bit also stores data now.
We can use mixed datatype as extension or expansion of fundamental datatype which provides
one datatype to be added before name of another fundamental datatype. These keywords are used to
changes storage capacity of a variable. Some of them are a) short int (integer with 2 byte space), b) long
int (integer with 4 byte space), c) double float (float with 8 byte space) etc. Let us see a storage capacity
table for all fundamental datatype available in JAVA:
Data Type Signed Unsigned Minimum value Maximum
value
byte 1 / 28 1 / 28 -128 (ACSII) 127 (ASCII)
char 1 / 28 1 / 28 -128 (ACSII) 127 (ASCII)
short 2 / 215 2 / 216 -32767 32768
int 4 / 231 2 / 232 -231 231 – 1
float 4/2 31
2/2 32
-231
231 – 1
double 8/2 63
2/2 64
-263
263 – 1
By: Sourav Sengupta Page # 8
long 8 / 263 2 / 264 -263 263 – 1
Boolean 2 / 216 2 / 216 true/false true/false
void -- -- -- --
Life time and Scope of Variable
Before declaring a variable within a program programmer should plan about two different things
about that variable, which are a) Scope of the variable (The scope indicates that what facility a variable
can offer to you. It means what kind of data you can store in that variable and what amount (data size) of
data can be stored) and b) Life time of the variable (This indicates how far and up to what time the
variable can be used. Generally we have four different types of variable according to their life time. They
are Auto, Static, Extern and Register)
In any programming language, whenever you are calling a sub function (in a multi level
programming) from the main() function then the computer creates a separate data-block for the variables
related to each different functions and each of these data-blocks are known as activation stack of
corresponding function. When the control comes back from the called (sub) function to the calling function
(main), then the data-block or activation stack of the of the child (sub) function gets erased and when you
are calling the same sub function again the stack gets recreated. This type of variable is known as auto
variable as it is a local variable being known by only a function and automatically created and deleted.
public class abc
{ public static void main(String args[])
{ int i;
for(i=1;i<=3;i=i+1)
{ autofunction(); }}
public static void autofunction()
{ auto int x=0;
x=x+1;
System.out.println("The current value of auto x variable is" + x); }
If you add the term static (known as storage class specifier) before the variable name during its
declaration then the variable of a sub function do not dies off as soon as the child function is terminated,
since the variable is declared some where else in the memory instead of the child activation stack. So if
you call the sub function for the next time then it is not recreated. The static variable dies off when the
entire program is closed or terminated. Let us see the above program using static variable.
public class xyz
{ public static void main(String args[])
{ int i;
for(i=1;i<=3;i=i+1)
{ staticfunction(); } }
public static void staticfunction()
{ static int x=0;
x=x+1;
System.out.println("The current value of static x variable is" + x); }
A static variable is initialized only once when the program is compiled and it is kept in a separate
data block that do not die when the sub function is not working and that is why this program has been
able to sustain the previous value of the variable x, which was not done in case of auto variable as
displayed earlier.
public class pqr
{ public static void main(String args[])
{int x;
x=9;
sub1(); }
public static void sub1()
{ extern int x;
System.out.println(x); }
By: Sourav Sengupta Page # 9
When you link these above two functions then it will give the error – Duplicate variable if the extern
keyword is not present, but if you define the variables in the second program as extern then the sub
function will look at all other functions for the ex-declaration of the variable and will not give you any error
since it is a global time variable. All variable of a function are stored within the Random Access Memory
(RAM) and it accesses the CPU by exchanging the data between RAM and CPU. If you declare a variable as
register type, then the variable gets stored within the CPU itself and if you include those variables within
CPU, then the accession time gets reduced automatically.
Separator are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code. Some of java separators are parentheses, braces,
brackets, semicolon, comma etc. they separate a block with another and a variable with another
Objects and Classes
In object-oriented programming technique, we design a program using objects and classes. An
object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
Class as basis of all computation
The Java programming language does not allow variable declarations or functions definitions to be
placed outside of the classes. Thus all the computations in Java programs must be placed inside a class
and that’s why a class is said to be the basis of all computations in Java. An entity that has state and
behavior is known as an object. For example chair, bike, marker, pen, table etc. It can be physical or
logical (tangible and intangible). The example of an intangible object is banking system. An object has
three characteristics like Characteristic: represents data (value) of an object, Behavior: represents
functionality of an object such as deposit, withdraw, Identity/ State: An object identity is typically
implemented via an unique ID. The value of ID is not visible to external user. However it is used
internally by JVM to identify each object uniquely. For Example Pen is an object. Its name is Reynolds,
color is white, known as its characteristic. It is used to write so writing is its behavior. An object is an
instance of a class. A class is a template or blueprint from which objects are created. Object is product
of a class. Object defines a) real-world entity, b) runtime entity, c) state and behavior and instance of a
class.
Class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical. A class in Java can contain fields
(variables), method (function), constructor (special type of function), block (construct), nested class (a
class within another) and interface. It is a collection of objects of similar nature. The new keyword is
used to allocate memory for objects at runtime. All objects get memory in heap memory area. The
syntax to declare a class is
<access specifier> class <class_name>
{ field;
method; }
Components of class
A class has two type of components like external wrapper and internal components. The external
wrapper deals with class keyword and classname. The intenal elements are data member (class and
instance variable), member functions (static and non-static), constructor, subclass etc.
Instance variable or Field: A variable which is created inside the class but outside all methods is
known as instance variable. This variable is always global and can be either static or nonstatic. The
static variables belongs to the class and cannot be ontained by the objects whereas the nonstatic
members belongs to the objects. The memory allocation of static variables of a class is done during
compilation time and nonstatic members is done at runtime. Instance variable gets memory at runtime
when an object of class is created. That is why it is known as instance variable.
Method: A method is a function which is used to expose the behavior of an object. It is a group of
codes reffered by a single name. it may take arguments or parameter and may return a value after
completion of its work. The advantage of having method is reusability of codes and code optimization.
Constructor: It is a special function of a class that is used to initialize the class or instance
variables. The name of constructor is similar to the name of class and it is invoked automatically when
objects are created.
Sub class: A class can reside within aniother class. It is called nested class. Lets see a example of
a class Student which has two data members id and name and create object of the class by new
keyword and printing the object's value.
public class Student
{ int id; String name;
public static void main(String args[])
By: Sourav Sengupta Page # 10
{ Student s1=new Student(); //creating an object of Student
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name); }}
0
null
In real time development we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a
single Java source file it is a good idea to save the file name with the class name which has main()
method or the class which is public in nature. Lets see:
class Student
{ int id; String name; }
class TestStudent1 //Creating another class which contains the main method
{public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name); }}
0
null
There are three ways to initialize object of a class in Java which are i) by reference variable, ii) by
method or iii) by constructor. Lets see them one by one.
class Student{ int id; String name; } //by reference variables
class TestStudent2
{ public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonu";
System.out.println(s1.id+" "+s1.name); }}
101 Sonu
We can also create multiple objects and store information in it through reference variable. For
example:
class Student{ int id; String name; }
class TestStudent3{
public static void main(String args[])
{ Student s1=new Student();
Student s2=new Student();
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name); }}
101 Sonoo
102 Amit
In following example we are creating the two objects of Student class and initializing value to these
objects by invoking the insertRecord method. Here we are displaying the state (data) of the objects by
invoking the displayInformation() method.
class Student{ int rollno; String name;
void insertRecord(int r, String n)
{ rollno=r; name=n; }
void displayInformation() {System.out.println(rollno+" "+name);} }
class TestStudent4{
public static void main(String args[])
{ Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation(); }}
111 Karan
222 Aryan
As you can see in above figure object gets memory in heap memory. The reference variable refers
to object allocated in heap memory area. Here, s1 and s2 both are reference variables that refer to the
objects allocated in memory. There are different ways to create an object in Java. They are: By new
keyword, By newInstance() method, By clone() method, By deserialization, By factory method.
By: Sourav Sengupta Page # 11
Anonymous Objects
Anonymous simply means nameless. An object which has no reference name is known as an
anonymous object. It can be used at the time of object creation only and therefore it will be killed
automatiocally. If you have to use an object only once an anonymous object is a good approach. For
example: new Calculation(); Calling method through a reference:
Calculation c=new Calculation(); c.fact(5);
Calling method through an anonymous object - new Calculation().fact(5); Let's see the full
example of an anonymous object in Java.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++)
{ fact=fact*i; }
System.out.println("factorial is "+fact); }
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object }} output: Factorial is 120
Creating multiple objects by one type only: We can create multiple objects by one type only as
we do in case of primitives. For example initialization of primitive variables can be done as
int a=10, b=20; Initialization of refernce variables on the other hand can be done as
Rectangle r1=new Rectangle(), r2=new Rectangle(); Let's see:
class Rectangle { int length; int width;
void insert(int l,int w) { length=l; width=w; }
void calculateArea() {System.out.println(length*width);} }
class TestRectangle
{ public static void main(String args[]){
Rectangle r1=new Rectangle(), r2=new Rectangle(); //creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea(); } }
55
45
Lets see another example:
class Account { int acc_no; String name; float amount; }
void insert(int a,String n,float amt) //Method to initialize object
{ acc_no=a; name=n; amount=amt; }
void deposit(float amt) { amount=amount+amt; System.out.println(amt+" deposited"); }
void withdraw(float amt)
{ if(amount<amt)
System.out.println("Insufficient Balance");
else
amount=amount-amt;
System.out.println(amt+" withdrawn"); }
void checkBalance(){System.out.println("Balance is: "+amount);}
void display(){System.out.println(acc_no+" "+name+" "+amount);} }
class TestAccount //Creating a test class to deposit and withdraw amount
{ public static void main(String[] args)
{Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
By: Sourav Sengupta Page # 12
a1.withdraw(15000);
a1.checkBalance(); }}
Access Modifiers
There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers
in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change access
level of fields, constructors, methods, and class by applying the access modifier on it. There are four types
of Java access modifiers:
private: The access level of a private modifier is only within the class. It cannot be accessed from outside
of the class.
default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be treated as default.
protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
Access within class within outside package by subclass outside
specifier package only package
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
There are many non-access modifiers or type modifiers like static, abstract, synchronized, native,
volatile, transient, friendly etc. They are used to specify the lifetime of a field/variable in the program.
Here are the list of different type modifiers of Java:
1) private: the private modifier is accessible only within the class. For example: we have created
two classes A and B. A class contains private data member and private method. We are accessing these
private members from outside the class and we get so there is a compile-time error.
class A { private int data=40;
private void msg(){System.out.println("Hello java");}}
public class B{ public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg(); }}//Compile Time Error
Role of private constructor: If you set any class constructor as private then you cannot create the
instance of that class from outside the class because a class cannot be private or protected except nested
class. For example:
class A{ private A(){}//private constructor
void msg(){System.out.println("Hello java");}}
public class Simple{
public static void main(String args[]){
A obj=new A(); }}//Compile Time Error
2) default: If you don't use any modifier during the declaration then it is treated as default. The
default modifier is accessible only within the package where the calss is created. It cannot be accessed
from outside of the package. It provides more accessibility than private but it is more restrictive than
protected and public specifier. In the following example we have created two packages pack and mypack.
We are accessing A class from outside its package. Since A class is not public it cannot be accessed from B
class which is outside of the package.
package pack; //save by A.java
class A{ void msg(){System.out.println("Hello");} }
package mypack; //save by B.java
import pack.*;
class B{ public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg(); }}//Compile Time Error
In this example, the scope of class A and its method msg() is default so it cannot be accessed from outside
of the package. 3) protected :The protected access modifier is accessible within package and
outside of the package but through inheritance only (by using sub class). The protected access modifier
can be applied on the data member, method and constructor. It can't be applied on the class. It provides
more accessibility than the default modifier but less benefits than public specifier. In this example we have
created two packages pack and mypack. The A class of pack package is public so can be accessed from
outside the package. But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance:
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
package mypack;
By: Sourav Sengupta Page # 13
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg(); }}
4) public: The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers. The example of public access modifier is as follows:
package pack;
public class A{ public void msg(){System.out.println("Hello");}
public void msg1(){System.out.println("Hello again");}}
package mypack;
class B extends A{ public void main(String args[]){
B obj = new B();
obj.msg();
super.msg1(); // public call}}
By: Sourav Sengupta Page # 14
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode. It is designed to be implemented on top of existing processor. It hides the under lying operating
system from Java application programs written in Java are compiled into Java Byte Code which is then
interpreted by a special Java interpreter for a specific platform. Actually this Java interpreter is known as
Java Virtual Machine or JVM.
JVM is
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries
+ other files that JVM uses at runtime.
Multi Level Function
Within Java program, there must be one main() function (as per core java) for execution of
program. Houever in IDE like BlueJ etc you can skip the main function. Other than main() function we can
have other functions also within a program. Those functions are called Sub-Function. There can be
unlimited number of sub functions within a program. Those sub-functions are basically used for purpose of
distributing load of main() function. That means using a sub function you can divide task to be done
among multiple segments and each of these sub functions are responsible to reply back to function from
where sub function was invoked or called. Let us see use of sub function to perform same task as done by
above program:
public class javalearning Intruduces a new class
{public static void main() First function to be executed.
{ system.out.println("Let us learn");
sub(); } Sub function invoked or called
public static void sub() Declares the sub function.
Body of Sub {
Function printf("C Programming"); }
In the above program message line to be displayed has been broken into two parts and printed
using two separate functions – main() and sub(). Every sub function that you are using in the scope of your
program must be declared before the main() function and within the main() function you must call the sub
function for at least one time if you want the sub function to perform. When sub function is called then
body of sub function is executed. Sub function can accept data from calling function for processing. Those
data comes to sub function via some variable or constant. When any sub function accepts data from its
parent (calling) function then those data are known as Argument. The arguments can be of any data type.
Let us see an example of arguments.
public class javalearning
{public static void main()
{ int a=10, b=25;
sub(a, b); } Calls the sub function with two integer arguments passed
public static void sub(int x, int y)
{ int z = x+y;
System.out.print("The output is %d",z);}}
The above sub function accepts two arguments coming from the main() function (a and b) which
are received by two integer variables of the sub function (x and y) and the sum is calculated accordingly.
Just like function of program can accept input values (arguments), every sub function also do have the
ability to send some data (output) back to its calling function though it is not always necessary. The output
data send back by sub function to its parent is known as Return Value. Like argument the data type of
return value can be anything like int, char, float etc. Let us see an example of return value.
public class javalearning
{public static void main()
{ int a=10, b=25;
int c=sub(a, b);
By: Sourav Sengupta Page # 15
System.out.pritln("The sum is “+c); }
public static int sub(int x, int y)
{ int z =x +y;
return(z); } returns the value of the variable z to main() function.
The above sub function accepts two arguments coming from the main() function (a and b) which
are received by two integer variables of the sub function (x and y) and returns one integer data (z) which
is received by the variable c of the main() function. The value of the variable z has been thrown to the
variable c and displayed in the scope of the main() function. Java sub function can be classified into four
types according to the use of arguments and return value. They are:
a) With argument and with return value
b) With argument and without return value
c) Without argument and with return value
d) Without argument & without return value
Let us demonstrate all four type of sub functions within a single program:
public class Javalearning
{public static void main()
{ int a=10, b=25,c;
c=sub1(a, b); // 1st sub function called
System.out.println("Sum using with argument and with return value method is"+c);
sub2(a, b);// 2nd sub function called
c=sub3 ();// 3rd sub function called
System.out.println("Sum using without argument and with return value method is "+ c);
sub4 (); // 4th sub function called }
public static int sub1(int x, int y)
{ int z= x+y;
return(z);}
public static void sub2(int x, int y)
{int z =x +y;
System.out.println("The sum using with argument and without return value method is "+ z); }
public static int sub3()
{int p=10, q=21, r;
r =p + q;
return (r);}
public static void sub4()
{int p=5, q=10, r;
r =p + q;
System.out.println("The sum using without argument & without return value method is"+r); }}
The above program is consists of four sub functions and each of them calculates the summation of
two numbers, either coming from the calling function or from its own scope. The first and second sub
function accepts inputs (arguments) from their parent function while the rest two generates the sum by
assigning data within the sub functions themselves.
By: Sourav Sengupta Page # 16
Flow of Control
Java compiler execute code from top to bottom. The statements are executed according to order in which
they appear. However Java provide statements that can be used to control flow or movement of Java code.
Sometimes we may not required to run all the statements of a program and we want to run selective part
of a program. Such statements are called control flow of control statement. Java provides three types of
control flow statement. They are i) Decision Making statement (if, switch), ii) Loop statement (do while,
while, for, for-each), iii) Jumping statement (break, continue). Flow of control is needed to control
operation of a program in certain situations. It is not necessary that everytime we need to execute all the
lines of a program because we may skip some part of it depending on some condition. We amy also repeat
a part of a program for more than once.
Decision-Making statement
As the name suggests decision-making statements decide which statement to execute and when.
Decision-making statements evaluates Boolean expression and control the program flow depending upon
the result of condition provided. There are two types of decision-making statements in Java. They are if
and switch statement. They are similar to decisions of real life. In programming we face situations where
we want certain block of code to be executed and some other part to be ignored. A programming
language uses control statement to control the flow of execution of program based on test condition.
There are several decision making statements in Java like if, if-else, nested-if, if-else-if, switch-case etc.
if
if: In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either true
or false. In Java, there are four types of if-statements given below. This statement is the most simple
decision making statement and used to decide whether a certain statement or block of statements will be
executed or not based on a given condition. The syntax of this statement is:
if(condition)
{ Statements to execute if condition is true }
if-else: If statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t, but what if we want to do something when the if condition
is false. Here comes else statement. We can use else statement along with if to execute a block of code
when the condition is false. The syntax is:-
if(condition)
{ Statements to execute if condition is true }
else
{ Statements to execute if condition is false }
Lets have a program on if-else statement:
public class Student {
public static void main(String[] args) {
int x = 10; int y = 12;
if(x+y < 10) { System.out.println("x + y is less than 10"); }
else { System.out.println("x + y is greater than 20"); }}}
Output:
x + y is greater than 20
Nested-if: A nested if is like nested loop statement. It is an if statement that is the target of another
if or else sattement. Nested if statements means if statement inside another if. The inner if statement
executes only when the out if is satisfied in its condition. The syntax of nested if statement is
if(condition)
{
if(condition)
{statement when the inner loop is true}
else
{statement when the inner loop is false} }
else
{statement when the outer loop is false}
Consider the following example regarding nested if.
public class Student {
public static void main(String[] args) {
By: Sourav Sengupta Page # 17
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida"); }
else { System.out.println(address.split(",")[0]); } }
else {System.out.println("You are not living in India"); }}}
Output:
Delhi
if-else-if ladder: Here a user can decide among multiple options. The if statements are executed
from the top to down. As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed. It is called chain of if statements of continuous if. The if-else-if
statement contains the if-statement followed by multiple else-if statements. In other words, we can say
that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
switch..case
The Java switch statement executes one statement out of multiple condition. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long types. In other words the switch
statement tests the equality of a variable against multiple values. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of
the program. While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. Remember that….
o There can be one or N number of case values for a switch expression.
o The case value must be of switch expression type only. The case value must be literal or constant.
It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-time error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
o Each case statement can have a break statement which is optional. When control reaches to the
break statement, it jumps the control after the switch expression. If a break statement is not found,
it executes the next case from the first matching case. It is called fall through.
o The case value can have a default label which is optional.
o We cannot use operator in switch cae statements. The syntax of switch statements is:-
switch(variable){
case value 1: code to be executed; break;
case value 2: code to be executed; break;
case value 3: code to be executed; break;
default: code to be executed if all cases are not matched; }
Loop Statement
Loop or iteration means repetition of some task in the programming for specific perods. In programming
languages loops are used to execute set of instructions/functions repeatedly when some conditions
become true. There are three types of loops in java. In programming, sometimes we need to execute a
block of code repeatedly while some condition evaluates to true. However loop statements are used to
execute same instructions in a repeated order. The execution of the set of instruction depends upon a
particular condition. In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time A simple loop is has the following four steps like
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false. It must return boolean value either true or false.
It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
In programming Loop means repetition or iteration. If you need to repeat a group of statements for
specific period of times till when the given condition is satisfied then use the looping commands of Java.
There are three different loops available in Java like while, for and do...while loop. A while loop is a control
structure that allows you to repeat a task for a certain number of times till the conditions given against the
while condition is true. The syntax of a while loop is: while(condition)
{
Statements to run
}
By: Sourav Sengupta Page # 18
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one
time. The syntax of a do...while loop is:
do
{
//Statements
}while(Condition)
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times. A for loop is useful when you know how many times a task is to be repeated. The
syntax of a for loop is:
for(initialization; condition; update)
{
//Statements
}
Comparison for loop while loop do while loop
Introductio The Java for loop is a The Java while loop The Java do while loop is a
n control flow statement is a control flow control flow statement
that iterates a part of the statement that that executes a part of
programs multiple times. executes a part of the programs at least
the programs once and the further
repeatedly on the execution depends upon
basis of given the given boolean
boolean condition. condition.
When to If the number of iteration If the number of If the number of iteration
use is fixed, it is iteration is not is not fixed and you must
recommended to use for fixed, it is have to execute the loop
loop. recommended to at least once, it is
use while loop. recommended to use the
do-while loop.
Syntax for(init;condition;incr/ while(condition){ do{
decr){ //code to be //code to be executed
// code to be executed executed }while(condition);
} }
Example for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); } while(i<=10){ do{
System.out.println( System.out.println(i);
i); i++; }while(i<=10);
i++; }
Syntax for(;;){ while(true){ do{ //code to be
//code to be executed } //code to be executed
executed} }while(true);
According to runtime a loop can be classified into two types like i)Finite and ii)Infinite loop and as per
condition test a loop can be classified as i) Entry-controlled loop and ii) Exit-controlled loop. According to
runtime a loop can be finite or infinite. Let's understand the loop statements one by
one.
for loop: In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement) {<statements}. The flow chart for the for-loop is given
below.
By: Sourav Sengupta Page # 19
Consider the following example to understand the proper functioning of the for loop in java.
public class Calculattion {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j; }
System.out.println("The sum of first 10 natural numbers is " + sum); }}
Output:
The sum of first 10 natural numbers is 55
for-each loop: Java provides an enhanced for loop to traverse the data structures like array or collection.
In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java
is given below.
for(data_type var : array_name/collection_name){//statements }. Consider the following example to
understand the functioning of the for-each loop in Java.
public class Calculation {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {System.out.println(name); }}}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
while loop: The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed. The syntax of the while loop is given below.
while(condition){ //looping statements } . The flow chart for the while loop is given in the following
image.
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2; }}}
By: Sourav Sengupta Page # 20
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
do-while loop: The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least once, we
can use do-while loop. It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
do
{ <statements >} while (condition); The flow chart of the do-while loop is given in the following
image.
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10); }}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statement
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
break statement: As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop. The break keyword is used to stop the entire
loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop
the execution of the innermost loop and start executing the next line of code after the block. The break
statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or
switch statement. Consider the following example in which we have used the break statement with the for
loop.
public class BreakExample {
public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break; }}}}
Output:
0
1
By: Sourav Sengupta Page # 21
2
3
4
5
6
break statement example with labeled for loop
public class Calculation {
public static void main(String[] args) {
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a; }}}}}
Output:
0
1
2
3
4
5
continue statement: Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop immediately.
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately
jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to
immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately
jumps to the Boolean expression. Consider the following example to understand the functioning of the
continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue; }
System.out.println(j); }}}}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
By: Sourav Sengupta Page # 22
Java Compilation
The steps in writing a Java program is illustrated as follows:
Step 1: Write the source codes (.java) using a programming text editor or an IDE (such as Eclipse or
NetBeans).
Step 2: Compile the source codes (.java) into Java portable bytecodes (.class) using the JDK compiler
("javac"). IDE (such as Eclipse or NetBeans) compiles the source codes automatically while they are
entered.
Step 3: Run the compiled bytecodes (.class) with the input to produce the desired output, using the Java
Runtime ("java").
We have a Java program to demonstrate three basic programming constructs: sequential, loop,
and conditional statement and the runtime sequence of the program:
//Sum the odd numbers and the even numbers from a lowerbound to an upperbound
public class OddEvenSum {
public static void main() {
int lowerbound = 1, upperbound = 1000, sumOdd = 0, sumEven = 0, number = lowerbound;
while (number <= upperbound) {
if (number % 2 == 0) { sumEven += number; // Same as sumEven = sumEven + number }
else { sumOdd += number; // Same as sumOdd = sumOdd + number }
number=number+1; }
System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " +
sumOdd);
System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + " is " +
sumEven);
System.out.println("The difference between the two sums is " + (sumOdd - sumEven)); }}
Comments are used to document and explain codes and program logic. Comments are not programming
statements and are ignored by the compiler but they important for providing documentation and
explanation for others to understand your program. There are three kinds of comment in Java like a) Multi-
line Comment (begin with /* and ends with */), b) Decorative Comment (bogin with /** and end with */), c)
Single line Comment (begins with //)
Statement: A programming statement is smallest independent unit in program just like a sentence in
paragraph. It performs a piece of programming action. A programming statement must be terminated by a
semi-colon (;). For example int n = 10;
Block: A block is also called construct or compound statement. It is a group of statement surrounded by
curly braces { }. All the statements inside the block is treated as single unit. Blocks are used as
the body in constructs like class, method, if-else and for-loop, which may contain multiple statements but
are treated as single unit. Empty block (no statement inside the braces) is also permitted in Java. For
example
if (mark >= 50) {
System.out.println("PASS");
System.out.println("Well Done!"); }
Formatting Source Codes: Extra white spaces are ignored and have no computational significance.
However proper indentation with tabs and blanks and extra empty lines greatly improves the readability of
program. For example the following one-line hello-world program works. But can you read and understand
the program?
public class Hello{public static void main(String[] args){System.out.println("Hello, world!");}}
By: Sourav Sengupta Page # 23
Java's convention is to place the beginning brace at the end of the line and align the ending brace with
the start of the statement. Indent each level of the body of a block by an extra 3 or 4 spaces. The
recommended Java programming style will be:
public class ClassName {
public static void main(String[] args) {
// Use empty line liberally to improve readability
statement;
statement;
if (test) { // Conditional statement
statements;
} else {
statements; } }}}
Variable
Computer programs manipulates data. A variable is used to store piece of data for processing. It is
called variable because you can change the value stored. A variable is a named space inside the memory
that is used to store data for time being. A variable has a name (or identifier),
e.g., radius, area, age, height. The name is needed to uniquely identify each variable, assign value to
variable and retrieve data stored in the variable A variable value has a type known as data type. A
variable can store value of that particular data type. It is important to take note that variable in most
programming languages is associated with type and can only store value of the particular type. For
example a int variable can store an integer value such as 123, but not real number such as 12.34, nor
texts such as "Hello". The concept of type was introduced in the early programming languages to simplify
interpretation of data made up of binary number. The type determines size and layout of data, the range
of its values, and the set of operations that can be applied. The following diagram illustrates three types of
variables: int, double and String. An int variable stores an integer (whole number). A double variable
stores a real number. A String variable stores text.
A variable is also an identifier. The rule of identifiers naming convension is applicable to a variable. It is
important to choose a name that is self-descriptive and closely reflects the meaning of the variable. For
example numberOfStudent etc. Avoid single-letter names like i, j, k, a, b, c, which is easier to type but
often meaningless. Exception are common names like x, y, z for coordinates, i for index. To use a variable
in your program you need to first "introduce" it by declaring its name and type in one of the following
syntaxes. The act of declaring a variable allocates a storage (of size capable of holding a value of the
type). Java is a "strongly type" language. A variable is declared with a type. Once the type of a variable is
declared it can only store a value belonging to this particular type. Each variable can only be declared
once. You can declare a variable anywhere inside the program, as long as it is declared before used. The
type of a variable cannot be changed inside the program.
Assigns a literal value (of the RHS) to a variable (of the LHS), e.g., x = 1; or evaluates an expression (of
the RHS) and assign the resultant value to a variable (of the LHS), e.g., x = (y + z) / 2. The syntax for
assignment statement is:
Syntax Example
// Assign the literal value (of the RHS) to
the variable (of the LHS) number = 88;
variable = literalValue;
// Evaluate the expression (RHS) and assign sum = sum + number;
the result to the variable (LHS)
variable = expression;
The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is
first evaluated to produce a resultant value (called rvalue or right-value). The rvalue is then assigned to
the variable on the left-hand-side (LHS) or lvalue. Take note that you have to first evaluate the RHS, before
assigning the resultant value to the LHS. For examples number = 8; In programming the equal
symbol '=' is known as the assignment operator. The meaning of '=' in programming is different from
Mathematics. It denotes assignment of the LHS value to the RHS variable, instead of equality of the RHS
and LHS. The RHS shall be a literal value or an expression that evaluates to a value; while the LHS must be
a variable. Note that x = x + 1 is valid (and often used) in programming. It evaluates x + 1 and assign the
By: Sourav Sengupta Page # 24
resultant value to the variable x. x = x + 1 illegal in Mathematics. While x + y = 1 is allowed in
Mathematics, it is invalid in programming (because the LHS of an assignment statement must be a
variable). Some programming languages use symbol ":=", "->" or "<-" as the assignment operator to
avoid confusion with equality.
Primitive Types
In Java, there are two broad categories of types: primitive types (e.g., int, double) and reference
types (e.g., objects and arrays). We shall describe the primitive types here and the reference types
(classes and objects) in the later chapters on "Object-Oriented Programming".
TYPE DESCRIPTION
byte Integer 8-bit signed integer
The range is [-2^7, 2^7-1] = [-128, 127]
short 16-bit signed integer
The range is [-2^15, 2^15-1] = [-32768, 32767]
int 32-bit signed integer
The range is [-2^31, 2^31-1] = [-2147483648, 2147483647] (≈9 digits)
long 64-bit signed integer
The range is [-2^63, 2^63-1] = [-9223372036854775808,
+9223372036854775807] (≈19 digits)
float Floating- 32-bit single precision floating-point number
Point (≈6-7 significant decimal digits, in the range of ±[≈10^-45, ≈10^38])
double Number 64-bit double precision floating-point number
(≈14-15 significant decimal digits, in the range of ±[≈10^-324, ≈10^308])
char Character
Represented in 16-bit Unicode '\u0000' to '\uFFFF'.
Can be treated as 16-bit unsigned integers in the range of [0, 65535] in arithmetic operations.
boolea Binary
n Takes a value of either true or false.
The size of boolean is not defined in the Java specification, but requires at least one bit.
The following diagram shows the order of implicit type-casting performed by compiler. The rule is to
promote the smaller type to a bigger type to prevent loss of precision, known as widening conversion.
Narrowing conversion requires explicit type-cast to inform the compiler that you are aware of the possible
loss of precision. Take note that char is treated as an 16-bit unsigned integer in the range of [0,
65535]. boolean value cannot be type-casted (i.e., converted to non-boolean).
Suppose that you want to find the average (in double) of the integers between 1 and 100. Study the
following codes:
public class Sum1To100 { public static void main(String[] args) {
int sum = 0;
double average; int number = 1;
while (number <= 100) {
sum += number; // Final sum is int 5050
++number; }
average = sum / 100; // Won't work (average = 50.0 instead of 50.5)
System.out.println("Average is " + average); // Average is 50.0}}
This is because both the sum and 100 are int. The result of division is an int, which is then implicitly casted
to double and assign to the doublevariable average. To get the correct answer, you can do either:
average = (double)sum / 100; // Cast sum from int to double before division
average = sum / (double)100; // Cast 100 from int to double before division
average = sum / 100.0; average = (double)(sum / 100); // Won't work. why?
Compound Assignment Operators: Besides the usual simple assignment operator '=' described earlier,
Java also provides the so-called compound assignment operators as listed:
Operation Description Usage Example
= Assignment var = expr x = 5;
Assign the value of the LHS to the variable at the
By: Sourav Sengupta Page # 25
RHS
+= Compound addition and assignment var += expr x += 5;
same same as x = x +
as var = var +expr 5
-= Compound subtraction and assignment var -= expr x -= 5;
same as var = var - same as x = x -
expr 5
*= Compound multiplication and assignment var *= expr x *= 5;
same same as x = x *
as var = var *expr 5
/= Compound division and assignment var /= expr x /= 5;
same same as x = x /
as var = var /expr 5
%= Compound remainder (modulus) and assignment var %= expr x %= 5;
same same as x = x %
as var = var %expr 5
Increment/Decrement: Java supports these unary arithmetic operators: increment '++' and
decrement '--' for all numeric primitive types (byte, short, char, int, long,float and double, except boolean).
Operator Description Example
++ Increment the value of the variable int x = 5;
by 1 x++; ++x;
same as x += 1 or x = x + 1
-- Decrement the value of the variable int y = 6;
by 1 y--; --x;
same as x -= 1 or x = x - 1
The increment (++) and decrement (--) operate on its operand and store the result back to its operand.
For example, x++ retrieves x, increment and stores the result back to x. Writing x = x++ is a logical
error!! Unlike other unary operator (such as negate '-') which promotes byte, short and char to int, the
increment and decrement do not promote its operand (because there is no such need). The
increment/decrement unary operator can be placed before the operand (prefix), or after the operands
(postfix), which affects its resultant value. If these operators are used by themselves (e.g., i++ or ++i),
the outcomes are the same for pre- and post-operators, because the resultant values are discarded. If '++'
or '--' involves another operation (e.g., y=x++ or y=++x), then pre- or post-order is important to specify
the order of the two operations:
Operator Description Example
++var Pre-Increment y = ++x; same as x=x+1; y=x;
Increment var, then use the new value
of var
var++ Post-Increment y = x++; same as oldX=x; x=x+1;
Use the old value of var, then y=oldX;
increment var
--var Pre-Decrement y = --x; same as x=x-1; y=x;
var-- Post-Decrement y = x--; same as oldX=x; x=x-1;
y=oldX;
Relational and Logical Operators: Very often, you need to compare two values before deciding on the
action to be taken, e.g. if mark is more than or equals to 50, print "PASS!". Java provides six comparison
operators (or relational operators):
Operator Description Usage Example (x=5,
y=8)
== Equal to expr1 == exp (x == y) → false
r2
!= Not Equal to expr1 != expr (x != y) → true
2
> Greater than expr1 > expr2 (x > y) → false
>= Greater than or equal expr1 >= exp (x >= 5) → true
to r2
< Less than expr1 < expr2 (y < 8) → false
<= Less than or equal to expr1 >= exp (y <= 8) → true
r2
In Java, these comparison operations returns a boolean value of either true or false. Each comparison
operation involves two operands, e.g., x <= 100. It is invalid to write 1 < x < 100 in programming.
Instead, you need to break out the two comparison operations x > 1, x < 100, and join with with a logical
AND operator, i.e., (x > 1) && (x < 100), where && denotes AND operator. Java provides four logical
operators, which operate on boolean operands only, in descending order of precedences, as follows:
Operator Description Usage
! Logical NOT !booleanExpr
By: Sourav Sengupta Page # 26
^ Logical XOR booleanExpr1 ^ booleanExpr
2
&& Logical AND booleanExpr1 && booleanEx
pr2
|| Logical OR booleanExpr1 || booleanExpr
2
Function/ Method
Methods of Java is collection of statements that performs specific task and returns result to its caller
function. Java method can also perform specific task without returning anything. This is called void
method. Method allow us to reuse same code without retyping it. Every method must be part of class. A
method or function is used to expose behavior of object. When you call System.out.println() method, the
system actually executes several statements in order to display a message on console. The advantage of
using method is code reusability and code optimization. In general a method has the following syntax:
<access_modifier> <return_type> <method_name>(parameter)
{Body of method}
A method definition consists of method header and body. Here are all the parts of method:
Modifier: Modifier: It defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 types of access specifiers like a) public: It is accessible in all classes in your
application, b) protected: It is accessible within the class in which it is defined and in its subclass, c)
private: It is accessible only within the class in which it is defined, d) default: It is declared/defined
without using any modifier. It is accessible within same class and package within which its class is defined.
Return Type: A method may return a value. The return-value-type is the data type of the value what a
method returns. Some methods perform the desired operations without returning a value. In this case the
returnValueType is void.
Method Name: This is the actual name of the method. The method name and the parameter list together
constitute the method signature.
Parameter: A parameter is like a placeholder. When a method is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a method. Parameters are optional; that is, a method may
contain no parameters.
Body: : it is enclosed between braces. The code you need to be executed to perform your intended
operations. It is Optional in syntax.
Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).
It is Optional in syntax. The declaration of a method looks like following:
There are two types of methods in Java which are:
1) Predefined Method: In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
2) User-defined Method: The method written by the user or programmer is known as a user-defined
method. These methods are modified according to the requirement.
There are two ways to create a method in Java which are:
1) Instance Method: Access the instance data using the object name.Declared inside a class. The syntax is:
void method_name(){ body // instance area }
2) Static Method: Access the static data using class name. Declared inside class with static keyword. The
syntax is:
static void method_name(){ body // static area }
Method Signature: It consists of the method name and a parameter list (number of parameters, type
of the parameters, and order of the parameters). The return type and exceptions are not considered as
part of it. Method Signature of the above function: max(int x, int y) Number of parameters is 2, Type of
parameter is int. A method name is typically a single word that should be a verb in lowercase or multi-
word that begins with verb in lowercase followed by an adjective noun. After the first word the first letter
of each word should be capitalized. While defining a method remember that the method name must be
By: Sourav Sengupta Page # 27
a verb and start with a lowercase letter. If the method name has more than two words, the first name
must be a verb followed by an adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example, findSum, computeMax, setX, and getX.
The method needs to be called for use its functionality. There can be three situations when a method is
called:
A method returns to the code that invoked it when: It completes all the statements in the method, It
reaches a return statement. For example:
import java.io.*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b)
{ sum = a + b;
return sum; }}
class GFG
{ public static void main(String[] args)
{ Addition add = new Addition();
int s = add.addTwoInt(1, 2);
System.out.println("Sum of two integer values :" + s); }}
Output
Sum of two integer values :3
import java.io.*;
class Test {
public static int i = 0;
Test()
{ i++; }
public static int get()
{ return i; }
public int m1()
{ System.out.println( "Inside the method m1 by object of GFG class");
this.m2();
return 1; }
public void m2()
{ System.out.println( "In method m2 came from method m1");}}
class GFG
{ public static void main(String[] args)
{ Test obj = new Test();
int i = obj.m1();
System.out.println("Control returned after method m1 :" + i);
int no_of_objects = Test.get();
System.out.print( "No of instances created till now : ");
System.out.println(no_of_objects);}}
Output
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1
The control flow of the above program is as follows:
By: Sourav Sengupta Page # 28
Two parties are involved in method: a caller, who calls the method and the method to be called. The caller
passes arguments to called method. The method receives these arguments, performs operations defined
in method's body, and returns the result back to caller.
Suppose we need to evaluate area of circle many times. It is better to write method called getArea() and
re-use it when needed.
public class MethodTest {
public static void main(String[] args) {
double radius1 = 1.1, area1, area2; area1 = getArea(radius1); // Call method getArea()
System.out.println("area 1 is " + area1);
area2 = getArea(2.2); System.out.println("area 2 is " + area2);}
public static double getArea(double radius) { return radius * radius * Math.PI; }}
Output:
area 1 is 3.8013271108436504
area 2 is 15.205308443374602
In the above example, a reusable method called getArea() is defined, which receives a parameter
in double from the caller, performs the calculation, and return a double result to the caller. In the main(),
we invoke getArea() methods thrice, each time with a different parameter. The syntax for method
definition is as follows:
public static returnValueType methodName ( arg-1-type arg-1, arg-2-type arg-2,... )
{ body ; }
Method Naming Convention
Method name shall be a verb comprising one or more words. The first word is in lowercase while rest are
initial-capitalized. For example, getArea(). Inside method body you could use return statement to return a
value back to caller. Suppose you need a method to perform certain action without need to return value to
caller, you can declare its return-value type as void. If there is no return statement the entire body will be
executed and control returns to caller. The main() is a method with void return type. When an argument of
primitive type is pass into a method, a copy is created and passed into the method. The invoked method
works on thecloned copy, and cannot modify the original copy. This is known as pass-by-value.
Memory Allocation for Methods Call
Methods calls are implemented through a stack. Whenever a method is called a stack frame is created
within the stack area and after that, the arguments passed to and the local variables and value to be
returned by this called method are stored in this stack frame and when execution of the called method is
finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top
of the stack which is adjusted accordingly. Example: pseudo-code for implementing methods
public class Example {
private int number;
private String name;
public int getNumber() { return number; }
public String getName() { return name; }
public void setNumber(int number)
{ this.number = number; }
public void setName(String name) { this.name = name; }
public void printDetails()
{ System.out.println("Number: " + number);
System.out.println("Name: " + name); }}
Use the methods in another part of the code Example example = new Example();
example.setNumber(123); example.setName("GFG Write"); example.printDetails();
There are several advantages to using methods in Java, including:
Reusability: Methods allow you to write code once and use it many times, making your code more
modular and easier to maintain.
Abstraction: Methods allow you to abstract away complex logic and provide a simple interface for others
to use. This makes your code more readable and easier to understand.
Improved readability: By breaking up your code into smaller, well-named methods, you can make your
code more readable and easier to understand.
Encapsulation: Methods allow you to encapsulate complex logic and data, making it easier to manage
and maintain.
By: Sourav Sengupta Page # 29
Separation of concerns: By using methods, you can separate different parts of your code and assign
different responsibilities to different methods, improving the structure and organization of your code.
Improved modularity: Methods allow you to break up your code into smaller, more manageable units,
improving the modularity of your code.
Improved testability: By breaking up your code into smaller, more manageable units, you can make it
easier to test and debug your code.
Improved performance: By organizing your code into well-structured methods, you can improve
performance by reducing the amount of code that needs to be executed and by making it easier to cache
and optimize your code.
Method Overriding
During inheritance if subclass creates method similar as declared in parent then it is known as method
overriding or function overriding. In other words if subclass provides specific implementation of a method
that has been declared by one of its parent class then it implies method overriding. It is used to provide
specific implementation of a method which is already provided by its superclass. Method overriding is
used for runtime polymorphism whereas method overloading implies compile time polymorphism.
Consider a scenario where Bank is a class that provides functionality to get rate of interest. However, the
rate of interest varies from bank to bank.
class Bank
{ int getRateOfInterest(){return 0;} }
class SBI extends Bank
{ int getRateOfInterest(){return 8;} }
class ICICI extends Bank
{int getRateOfInterest(){return 7;} }
public class call
{ void main()
{ ICICI ob = new ICICI();
System.out.println(ob.getRateOfInterest()); }}
Dynamic Method Dispatch or runtime polymorphism is another feature of Java. Method overriding is
a process by using which Java supports runtime polymorphism. Dynamic method dispatch is a mechanism
by which a call to an overridden method is resolved at run time. When an overridden method is called by
superclass Java determines which version (superclass/subclasses) of method is to be executed based upon
type of object being referred at time of call. Thus this determination is made at run time. A superclass
reference variable can refer to subclass object. This is also known as upcasting.
Java uses this fact to resolve calls to overridden methods at run time. Therefore, if a superclass contains a
method that is overridden by a subclass, then when different types of objects are referred to through a
superclass reference variable, different versions of the method are executed. Here is an example that
illustrates dynamic method dispatch.
class A
{ void m1()
{ System.out.println("Inside A's m1 method"); }}
class B extends A
{ // overriding m1()
void m1()
By: Sourav Sengupta Page # 30
{ System.out.println("Inside B's m1 method"); }}
class C extends A
{ // overriding m1()
void m1()
{ System.out.println("Inside C's m1 method"); }}
// Driver class
class Dispatch
{ public static void main(String args[])
{ // object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1(); } }
Therefore if a superclass contains method that is overridden by subclass, then when different types of
objects are referred to through superclass reference variable, different versions of the method are
executed. For eample:
class A
{ void m1()
{ System.out.println("A Class M1 Function"); }}
class B extends A
{ void m1()
{ System.out.println("B Class M1 Function");; }}
public class Dispatch
{ public static void main()
{ A oa = new A(); //object of A class
B ob = new B(); // object of B class
A ref;
ref = oa; // ref refers to an A object
ref.m1();
ref = ob; // ref refers to a B object
ref.m1(); }}
Advantages: a) Dynamic method dispatch allows Java to support overriding of methods which implement
runtime polymorphism. b) It allows a class to specify methods that will be common to all of its derivatives,
while allowing subclasses to define specific implementation of methods c) It allow subclasses to add
specific methods to define specific implementation of some.
Constructor
Constructor is a member function with a name same as that of the class name. That means name
of constructor function has to be similar with name of class where in it resides. The advantage of
constructor is that it runs automatically when object of class is created. We use constructor to initialize
data members or instance variables of a class. Every class has a constructor. If we do not explicitly write a
constructor for a class, the Java compiler builds a default constructor for that class. Each time a new object
is created one constructor gets invoked. The constructor are always declared and defined under the public
specifier. A constructor does not return any value and that’s why it does not have any return data type.
There are two types of constructor available. They are Parameterized and Non Parameterized
constructor. The constructor function which does not accept or posses any arguments or parameter during
execution time is known as non parameterized constructor. The constructor which has arguments or can
accept data during its runtime from object creation module is known as parameterized constructor. A
constructor can not be called or invoked like a user defined function. It executes or runs automatically as
soon as the object of the class is created.
If there is no constructor present in a class then the compiler automatically generates a
constructor. The concept Polymorphism is applicable in case of constructor also like other user defined sub
functions of Java. The act of defining more than one constructor function is known as constructor
By: Sourav Sengupta Page # 31
overloading. Parameterized constructor: A constructor with arguments is termed as parameterized
constructor. Parameterized constructors can be used to set the initial state of objects of a class according
to the requirements of a program.
Parameterized constructors can be used to set the initial state of objects according to the
requirements of the program/user. The arguments of a parameterized constructor can be used to set
either the environment information or the data elements of the object under creation. Every time an
instance of a class created, one of its constructors is invoked. Thus if a function has to create instances of
a class then the constructor of the class must be accessible in the scope of the function. In other words the
visibility of instances of a class is controlled by the accessibility of its constructors.
public class Puppy
{ public Puppy() { } // This constructor has no parameter.
public Puppy(String name){ }// This constructor has one parameter, name. }
public class MyClass
{private
int roll; String name; double fees;
public MyClass() //Constructor
{roll=0;
name=" "; fees=0.0;
System.out.println("Constructor has Activated");}
public void show()
{System.out.println("Name = "+name);
System.out.println("Roll = "+roll);
System.out.println("Fees = "+fees);}
public static void main()
{MyClass Obj = new MyClass(); //creating objects
Obj.show(); // calling sub functions. It will show the initialised values of the variables. }}
By: Sourav Sengupta Page # 32