Java Tutorials Part 1
Java Tutorials Part 1
History of java:
Java is a high-level programming [Link] called OAK.
Released By: Sun Microsystems (now it is subsidiary of Oracle Corporation)
In Year: 1995 (actually OAK was released in year 1991 but it got failed then again it was
launched with a new name “java” in spring of 1995)
Author: James Gosling, Mike Sheridan, Chris Warth, Ed Frank & Patrick Naughton
Designed for: Consumer goods
4. clicking will open another dialog box. in that newly opened dialog box you will find list of user
variables as well as system variables. you will be able to edit system variable only if you are
In list of user variables check if there exist a variable path, if not click on new button provided
below list of user variables, it will open a dialog box.
● Enter “path” in variable name text box
● Paste java installation path that you got from step 1 in value
now go to start menu click on the run button type cmd in text box then click on run button,
console will be appeared in front of you. Now type javac then press enter. you will get list of all
options along with their description.
Download java tar file according to your need (32 bit or 64 bit).
C 1. Human friendly
2. Uses procedural programming
approach that make code cleaner but
not suitable for very large programs
(like greater than 75,000)
3. Machine dependent code
After looking at the journey of programming from binary to C++ we have solved all problems like
(human friendliness of language, managing large code etc) but Machine Dependant Code is
still an issue, that is addressed by java.
In network, basically two broad categories of objects are transmitted between server and
personal computer
1. Passive information
2. Dynamic active programs
Passive means that is not executing. like when you are viewing a mail you are reading a
passive information, or you are just downloading a setup of a software it is also a passive data
until you do not install it.
Bytecode:
Whenever someone compile a java program its output is not an executable code it is a
intermediate highly optimized set of instruction that is executed by java runtime system, known
as JVM (Java virtual machine), that intermediate set of instruction is called Bytecode.
Portability:-
Java achieve portability with the help of bytecode. because bytecode runs on JVM so only the
JVM needs to be implemented for each platform. Once the run-time package (that is JVM)
exists for a given system, any Java program can run on it. Remember, although the details of
the JVM will differ from platform to platform, all interpret the same Java bytecode. That feature
make java an Architecture neutral language.
The Java environment itself is readily portable to new architectures and operating systems. The
Java compiler is written in Java. The Java run-time system is written in ANSI C with a clean
portability boundary which is essentially POSIX-compliant. There are no "implementation-
dependent" notes in the Java language specification.
Security:-
Now we are talking about security aspect. java provide us a facility to create dynamic, self
executing programs for web, called applet. you can consider an applet like a program that is
downloaded like other component of web page (i.e. images, text etc.). but that program runs on
java compatible web browser. Java compatible web browser allow that applet to just access
java execution environment, not other parts of computers. you can understand it very much like
there exists a firewall (The term firewall originally referred to a wall intended to confine a fire
within a building) between your applet and other part of your computer. that firewall prevent
applet to access other part of your computer like file system thus potential security risk has been
overcome.
JVM is an interpreter for bytecode. means it convert bytecode into executable code line by line
remember it is not possible to compile an entire Java program into executable code all at once,
because Java performs various run-time checks that can be done only at run time. hence
improve security.
Also it has bytecode verifier, that acts as a sort of gatekeeper: it ensures that code passed to
1. Simple
Java inherits the C/C++ syntax and many of the object-oriented features of C++,Also, some of
the more confusing concepts from C++ are either left out of Java or implemented in a cleaner,
more approachable manner. so if you are familiar with C/C++ then it will take a little efforts to
learn java.
A common source of complexity in many C and C++ applications is storage management: the
allocation and freeing of memory, java provides automatic garbage collection, thereby
simplifying the task of programmer.
2. Secure
3. portable
we have already discussed above.
4. Object Oriented
Java is fundamentally based on the OOP notions of classes and objects Java uses a formal
OOP type system that must be obeyed at compile-time and run-time. This is helpful for larger
projects, where the structure helps keep the various parts consistent
5. Robust
Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime)
checking, and eliminating situations that are error prone.
Java is a strongly typed language, one of the advantages of a strongly typed language is that it
Java has a pointer model that eliminates the possibility of overwriting memory and corrupting
data. Instead of pointer arithmetic, Java has true arrays. This allows subscript checking to be
performed. also cannot gain unauthorized access to memory, which could happen in C or C++.
Also garbage collector is responsible for managing memory means laking of memory due to
mismanagement is avoided.
Exception handling is another feature in Java that makes for more robust programs. An
exception is a signal that some sort of exceptional condition, such as a "file not found" error, has
occurred. Using Exception handling, you can group all of your error handling code in one place,
which greatly simplifies the task of error handling and recovery.
6. Multithreaded
Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.
7. Architectural Neutral
Java was designed to support applications on networks. In general, networks are composed of
a variety of systems with a variety of CPU and operating system architectures. Java follows
“Write once; run anywhere, any time, forever.”
paradigm. Means Any machine (architecture) that has a JVM running on it, can execute any
Java program that has been compiled into byte codes.
Architecture neutrality is just one part of a truly portable system.
8. Interpreted
Java bytecode are translated on the fly to native machine instructions (interpreted) and not
stored anywhere. And since linking is a more incremental and lightweight process, the
development process can be much more rapid and exploratory.
9. High Performance
Java bytecode was carefully designed so that it would be easy to translate directly into native
machine code for very high performance by using a just-in-time compiler. Java run-time systems
that provide this feature lose none of the benefits of the platform-independent code. “High-
performance cross-platform” is no longer an oxymoron. also java performance has gotten a lot
better with aggressive just-in-time-compiler (JIT) techniques (the HotSpot project). Java
performance is often similar to the speed of C in case of JIT.
Java supports multi-threading that help to improve resource optimization and achieve
concurrency means you program is able to do more than one task in a single execution.
10. Distributed
Java also support remote method invocation (RMI). This feature enables a program to invoke
methods across a network.
11. Dynamic
Although the Java compiler is strict in its compile-time static checking, the language and run-
time system are dynamic in their linking stages. Classes are linked only as needed. New code
modules can be linked in on demand from a variety of sources, even from sources across a
network.
Also java programs carry with them substantial amounts of run time type information that is
used to verify and resolve accessed to object at run time. This makes it possible to dynamically
link code in a safe and expedient manner. This is crucial to the robustness of the java
environment in which small fragments of bytecode may be dynamically updates in a running
system.
Unit-II
The Object Oriented Programming Concept
Let us consider an example of a fan that might be available over your head now :P. take a look
at it and note down some attribute that describe about it like
1. No. of blades
2. company name
3. Color
4. On/Off
5. weight
6. Rotation per minute
and talking about Operations that changes the description of these components.
1. Turning it on from off and vice-versa
2. Changing its color
3. Making it light in weight
4. Increasing/Decreasing rotation per minute
Now take another example of mobile, that you might have in your hand now :P. and note down
some component that describe about it like
1. Weight
2. Price
and talking about Operations that changes the description of these components.
1. Turning it on from off and vice-versa.
2. Turning its FM on from off and vice-versa.
3. Turning its Blue-tooth on from off and vice-versa.
4. Changing its color etc
In the example of fan and mobile that we have discussed above, we are using some attribute to
describe a real world entity these attributes are called states. Or we can say any attribute that
describe about a real word entity is called state.
And we are also discussing operation that make changes in the state of the real world entity
these operations are known as behaviors. Or we can say any operation that make changes in
the state of an real world thing is called behavior.
Now again coming back to our example and observe following scenario.
Fan that you were observing is same as all other fan that have same model no and
manufactured by same company in the terms of state and behavior?
Again about mobile that you were observing is same as all other mobile that have same model
no and manufactured by same company in the terms of state and behavior?
but is it a coincidence that all mobiles and fans that are manufactured by same company and
having same model number are identical??
Means we can say that before manufacturing these mobiles and fans, someone have already
define their states and behavior, say on a document, and that document serve as a blueprint for
all mobiles and fans.
Also that document itself is a passive entity that is just defining states and behaviors in a
document does not create a mobile or fan, while we have make a real world entity by following
that blueprint. that real world entity is called object while the document that serve as a blueprint
for that real world object is called class.
Class
A Class is the blueprint from which individual objects are created. It is a passive entity. It is also
knows as user defined data type.
Abstraction
Now again come back to the example of mobile. So far we have seen it as an object that have
its own state and behavior. Now consider a scenario, you are sitting in a garden and feeling
bored (might be because you are waiting for someone), you took out mobile from your pocket
and start traversing gallery then selecting a song and start it listening.
And now come to our another example that is about fan. In the season of summer you are
coming to home from office/college and feeling tired, then you go to your drying room, switching
on fan, sitting comfortably on chair and start enjoying cool air.
In both situation that we have discussed above, do you need to bother about how mobile phone
play songs or how a fan rotates?
Simple answer: no, you are able to use an object even you don’t have to bother about its
internal working. You just need to bother about how to use that particular object. so you are
using an object without knowing its internal mechanism. That is called abstraction.
Encapsulation
General meaning of encapsulation is
“To completely cover something especially so that it will not touch anything else.”
The wrapping up of data and its associated function together in a single unit (called class) and
keeps both safe from outside interference and misuse is known as encapsulation.
Encapsulation works as a wrapper that protect data and code from arbitrary access by other
code defined outside the wrapper.
Encapsulation is achieved with the help of access specifiers. So whenever we want any
property of an object (constants, variables, or method) to be revealed to others, we just have to
set it as a public property and when we don't want it to be, we set it as private.
Inheritance:
It is the process by which one object acquire the property of another object. It is used to
implement concept of hierarchical classification.
(A Simple Hierarchy)
So with the help of inheritance, A professional course student have all attributes of student as
well as of human. So attributes of a professional course student are
Name, Height, Weight, Age, Gender, Roll no, Institution name, Semester, Year and University.
Polymorphism:
Taking a simple example of your mobile phone. Every mobile have call button (having green
icon of phone) with it now consider observe reaction of pressing call button in following
situations
1. Let say you have an incoming call on your phone. you are pressing call button, now you
can talk to person who have make call to you.
2. Let say you have received a message and you are reading it, at the time of reading
press call button you will get list of all numbers that are in message as well as mobile
number of sender.
3. Let say you are browsing your dialled number list and on when your control is on a
particular number again press call button, now you are calling on that particular number.
From the above discussion we can make a simple observation that applying same behavior
(that is, pressing call button)on an object (that is, mobile) react differently in different situation.
That feature is known as polymorphism.
and hit enter, following step 2 will open an editor in front of you with file name [Link]
When you execute the Java interpreter as just shown, you are actually specifying the name of
It will automatically search for a file by that name that has the .class extension. If it finds the file,
it will execute the code contained in the specified class.
then
class A{
This line uses the keyword class to declare that a new class is being defined. A is an identifier
that is the name of the class.
{ opening curly brace of the class
The entire class definition, including all of its members, will be between the opening curly brace
({) and the closing curly brace (}). The use of the curly braces in Java is identical to the way they
are used in C, C++, and C#.
This is the line at which the program will begin executing. Just like C/C++ all Java applications
begin execution by calling main( ).
public means that function is visible to all over.
static means method main can be called without creating an object of encapsulating class.
void tell the compiler that main function will not return any value
In main( ), there is only one parameter, String args[ ] declares a parameter named args, which
is an array of instances of the class String. you might choose other name instead of args.
{ opening curly brace of main method
finally two consecutive closing curly braces one for closing main method and one for closing
class A.
Comments In Java:
Comments are optional part of program that are written by developer to specify objective of a
program or module in simple human friendly language. Comments are transparent to java
compiler means compiler simply ignores all comments written in a code.
Similar to C/C++, java supports two styles of comments that are as follow
1. Single line comment:- Such type of comment are used when our comment have length
limited to just one line. To insert a single line comment, simply start comment with two
consecutive slashes (/). Example
// This is a single line comment.
2. Multi line comment:- Such type of comment are used when our comment have length
more than one line. To insert a multi line comment, simply start comment with a slash (/)
and asterisk sign (*), and after completing comment just place an asterisk (*) sign and
slash (/) Example
/* I am multi line comment.
Comments are transparent to compiler
*/
Unit-III
Data type, variables and Type conversion
Data type:
A variable's data type determines values it may contain and operations that may be performed
on it.
Java supports both user defined data type (e.g. class) as well as primitive data type. A primitive
type is predefined by the language and is named by a reserved keyword.
In that chapter, we will discuss about primitive data type. java basically support 8 kind of
primitive data types.
for the sake of convenience, out of these 8 primitive data types, first 4 that are (byte, short, int
and long) are placed in a common group that is integer because these four data type hold a
whole numbers.
next 2 (that are float, double) are placed in a group that is floating point numbers because they
hold floating point numbers.
char is used to store characters like letters, numbers and special symbols. it is placed in a group
that is Character
finally boolean is used to store true/false value. it is placed in a group that is Boolean.
Integer
byte:
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128
and a maximum value of 127 (inclusive).
example: byte b;
here b is name of variable that is byte type.
byte c = 1;
here c is name of variable that is byte type and having initial value 1.
short:
The short data type is a 16-bit signed two's complement integer. It has a minimum value of -
32,768 and a maximum value of 32,767 (inclusive).
example: short s;
here s is name of variable that is short type.
short t = 150;
here t is name of variable that is short type and having initial value 150.
int:
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)
The int type is the most versatile and efficient type, and it should be used most of the time when
you want to create a number for counting or indexing arrays or doing integer math. It may seem
that using short or byte will save space, but there is no guarantee that Java won’t promote those
types to int internally anyway.
example: int i;
here i is name of variable that is int type.
int j = 150000;
here j is name of variable that is int type and having initial value 150000.
double:
The double data type is a double-precision 64-bit IEEE 754 floating point. having approximate
range 4.9e–324 to 1.8e+308. float are useful when you require a large degree of precision.
Optionally d or D can be appended to value that is assigned to a double variable.
double prints maximum 13 digit next to decimal point.
example: double d;
here d is name of variable that is double type.
double d1 = 1.5;
here d1 is name of variable that is float type and having initial value 1.5.
Character
char:
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or
0) and a maximum value of '\uffff' (or 65,535 inclusive).
Boolean
boolean:
The boolean data type has only two possible values: true and false. Use this data type for
simple flags that track true/false conditions.
example: boolean b;
here b is name of variable that is boolean type.
boolean b1 = true;
here b1 is name of variable that is float type and having initial value true.
An Example:
class DataTypeDemo{
public static void main(String a[]){
byte b = 1;
short s = 300;
int i = 123123;
long l = 65467890987L;
float f = 3.1416256f;
double d = 1222.0235859256566;
char c = 'a';
boolean bln = true;
[Link]("byte b is "+b);
[Link]("short s is "+s);
[Link]("int i is "+i);
[Link]("long l is "+l);
[Link]("float f is "+f);
[Link]("double d is "+d);
[Link]("char c is "+c);
byte b is 1
Literals:
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.
Integer:
Any whole number value is an integer literal. An integer literal is of type long if it ends with the
letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L
because the lower case letter l is hard to distinguish from the digit 1.
There are other bases which can be used in integer literals.
● Binary (base 2): Binary digits are denoted in Java by a leading zero- b(0b or 0B). (only
supported in Java SE 7 and later)
● Octal (base eight) : Octal values are denoted in Java by a leading zero.
● Hexadecimal (base 16) : You signify a hexadecimal constant with a leading zero-x, (0x
or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
The floating point types (float and double) can also be expressed using E or e (for scientific
notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by
convention is omitted).
Character Literals:
Literals of types char may contain any Unicode (UTF-16) [Link] your editor and file
system allow it, you can use such characters directly in your code. If not, you can use a
"Unicode escape" such as '\u0063' for alphabet c. Always use 'single quotes' for char literals.
An Example of literals
class LiteralDemo{
public static void main(String a[]){
int decVal = 26;//decimal literal
int hexVal = 0x1a;//hexadecimal literal
int octVal = 012;//octal literal
[Link]("d1 is "+d1);
[Link]("d2 is "+d2);
[Link]("f1 is "+f1);
[Link]("cc is "+cc);
[Link]("cd is "+cd);
}
}
decVal is 26
octVal is 10
hexVal is 26
d1 is 123.4
d2 is 123.4
f1 is 123.4
cc is c
cd is d
An Example:
class ScopeDemo{
public static void main(String a[]){
int x = 10;
if(x == 10){ //starting a new block
int y = 1000;
[Link](“x is ” + x + “ and y is ” + y);
}//block ends here
//y = 10; // error! scope of has over
[Link](“x is ” + x);
}
}
As per the discussion x is visible inside nested block while y is not accessible outside its block.
variables can be declared at any point, but are valid only after they are declared. Thus, if you
define a variable at the start of a method, it is available to all of the code within that method.
if you are declaring a variable after using it, compiler will report an error.
An Example:
class DeclarationDemo{
public static void main(String a[]){
[Link](“x is ” + x);// error
int x = 10;
}
}
in the code snippet given above, we are trying to use x before it is declared. hence an error.
Similar to C/C++, blocks can be nested in java , you cannot declare a variable to have the same
name as one in an outer scope.
An Example:
Dynamic Initialization:
Dynamic Initialization can be defined as the dynamic operation that allows variables to be
initialized dynamically using any expression valid at the time of the variable declaration.
An Example:
class DynamicInit{
public static void main(String a[]){
int a=5;
int b=2;
int c=a*a+b*b;
[Link]("value of c is "+c);
}
}
value of c is 29
In the above program we have three variables a,b and [Link] has been declared as ' int
'.Variable a and b are declared and provided values on declaration whereas the variable c has
been assigned a expression to evaluate and store its [Link] is done through dynamic
evaluation.
when the two conditions takes place then it is called “widening conversion”.
Widening conversion is take place in the following cases:-
1. byte to short, int, long, float, or double
Narrowing conversion:-
when your source type is larger than the destination type or when your variable is incompatible
with the data to be assigned then you have to explicitly make the value narrower so that it can fit
into the target type.
To perform conversion between two incompatible types, you must use a cast. A cast is simply
an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
An Example:
class NarrowConversion {
public static void main(String[] args) {
int i = 100, j = 200;
//short s = i it’s an error because short is smaller then int
short s = (short) i;
byte b = (byte) j;
char ch = (char) i;
[Link]("i is " + i + " s is " + s + " b is " + b + “ ch is ” + ch);
}
}
in the example given above we have created two variable i and j. if we are trying to assign i to s
then compiler will report us error because short is smaller then int. to assign value of an integer
variable to a short variable we have to type cast it.
In the next statement we have casted value of int to byte due to same reason explained above.
and when we are assigning value of an integer to a char then due to smaller size as well as
incompatibility we have typecast then.
An Example:
class Truncation{
public static void main(String args[]) {
byte b;
int i = 260;
double d = 330.14;
After discussing widening and narrowing conversion, we have found one speciality of java that
is whenever you are assigning a value to a variable, java performs compatibility of assigned
value to the target type and generate proper error message if found them incompatible. We can
say java avoid accidental assignment of mismatching data to variable, that is why java is know
as Strongly typed language. as checking takes place whenever you are passing argument to
functions and assigning expression’s result to a variable.
Unit-IV
Operators
So far we have learned about declaring, initializing variables in java. Now its time to know about
operation that you can perform over these variable. In that chapter we will discuss about all
operator that java provides you with example.
Arithmetic operators:
Java provides following arithmetic operators:
Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulus Assignment
An Example:
class BasicArithmetric {
public static void main(String args[]) {
int ia = 10 + 10;
int ib = ia - 10;
int ic = ib * 10;
int id = ic/ib;
double da = 1 + 1;
double db = da - 1;
double dc = db * 1;
double dd = dc/db;
Integer Addition is 20
Integer Subtraction is 10
Integer Multiplication is 100
Integer Division is 10
both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.
An Example:
class ArithmeticAssign {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 30;
a+=5;
[Link]("Addition Assignment: a is " + a);
b-=5;
[Link]("Subtraction Assignment: b is " + b);
Addition Assignment: a is 15
Subtraction Assignment: b is 15
Multiplication Assignment: c is 90
Division Assignment: b is 5
Modulus Assignment: c is 10
An Example:
class PrePost {
int b = a++;
[Link]("a is " + a + " b is " + b);
int c = --a;
[Link]("a is " + a + " c is " + c);
b = a--;
[Link]("a is " + a + " b is " + b);
c = ++a;
[Link]("a is " + a + " c is " + c);
}
}
a is 10
a is 11 b is 10
a is 10 c is 10
a is 9 b is 10
a is 10 c is 10
Relational Operators:
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
Java provide following arithmetic operators:
Operator Result
== Equal To
!= Not equal to
> Greater Than
< Less than
>= Greater than or equal to
<= Less than or equal to
● All data types in java can be compared using equaity test (==) and unequaity (!=) test.
● Only numeric type can be compared using rest of the relational operators. (i.e. <, <=, >,
>=)
● Output of the relational expression is always a boolean value.
An Example:
class Relational {
public static void main(String args[]) {
int a = 4;
int b = 8;
boolean rslt = a < b; //expression will preduce a boolean result
if(rslt){
[Link]("a is less than b");
}else{
[Link]("a is greater than or greater than b");
}
}
}
a is less than b
one more thing to remember: in C/C++, you often write code like
int i = 10;
if(i){
cout<<”i is nonzero”;
Bitwise Operators:
Java's bitwise operators operate on individual bits of operand. Operand may be integer, short,
long, byte or character type.
before moving into the depth of bitwise operators we must have understanding about how java
stores integer. As all we know that for computer everything in binary (i.e. 0 and 1). numbers are
also represented with the help of their corresponding binary notation.
let say you to store 6 in a variable of byte type. binary representation of 6 is 110 that requires 3
bits of storage. our byte variable occupy 8 bits hence will store it as 00000110, means padding
remaining 5 bits with 0.
Negative Numbers are stored with the help of two’s complement representation. if you want to
store any negative number in memory go through following steps:
1. Find out binary representation of corresponding positive number.
2. Find out one’s complement of binary representation that you have from step one. simply
Invert all bits of that binary representation.
3. Now add binary one to binary representation that you obtained from step 2. that’s all
result of step 3 is representation of corresponding negative number.
Operator Result
~ Bitwise unary Not
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
>>> Shift Right zero fill
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right Assignment
so a & b is
00001001 = 9
&00001110 = 14
--------------
00001000 = 8
Bitwise OR (|):
Bitwise OR produces a zero if all operands are zero. In all other cases it will produce one.
Again let say we have a variable named a of byte type stores 9. binary representation of 9 is
00001001.
Currently a = 00001001
And we have another variable named b of byte type stores 14. binary representation of 14 is
00001110.
Currently b = 00001110
so a | b is
00001001 = 9
| 00001110 = 14
--------------
00001111 = 15
so a ^ b is
00001001 = 9
^00001110 = 14
--------------
00000111 = 7
An Example:
class LeftShift {
public static void main(String args[]) {
int a = 16;
int b = (a << 1);
a is 2147483647
b is -2
An Example:
class RightShift {
public static void main(String args[]) {
int a = 32;
int b = (a >> 2);
int c = 35;
int d = (a >> 2);
a is 32
b is 8
c is 35
d is 8
Each time you shift the value to the right. It divide the value by 2 and discard the remainder.
thus you may take advantage of right shift to perform high speed division.
whenever you are shifting a value to the right, leftmost bit is filled its previous value. that is
called sign extension because that property keep sign of number unchanged.
An Example:
class RightShiftPreserve {
public static void main(String args[]) {
int a = -8;
int b = (a >> 2);
a is -8
b is -2
An Example:
class UnsignedRightShift {
public static void main(String args[]) {
int c = -1;
int d = (c >>> 1);
c is -1
d is 2147483647
both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.
An Example:
class BitwiseAssign {
public static void main(String args[]) {
int a = 9;
int b = 14;
a|=b;
[Link]("Bitwise OR Assignment: a is " + a);
a = 9;
a&=b;
[Link]("Bitwise AND Assignment: a is " + a);
a = 9;
a^=b;
[Link]("Bitwise XOR Assignment: a is " + a);
a = 8;
a>>=2;
[Link]("Right Shift Assignment: a is " + a);
a = -8;
a>>>=2;
[Link]("Unsigned Right Shift Assignment: a is " + a);
a = 8;
a<<=2;
[Link]("Left Shift Assignment: a is " + a);
}
}
Bitwise OR Assignment: a is 15
Bitwise AND Assignment: a is 8
Bitwise XOR Assignment: a is 7
Right Shift Assignment: a is 2
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0
Logical AND:
Logical AND produces true if all operands are true, in all other cases it will produce false.
let say we have a variable named a of boolean type stores true.
Currently a = true;
And we have another variable named b of boolean type stores false
Currently b = false;
so a & b is false because true & false = false.
Logical OR:
Logical OR produces true if any operands is true, if all operands are false then produce false.
let say we have a variable named a of boolean type stores true.
Currently a = true;
And we have another variable named b of boolean type stores false
Currently b = false;
so a | b is true because true | false = true.
Logical XOR:
Logical XOR produces true if exactly one operands is true, if all operands are true or all are
false then produce false.
An Example:
class Logical {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a|b;
[Link]("a|b is " + c);
boolean d = a&b;
[Link]("a&b is " + d);
boolean e = a^b;
[Link]("a^b is " + e);
boolean f = !a;
[Link]("!a is " + f);
}
}
Let say we have two boolean variables named a and b. a have value true and b have value
false. to perform boolean OR of a with b and assign result to we often write
a = a|b;
with the help of boolean assignment operators that can be re-written as
a|=b;
both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.
An Example:
class BooleanAssign {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
a|=b;
[Link]("a|=b is " + a);
a&=b;
[Link]("a&=b is " + a);
a^=b;
[Link]("a^=b is " + a);
}
}
a|=b is true
a&=b is false
a^=b is false
Conditional Operators:
An Example:
class ShortCircuit {
public static void main(String args[]) {
int i = 0;
int j = 1;
if((j == 1) || (i == 1)){
[Link]("That is Short-circuit OR");
[Link]("No need to evaluate (i == 1)");
}
boolean a = false;
boolean b = false;
That is Short-circuit OR
No need to evaluate (i == 1)
An Example:
class TernaryDemo {
public static void main(String args[]) {
int i = 1;
int j = i==0?i:i+10;
i is 1
j is 11
An Example:
class ATP {
public static void main(String args[]) {
byte a = 100;
byte b = 20;
byte c = 10;
int i = a*b/c;
[Link]("i is " + i);
}
}
in that example given above variable a and b are of data type byte. Expression a*b/c is
evaluated as (a*b)/c. a*b produces 2000 that is larger than what a byte variable can hold. that is
why operand a and b are promoted to int. This means subexpression a*b is evaluated using int,
not byte.
An Example:
class ATP2{
public static void main(String args[]) {
byte a = 20;
byte b = 2;
c is 10
while the statement byte c = a/b; produces an error because while evaluating a/b both operands
a and b are promoted to int hence result is also an integer value. but variable that is left to the
assignment operator is byte hence target type is smaller in size so you have to type cast it
explicitly as we have done in next statement.
An Example:
class TypePromo {
public static void main(String args[]) {
byte b = 2;
short s = 5;
int i = 10;
float f = 11.2f;
double d = 111.23;
double result = ((b*f)/i) + f*s + d;
[Link]("result is " + result);
}
}
result is 169.47000167846682
In the expression
double result = ((b*f)/i) + f*s + d;
(b*f) will produces result in float because float is larger than byte. output of that subexpression is
22.4. i.e (b*f) = 22.4.
22.4/i will produces result in float because float is larger than integer. output of that sub-
expression is 2.24. i.e ((b*f)/i) = 2.24
f*s will produces result in float because float is larger than short. output of that subexpression is
56.0. i.e f*s = 56.0
Unit-V
Control Flow Statements
So far we have written so many java program and found a common observation that flow of
execution is top to bottom and instructions are executed in linear order, means instruction that
comes first (from top) in source file get executed first.
In that chapter we are going to study some special instructions that allow you to control flow of
execution. We can broadly classify these instruction in three categories.
1. Selection or Decision making
2. Looping or Iteration
3. Branching statements or Jump;
An Example:
class IfDemo {
public static void main(String args[]) {
int i = 20;
if(i%2 == 0){
[Link](i + " is an even number");
}
}
}
20 is an even number
In the example given above if remainder of i with 20 is equal to zero then statements written
within pair of parenthesis for if will be executed. If remainder not equal to zero (Let say for i =
21) then statements within pair of parenthesis for if will be bypassed.
An Example:
class IfDemoWOBraces {
public static void main(String args[]) {
int i = 21;
if(i%2 == 0)
[Link](i + " is an even number");
[Link]("I will be executed every time");
}
}
Because we are not placing curly brackets with if block, hence scope of if block is limited to just
one statement that is [Link](i + " is an even number"); and statement
[Link]("I will be executed every time"); is out of its scope. simply it is like
if(i%2 == 0){
Nested if:
One if statement can be placed inside another if statement. if that are inside another if are called
nested if. programmer can make any number of nested if as per his requirement.
An Example:
class NestedIf {
public static void main(String args[]) {
int age = 80;
if(age >= 18){
[Link]("You are not minor");
if(age >= 65){
[Link]("Even you are a senior citizen");
}
}
}
}
In the example given above, we have nested if(age >= 65) into if(age >= 18). [Link] if will
only be checked for condition if and only if condition for outer if is evaluated to true.
if-else:
The if-else statement provides a another path of execution when an if clause evaluates to false.
General form of if-else is
if(condition){
Group of statements (to be executed if condition is true);
}else{
Group of statements (to be executed if condition is false);
}
As you can observe when condition given within parenthesis is evaluated to false then code
segment written within else block is executed.
Similar for if statement given above If we do not use curly braces with if/else block then scope of
if/else block will be limited to just one statement.
An Example:
class BetweenIfElse {
public static void main(String args[]) {
int age = 15;
if(age >= 18){
[Link]("You are not minor");
[Link]("You are free to take your decision");
}
[Link]("I can’t come here");
else{
[Link]("You are minor");
[Link]("Be careful! You need guidance");
}
}
If you try to compile that code it will produce an error because we have placed a line
[Link]("I can’t come here"); between end of if block and start of else block, that is
not allowed.
if-else-if ladder:
General form of if-else-if ladder is:
if(condition){
group of statements;
}else if(condition){
group of statements;
}else if(condition){
group of statements;
}
.
.
.else{
group of statements;
}
The if statements are executed from the top to down as usual. As soon as one of the conditions
associated with the if is true, the group of statements written block of that if are executed, and
the rest of the ladder is simply bypassed. If none of the conditions is true, then group of
statement for final else will be executed. The final else acts as a default condition; that is, if all
other conditions fail, then the last else is performed. If there is no final else and all other
conditions are false, then no action will be performed.
An Example:
class IfElseLadder {
public static void main(String args[]) {
int score = 76;
In the program given above, first condition is evaluated to true hence Hurray! first division is
printed and subsequent code is bypassed. if score is set to 30 then all condition would
evaluates to false and final else part will be executed so output will Alas! Repeat.
switch-case statement:
It is a multi-way branching statement. It provides facility to execute different part of code based
on value of expression. It is used as an alternative of large if-else-if ladder. Genaral form of
switch statement is:
switch(expression){
case value1:
statement sequence for value1
break;
case value2:
statement sequence for value2
break;
case value3:
statement sequence for value2
break;
.
.
case valueN:
statement sequence for valueN
break;
default:
default statement sequence
}
● A switch statement works for primitive data type byte, short, int and char.
● Each case must have a unique literals, duplicate values are not allowed.
An Example:
class SwitchCaseDemo{
public static void main(String args[]) {
int division = 1;
switch(division){
case 1:
[Link]("Hurray! first division");
In switch case value of expression is evaluated first and compared with available case literals. If
match found then statement sequence for corresponding case is executed. if no match i found
then statement sequence written for default is executed.
So in above program value of division is 1 that is matched with first case so output is Hurray!
first division. if value of division is other than 1, 2 and 3 then no match will found and statement
sequence for default will executed and output of that program will be Alas! repeat.
break is used to terminate statement sequence. It is an optional statement. If break is not used
to terminate statement sequence then statement sequence for subsequent cases including
default will be executed.
An Example:
class SwicthCaseWOBreak {
public static void main(String args[]) {
int division = 1;
switch(division){
case 1:
[Link]("Hurray! first division");
case 2:
[Link]("Second division. it's okay");
case 3:
[Link]("Third division. just pass");
default:
[Link]("Alas! repeat");
}
An Example:
class OmittingBreak{
public static void main(String args[]) {
int division = 1;
switch(division){
case 1:
case 2:
case 3:
[Link]("Pass");
default:
[Link]("Fail");
}
}
}
Pass
Whether you take division 1, 2 or 3 result will be displayed as Pass and for all other values it will
be Fail.
Nested Switch:
Just like nested if a switch statement can be nested within another switch.
An Example:
class NestedSwitch {
public static void main(String args[]) {
int division = 2;
char grade = 'D';
No conflict arises between cases of outer if and nested if, because both have their separate set
of cases.
An Example:
class NestedSwitchDuplicateCase {
public static void main(String args[]) {
int outerswitch = 1;
int innerswitch = 1;
switch(outerswitch){
case 1:
[Link]("inside outer switch");
switch(innerswitch){
case 1:
[Link]("inside inner switch");
}
}
}
}
Looping or Iteration:
Iteration statements involve while, do-while and for loop.
while loop:
It is most basic loop statement supported by java. while loop repeat a block of statement while
its controlling condition is true. General form of while loop is:
Condition can be any boolean expression. Sequence of statement written within scope of while
loop (also called body of loop) is executed until condition is evaluated to false. As condition
goes false, the control passes to the statement written just next to while loop block.
An Example:
class WhileDemo {
public static void main(String args[]) {
int loopCounter = 1;
Loop counter is 1
Loop counter is 2
Loop counter is 3
Loop counter is 4
Loop counter is 5
Loop counter is 6
Loop counter is 7
Loop counter is 8
Loop counter is 9
Loop counter is 10
I am after loop
In the code given above, loopCounter is initialized to 1 and variable loopCounter is checked
whether it is less than or equal to 10. Condition is true hence body of loop is executed so output
comes on screen is “Loop counter is 1” then loopCounter is incremented by one. as control
touches end of loop body, it goes back to condition, here again condition checking takes place
and if it is true then again body of loop is executed. finally when condition goes false for
loopCounter’s value 11 then control passes to instruction [Link] ("I am after loop");
so finally it prints I am after loop.
In the code segment given above we have place true instead of condition so obviously it will
never go false. Hence an infinite loop.
Similar to if statement, If we do not use curly braces to define scope of while block then scope
will be limited to just one statement.
do while loop:
As we have observe that in while loop condition is evaluated first if it goes true then body of loop
is executed but if condition is evaluated to false for first time then body of loop never get chance
to execute.
Now us consider a situation, when we make a call to customer care office, an audio file that hold
menu content is played and ask to enter choice. if we enter an invalid option then audio file is
played again else we go through next phase or we can say audio file is played at-least for once
no matter what choice we will enter when asked so.
To address such kind of situation we use do-while loop. General form of do-while loop is:
do{
Sequence of statement
}while(condition);
do-while loop executes body of loop first then check condition. if condition is evaluated to true
then body of loop is executed again else control goes to instruction that comes next to
while(condition) statement.
loopCounter is 11
I am after loop
In the example given above we have set value of loopCounter to 11 we have setted condtion
loopCounter <= 10. As we have discussed above in case of do-while loop, body of loop is
executed at-least once no matter whether he condition is going to false or true. so output comes
loopCounter is 11 and when condition is checked it is evaluated to false hence no repeated
execution of body takes place and control now comes to instruction that is next to
while(loopCounter <= 10); that is [Link]("I am after loop"); and prints I am after loop.
Similar to if statement, If we do not use curly braces to define scope of do-while block then
scope will be limited to just one statement.
for loop:
for loop provides a compact way of iteration. It is a powerful and flexible construct. general form
of for loop is:
for(initialization; condition; iteration){
Sequence of statement
}
Initialization express initialization of loop, it is executed only once as the loop begins. normally
used to initialize loop control variable.
Condition is check every time before entering into body of loop it must be a boolean expression
if condition is evaluated to true then body of loop executed else control passes to the instruction
that comes next to body of loop.
Iteration is executed each time after execution of body of loop. It is normally an expression that
changes loop control variable.
An Example:
class forDemo {
public static void main(String args[]) {
loopCounter is 1
loopCounter is 2
loopCounter is 3
loopCounter is 4
loopCounter is 5
loopCounter is 6
loopCounter is 7
loopCounter is 8
loopCounter is 9
loopCounter is 10
I am after loop
In the example given above, initialization (i.e. int loopCounter = 1) statement is executed in first
step, then condition (i.e. loopCounter <= 10) is checked in second step if condition is evaluated
to true, then body of loop is executed, then iteration (i.e. loopCounter++) is executed. Now
again control goes to second step, condition is checked and if condition is evaluated to true,
then body of loop is executed, then iteration (i.e. loopCounter++) and so on. Until condition does
not evaluated to false.
Here variable loopCounter is defined withing the scope of for loop hence it is not accessible
outside for for loop’s block.
class ForIniItr {
public static void main(String args[]) {
int loopCounter = 1;
for(;loopCounter <= 10;){
[Link]("loopCounter is " + loopCounter);
loopCounter++;
}
}
}
loopCounter is 1
loopCounter is 2
loopCounter is 3
loopCounter is 4
loopCounter is 5
loopCounter is 6
loopCounter is 7
loopCounter is 8
loopCounter is 9
loopCounter is 10
Here we have omit initialization and iteration but loop control variable is initialized before start of
for loop and iteration is place inside loop body.
An Example:
class ForInfi {
public static void main(String args[]) {
for(;;){
[Link] ("I am going to execute forever");
}
}
}
We haven’t place any condition to stop execution of loop body so it’s an infinite loop
Also it is possible to place multiple initialization and iteration in for loop using comma operator.
An Example:
class ForMultiIniItr {
a=4b=1
a=3b=2
a=2b=3
a=1b=4
Nested Loop:
A loop can be placed inside another loop. Programmer can make any number of nested loop as
per his requirement.
An Example
class NestedLoop {
public static void main(String args[]) {
for(int row = 4; row > 0; row--){
for(int col = 0; col < row; col++){
[Link]("*");
}
[Link]();
}
}
}
****
***
**
*
break:
break has two forms
1. Unlabeled: Normally we are using break in unlabeled form. we have already used it with
switch case to prevent execution of subsequent cases.
An Example:
class BreakLoop{
public static void main(String args[]){
for(int i = 0; i <= 10; i++){
if(i == 5){
break;
}
[Link](“i is ” + i);
}
[Link](“Loop completed”);
}
}
i is 0
i is 1
i is 2
i is 3
i is 4
Loop completed
break can be used to terminate any type of loop ,mainly it is used to exit infinite loop.
An Example:
class BreakInfinite{
public static void main(String args[]){
int i = 0;
while(true){ //it’s an infinite loop
[Link](“I am in infinite loop”);
if(i == 5){
[Link](“Now infinite loop is going to break”);
break;
}
i++;
}
[Link](“Loop completed”);
}
}
if break is used with nested loops, then it will break only loop inside which break is used.
An Example:
class InnerBreak{
public static void main(String args[]){
for(int i = 0; i<= 2; i++){
for(int j =0; j<= 2; j++){
[Link](“i is ”+i+“ j is “ + j);
if(j == i){
[Link](“Breaking inner loop”);
break;
}
}
}
}
}
i is 0 j is 0
Breaking inner loop
i is 1 j is 0
i is 1 j is 1
Breaking inner loop
i is 2 j is 0
i is 2 j is 1
i is 2 j is 2
Breaking inner loop
2. Labeled: Labeled breaks are used to break deep structures and mainly used to break
inner loops an inner switch cases.
Here, label is the name of a label that identifies a block of code. When this form of break
i is 0
i is 1
After block having label B
In the code segment given above, we have written a line break B; when that line get
executed, control jumps outside B block and start executing instruction that is next to
end of B block.
continue:
We have seen with break, it take control out of the block and executes instruction that is next to
block. We have another branching statement that is continue. it brings control at the start of
block, opposed to break that brings control at the end of block.
An Example:
class ContinueDemo{
public static void main(String args[]){
for(int i = 0; i <= 10; i++){
if(i%2 == 0){
i is 1
i is 3
i is 5
i is 7
i is 9
In the code segment given above we have placed continue inside if block,that checks whether
the given number is even or not, if number is even that control goes to start of for loop (meaning
to say at increment, not at initialization) and then checking condition with updated value and
again enter into block and do its execution.
So far we have seen that continue have its effect just for the loop in which it is used. Although it
is possible to extend its effect for outer loop using loop label. A loop label is a label that have a
loop in it, a loop label does not enclose its loop in curly braces.
An Example:
class LoopLabel{
public static void main(String args[]){
A:for(int i = 1; i <= 3; i++){
[Link]("i is " + i);
B:for(int j = 1; j<= 2; j++){
[Link]("j is " + j);
if(j%2 == 0){
continue A;
}
}
}
}
}
i is 1
j is 1
j is 2
return:
Final statement that is used for branching is return. Similar to C/C++, return is used to terminate
execution of a method and return control back to the caller of method. return statement can be
used to terminate execution of a method with return a value as well as to without returning
anything.
An Example:
class ReturnDemo{
public static void main(String args[]){
boolean isReturn = true;
if(isReturn){
[Link]("Going back to caller");
return;
}
[Link]("I won't executed ever");
}
}
In the code segment given above last print statement will never be executed because we have
placed return statement before it and that statement will execute because variable isReturn is
true.
An Example:
class CarelessReturn{
public static void main(String args[]){
[Link]("Going back to caller");
return;
[Link]("I won't executed ever");
}
In code segment given above, compiler will produce “Unreachable code” error, because return
statement will get executed in every time. We have placed no condition over its execution.
Unit-VI
A Closer Look to Arrays
Array:
An array is a collection of similar typed variable that are referred to by a common name. Each
item in array is called element and each element is accessed by its numeric index. Numeric
index begins with zero and ends to one less than length of array.
Initializing An Array:
General form of initializing an array is
type[] var-name = {initializing values};
When initialization is used, no need to use new operator because memory is allocated implicitly
for total number of elements specified in initialization list.
e.g. int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
In the example given above month is an array of integer type with 12 elements and these
elements are initialized by value 31, 28, 31...........and so on.
first element of that array that is month[0] have value 31, second element month[1] have value
28. Last element of array that is month[11] have value 31.
As we have discussed in the above each element in the array is referred with a numeric index
and these index are continuous, so we can use loops to access array elements.
An Example:
class ArrayDemo{
public static void main(String args[]){
int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for(int i = 0; i <= 11; i++){
[Link]("Month " +(i +1)+ " have " + month[i] + " days");
}
}
}
An Example:
class BoundCheck{
public static void main(String args[]){
int[] month = {31};
[Link]("month 2 have " + month[1] + " days");
}
}
In the code segment given above we have declared an array month that have just one element
and that element is at index 0. but in print statement we are accessing element, having index 1
means 2nd element of array. when we compile that program no error will be generated but at run
time program will display an error message.
Also java implements array as an object. To find size of an array, java provides inbuilt project
lenght, that returns total number of elements in array.
class ArrayLength{
public static void main(String args[]){
int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
[Link]("Array month have " + [Link] + " elements");
}
}
An Example:
class ForeachDemo{
public static void main(String args[]){
int[] marks = {18, 18, 17, 15, 10};
int sum = 0;
Sum id 78
is equivalent to
By using foreach loop we don’t required to create and maintain a variable that deals with index
of array.
Multidimensional Array:
Like C/C++, Java also supports multidimensional [Link] we are taking example of 2-
dimensional array, similar rules are all applied for higher dimensions .Similar to one
dimensional, Creating a 2-D array is also two step process:
1. Declaration: General form of declaring a 2-D array is
type var-name[][];
or
type[][] var-name;
Here type define the data type of array. i.e. type of value that every element of array hold.
Square bracket indicates that variable holds an array. size of array is not part of declaration. and
var-name is any valid name of array.
e.g. int matrix[][];
Above discussion so far is just declaration of an array still we have to allocate memory to it.
An Example:
class TwoDArrayIni{
public static void main(String args[]){
int matrix[][] = {
{31, 28, 31, 30},
{31, 30, 31, 31},
{30, 31, 30, 31}
};
31 28 31 30
31 30 31 31
30 31 30 31
Java provides facility of creating array with uneven rows, means we can create an array that
have different number of elements in each row. To do that, just specify first dimension of array
and no. of element for each row can be specified separately later on.
An Example:
class UnevenArray{
public static void main(String args[]){
int matrix[][] = new int[3][];
matrix[0] = new int[2];
matrix[1] = new int[3];
01
123
2345
In the program given above matrix is a 2-D array. its first 1-D array have 2 elements, second 1-
D array have 3 and last 1-D array have 4 elements. We have just specified number of rows at
the time of declaration that is merged with memory allocation. but number of element for each
row are defined in subsequent lines.
finally using length property of array with 2-D array returns number of 1-D arrays that it have
and using it with 1-D array returns number of elements that it have. hence [Link] returns
3 while matrix[0].length returns 2.
Unit-VII
A Deep Look at Classes and its Members
At the time of starting, we have discussed object oriented concept in details, very first concept
that we were discussing was class. classes are base of object oriented programming. In
examples that we have seen so far, we were using it just to encapsulate main method because
in java, It is essential to put every concept that we want to implement inside class.
It is time to take deep look on classes and know about all facilities that a class can provide us.
Here class-name is name of class whose object is being created, and obj-name is name of
object. we are free to choose any valid name for an object. new is an operator that is used to
allocate memory dynamically.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp = new MobilePrice();
[Link] = 1000;
[Link]= 4.5f;
[Link] = 3.5f;
In the example given above we have created a class named MobilePrice that have three
variables. We have also created another class MobilePriceDemo that have main. In first line of
main, we have created object of class MobilePrice. Before moving ahead it would be beneficial
to take a deep look at object creation.
Object Creation:
Actually creating an object is two step process
Step 1: Creating a reference of class. General form of creating a reference is
class-name obj-name;
actually a reference is variable that point to an object. To create a reference of MobilePrice
class we just need to write
MobilePrice mp;
now our reference mp does not pointing to any object. It have value null.
For the sake of convenience, java allow us to merge both steps. we just need to write
class-name obj-name = new class-name();
and we have already use that form in example given above. that’s all about object creation in
java.
(Although step 2 contains one more step that is initialization, we will discuss about it later in
same chapter.)
The two step procedure can be understood with the help of figure given below.
One thing to note about new is, it allocate memory at run time. But memory is finite, so
sometime it is not possible for new to allocate memory due to insufficient space. In such
situation a run time exception takes place (We will discuss about Exception Later in details).
An important point:
Java apply dynamic memory allocation for arrays and object not for primitive data types.
Reason behind implementing primitive data type not as an object is interest of efficiency.
because creating an object at run time generate a significant overhead and java require to
maintain attributes of each object separately. Java implement primitive data types simply to
avoid overhead and achieve speed.
Instance Variable:
In the starting chapters we have defined object as an instance of class & all variable that are
defined within a class are called instance variable. To access instance variable outside class &
static members (discussed later in details).We have to use dot(.) operator, that links object
name with instance variable name. General form for accessing instance variable using object is:
[Link]-variable-name
Interesting to know, variable defined in a class are called instance variable because they are
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;
[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;
[Link] = 1200;
[Link] = 2.3f;
[Link] = 3.7f;
}
}
In the code given above we have created two object mp1 and mp2 of class MobilePrice and we
have assigned different value to each instance variable of mp1 and mp2. When we are
calculating total price for mp1 and mp2, final prices are calculated on basis of values of their
own instance variable.
In the next line when we have changed values of instance variables of mp2 then again
calculating mobile prices for both object, we get same price for mp1 but different for mp2
because changing values of instance variable for mp2 does not affect values of instance
variable for mp1.
If you are familiar with c++, then you might thinking that mp2 is now referring another object that
is similar to what mp1 is referring currently, because default object assignment in c++ create bit-
wise copy of object that is being assigned. mp1 and mp2 refer to different object and changing
instance variable of mp1 does not affect mp2.
But that is not true for java. whenever we are performing such kind of assignment, java does not
make bit-wise copy of object being pointed by assigning reference instead it just create a copy
of assigning reference. means after assignment we have another reference variable that points
to similar object currently pointed by assigning reference.
Hence if we make changes in values of instance variable using one reference variable then
changes will be effective for another reference because ultimately they are pointing to same
object.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = mp1;
[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;
[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;
In the code segment given above, in first line of main method we have created an object of
class MobilePrice that is mp1 and we have assigned into reference variable mp2. Now mp1 and
mp2 referring to same object.
Then we have assigned values to instance variable of mp1 and calculating total price for mp1
that is 1080.0 Now we have make changes in instance variable using mp2. because both
reference variables point to same location hence these changes are also applied to mp1. So
calculating total price for mp1 and mp2 provides same result.
Also when we assign null to reference mp2 then it will not affect mp1. because mp2 simply hold
null and mp1 points to object.
Array Of Object:
Similar to an array of primitive data type it is possible to create an array of object. Creating an
array of objects is a bit similar to creating an uneven array. It is a two step process.
In that step we are just creating array of reference so far we have not allocated memory for
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mpArray[] = new MobilePrice[2]; //creating array of reference
for(int i = 0; i < 2; i++){
mpArray[i] = new MobilePrice(); //Assigning memory to each individually
mpArray[i].manufacturingCost = 1000 + i*100;
mpArray[i].exciseDuty= 4.5f + i*1.0f;
mpArray[i].serviceTax = 3.5f + i*1.0f;
}
Method:
Now we are going to discuss methods. We all know that to in C language, we create functions
to perform a specific task and these functions are called according to requirement. Similar to
Here return-type defines type of value, returned by method. if a method does not return a value
then return-type must be void. In java it is essential to define return type of method.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
void calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100 +
serviceTax * manufacturingCost / 100;
[Link]("total price of mobile is " + totalPrice);
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
[Link] = 1000;
[Link] = 4.5f;
[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;
[Link]();
[Link]();
}
}
A method of a class is always called relative to an object of that class and once invocation takes
place, the calling object is known hence there is no need to use object again to accessing
instance variable.
First line calculate price for mp1 because calculatePrice() is called relative to mp1 and once
invocation takes place compiler knows about calling object hence variable that are used inside
calculatePrice belongs to mp1.
As that line segment executes then control goes to code defined inside calculatePrice method.
after statements inside calculatePrice have executed. control goes back to statement that
comes after [Link]().
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;
[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
1000 is copied to local variable m, 4.5f is copied to local variable s and 3.5f is copied to local
variable e. Values of m,s,e are assigned to instance variables manufacturingCost, serviceTax
and exciseDuty respectively. because method setPriceElement is called for object mp1 hence
instanc variable that accessed inside method setPriceElement belong to object mp1. Similar
execution takes place for mp2.
Constructor:
Now let us Consider a situation, we have a file that have information of 25 mobile phones. we
have to create objects, each representing a mobile phone. We have to open that file and read
information of each mobile then create objects and then call a Parametrized method that
initializes state of each object with values stored in file. In the whole processing we have to call
Parametrized method for all 25 objects. Java provides us a better way to do so using
constructor. Constructor provides us ability to initialize object when they are created.
In the previous example we have used setPriceElement method to initialize instance member of
object now we are going to do same opration using constructor. Initailly we are using simplest
form of constructor that is without parameters.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
MobilePrice(){
[Link](“Inside Constructor”);
float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
We have place empty pair of parenthesis after ’new MobilePrice’ to call constructor that do not
accept any parameter. We will study that topic in detail when we discuss constructor
overloading in subsequent chapter.
Parametrized constructor:
In the Example discussed above we are using constructor that do not accept any parameter
hence we are unable to initialize instance variable for each object uniquely. To address that
problem we can use parametrized constructor. passing argument to constructor is similar to
passing argument in method. Just we have to specify arguments at the time of object creation.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 3.5f, 1.5f);
MobilePrice mp2 = new MobilePrice(1500, 3.0f, 2.0f);
In the program given above, we have defined parametrized constructor in MobilePrice class.
When we are creating object of class MobilePrice, we have to specify arguments for
constructor. In the first line of main we are passing arguments 1000, 3.5f and 1.5f. hence after
memory allocation instance variable manufacturingCost, serviceTax & exciseDuty are initialized
to 1000, 3.5f and 1.5f. finally a reference of allocated memory is assigned to mp1.
Similar operation will take place for creation of object mp2. because both objects have different
value for their own instance variables hence calling method calculatePrice for each of them
produce different result.
Garbage collector does not claim an object as it goes out of the scope. It runs periodically,
checking for objects that are no longer referenced and finally claim memory location occupied
by unreferenced object. Whatever we want to perform at the time of reclaiming, we should write
in finalize method. like simply we can have situation in which we have an object that have
One thing to keep in mind is that we cannot determine when garbage collector is going to claim
an object hence we cannot confirm when finalize will be executed and even if it will be executed.
Using finalize is not a reliable solution.
An Example:
MobilePrice(int m, float s, float e){
[Link] = m;
[Link] = s;
[Link] = e;
}
In the Code segment given above we have used ‘this’ keyword to access instance members of
calling object. although in the previous examples we don’t use ‘this’ because our compiler
already know which object calls it. In normal it is absolutely unnecessary to use ‘this’ but in
some situation it is very much useful.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 3.5f, 1.5f);
In the example given above we have used same name for instance variable as well as local
variable of constructor. due to locality, variables that are defined inside constructor hides
instance variable. In that constructor we are assigning value of local variable manufacturingCost
to local variable manufacturingCost. Hence We are hiding instance variable manufacturingCost
by local variable manufacturingCost.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}
class MobilePriceDemo{
Here using [Link] (on left hand side of assignment operator) specifies that we
are using instance variable of calling object and manufacturingCost (on right hand side of
assignment operator) is simply refer to local variable.
static Keyword:
So far we have learned about instance variable. Instance variable are specific for each instance
(object) of class. Java provides us facility to create variable that are not specific to objects of
class using static keyword.
To create a static variable just precede its declaration with static keyword. a static variable have
following characteristics
● A static variable belongs to a class, not to an objects.
● Because they are not specific to objects, hence only a single copy is maintained.
● Also static variable does not belong to object hence it can be accessed using class
name to which they belong. To access a static variable simply write
[Link]-variable-name;
Although It is possible to access a static variable using object name. using class name to
access is recommended.
● Java does not supports static local variable i.e. it is not possible to create a local variable
with static keyword.
Similar to static variable we can also create static method. To declare a method static just
precede its signature with static keyword. A static method have following characteristics
● A static method belongs to a class, not to an object.
● Because they are not specific to objects, hence can be called using class name to which
they belong. To call a static method simply write
[Link]-method-signature;
● Because static methods are not specific to objects, they can not access instance
variable of an object, but can access static variables. for the same reason static method
cannot call a non-static method without an object, but can call another static method.
● Because static methods are not specific to objects, hence ‘this’ keyword is not available,
An Example:
class MobilePrice {
static int modelNo;
int mobilePrice;
float serviceTax;
float exiseDuty;
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
In the code given above we have created a static variable modelNo and a static method
getModelNo. In in subsequent lines we have accessed modelNo with different styles. Because
only a single copy of modelNo exists that is shared between all objects, hence changes made
reflect for all others.
Variables that are declared within a class without static keywords are specific to instance, hence
called instance variable of class. But variable that are declared with static keyword are specific
to class hence these variables are called class variables. For the same reason methods having
their signature preceded with static are called class methods.
We have studied about constructor that are called implicitly at the time of object creation and
mainly used to initialize instance variable of an object. Although constructors can also be used
to initialize class variables but java provides a better way to initialize class variables using static
block. A static block is executed only once when class is first loaded to JVM. General form of
static block is
An Example:
class MobilePrice {
static int modelNo;
int mobilePrice;
float serviceTax;
float exiseDuty;
static{
[Link]("Inside static block");
modelNo = 1100;
}
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
final Qualifier:
Creating a program requires declaring constant identifiers. To declare a constant identifier
simply precede its declaration with final keyword. Doing so prevent content of that identifier from
being modified. We must initialize such identifier at the time of declaration.
In the previous example declare modelNo as static variable but that variable is changeable to
avoid any accidental change, simply precede its declaration with final and initialize it.
An Example:
class MobilePrice {
static final int MODEL_NO = 1100;
int mobilePrice;
float serviceTax;
float exiseDuty;
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
An Example:
class CommandLineDemo {
public static void main(String[] args) {
for(int i = 0; i < [Link]; i++){
[Link]((i+1)+ " command line argument is-" + args[i]);
}
}
}
Compile that code and To pass command line argument simply type
java CommandLineDemo all is well
To pass multiword string as a single argument simply enclose them in single/double quotes
java CommandLineDemo 'all is well'
Unit-VIII
A Deep Look at Method and Constructor
In last chapter we have read about class, creating a method in a class, creating constructor etc.
Its time to take a deep look at methods, constructor and know about high level flexibilities
provided by java to both.
Method Overloading:
Consider a situation, you are asked by your trainer to make an assignment. Your Assignment is
”Create a program that add two integers, two floating point numbers and two characters. you
have to create separate function to perform each addition do not mesh all code inside main
function.”
One way to do is create three different methods like addInt, addFloat and addChar. and call
them separately. In that scenario you have to remember name of each method. although you
are performing same operation but just due to different types of parameter you have use
different name for each. Method overloading provides a smart way to deal with such kind of
problems.
Method overloading allow us to create more than one method in a class that have same name.
These method must differ in types of parameter they accept or number of parameter they
Return type does not play any role in method overloading. if more than one method have same
name, same number of parameters with same type but different return type, then compiler will
report an error.
An Example:
class Overload {
int add(int firstNumber, int secondNumber){
return (firstNumber + secondNumber);
}
class OverloadDemo{
public static void main(String[] args) {
Overload ol = new Overload();
intAddition is 3
floatAddition is 4.0
charAddition is a
In that program given above we have defined three method each of them have same name that
is add. first version of add method accepts two integer parameter, second accept two float
parameter and third accept two character parameter. All three methods perform same addition
Look at the syntax of calling them inside main method, they are looking same. At the time of
calling, we just have to specify arguments. In other way we can say that we have implemented
“single interface multiple methods”, that is polymorphism. Because decision of calling specific
version is taken at compile time that is why we say method overloading is a way to implement
compile time polymorphism.
When overloaded methods are called, compiler matches number of argument and type of
argument to parameter, and based on that matching, specific version of method is called. In
above example we have call add method three times. first time we have called it with two
integer arguments hence out of three available versions, first is matched exactly hence it is
called. for the second time when float values are passing as an arguments then second version
is called.
If java compiler do not find exact match then automatic type promotion play its role.
An Example:
class Overload {
int add(int firstNumber, int secondNumber){
return (firstNumber + secondNumber);
}
class OverloadDemo{
public static void main(String[] args) {
Overload ol = new Overload();
intAddition is 3
doubleAddition is 4.0
charAddition is a
Here in second call of add, we are passing float values while we haven’t define any version of
add that accept float as a parameter. here float is automatically promoted to double and second
version of add is called.
Constructor Overloading:
Similar to method overloading, java allow us to overload constructors also. We may have some
situation when we do not want to initialize all instance variable of an object. We may want to
initialize one or two instance variable. Now Look at example that we have discussed in
parameterized constructor, we have passed three arguments in constructors. In that case
creating an object without passing three argument is an error. Constructor Overloading provides
us facility to deal with such situation.
Similar to method overloading, more than one version of constructor should either have different
number of parameter or different types of parameter.
An Example:
public class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;
MobilePrice(){
mobilePrice = 0;
serviceTax = 0.0f;
exiseDuty = 0.0f;
}
MobilePrice(int m){
mobilePrice = m;
serviceTax = 0.0f;
exiseDuty = 0.0f;
}
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1000);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);
In the example given above we have defined three versions of constructor. first version do not
have any parameter. Second have one parameter and third have three parameters. At the time
of object creation arguments are matched to parameters, and based on that matching
constructors are called. for
MobilePrice mp1 = new MobilePrice();
first constructor that do not accept any parameter is called. and for
MobilePrice mp2 = new MobilePrice(1000);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);
second and third versions are called.
An Example:
class MobilePrice {
int mobilePrice;
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1250, 2.0f, 1.9f);
MobilePrice mp2 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);
In the Example given above we have created a method haveSamePrice. That method takes an
object of MobilePrice as a parameter. Objects are passed just same inbuilt data type are
passed.
We can also pass object to constructor. Passing object as an argument is particularly useful
when we want to create an object that is same as an already existing object.
An Example:
class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;
MobilePrice(MobilePrice mp) {
mobilePrice = [Link];
serviceTax = [Link];
exiseDuty = [Link];
}
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}
class MobilePriceDemo{
In the Example given above we have defined an another version of constructor that accept
object of MobilePrice class as a parameter. In main function we are passing object mp1 as a
parameter when creating object mp2. In constructor we have initialized all instance variables of
mp2 with values of instance variable mp1. hence comparing prices for these two objects return
true.
Returning Object:
In the previous example, We have seen that an object can be passed as an argument similar to
other data-type. An object can also be returned from a method.
An Example:
class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;
MobilePrice getNewObject(){
MobilePrice temp = new MobilePrice(mobilePrice+1000,serviceTax,exiseDuty);
return temp;
}
float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
In the Example given above, we have defined a method getNewObject(), that method create a
new object of MobilePrice class and return it. Returning an object is similar to returning a
primitive data type, To collect returning object we just have to create a reference of that class.
Recursion:
Simply recursion is defined as a process of repeating an item in a self-similar way or defining
something in the term of itself.. In the terms of function we can say when a function call to itself
than it is known as recursive function.
An Example:
class Fact{
int factorial(int factNo){
if(factNo == 1){
return 1;
}
int result = factorial(factNo-1)*factNo;
return result;
}
}
class FactDemo {
public static void main(String[] args) {
Factorial of 3 is 6
Factorial of 2 is 2
Factorial of 4 is 24
Whenever a method is called, Space is allocated for its parameters and local variables and as
control return from method, all parameters and local variables stored in stack are destroyed and
memory occupied by them is free for further use.
Recursion allow us to create code that are are simple and cleaner but it generate significant
number of method calls that create larger number of local variables and parameters which may
lead to run out of space. It is also slower than equivalent iterative code.
“The wrapping up of data and associated function together in a single unit (called class) and
keeps both safe from outside interference and misuse is known as encapsulation.”
So far we have discussed so many examples and in each example we are able to access
variables as well as methods outside the class using object. An uncontrolled access may lead to
misuse of data. To avoid such misuse we may allow access of data only through a set of
methods, means no user can directly access data he can only access methods. Avoiding direct
access of data make your class behave like a black box, the data and inner working is not
available for tempering.
Encapsulation contains one more attribute that is access control. Through access control we
can define which part of program can access members of a class. Java provides four kind of
access specifiers first is private access specifier. Data & methods that are declared as private
in a class are accessible only up to that class. Any Code defined outside that class cannot
access private members. second is protected access specifier, we will discuss it in next
chapters in short we can say that any variable declared as protected is accessible in
subclasses. Third is No-modifier that is also known as default modifier, it is applied when we do
not specify any access specifiers among private public and protected. Variable and methods
that have default access specifiers are accessible with its package (we will discuss about
package in upcoming chapters, till then consider it equivalent to public). Fourth & final is public
An Example:
class MobilePrice {
private int manufacturingCost;
private float serviceTax;
private float exciseDuty;
void calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100 +
serviceTax * manufacturingCost / 100;
[Link]("total price of mobile is " + totalPrice);
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();
[Link]();
[Link]();
}
}
Inheritance:
As we have already discussed in previous chapters, Inheritance is the process by which one
object acquire properties of another object. In that chapter we will take a deep look at how java
implements inheritance.
Super class: A class from which another class is derived is called super class.
Sub class: A class that is derived from a superclass is called sub class.
An Example:
class A{
int firstNumber,secondNumber;
void showNumbers(){
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);
class B extends A{
int thirdNumber;
void showThirdNumber(){
[Link]("thirdNumber is " + thirdNumber);
}
void average(){
[Link]("Average is " + (firstNumber + secondNumber +
thirdNumber) / 3);
}
}
[Link]();
B cd = new B();
[Link](150);
[Link]();
[Link]();
[Link]();
}
}
firstNumber is 100
secondNumber is 200
Average is 50
In the code segment given above, class A is our superclass and b is our sub class. as we can
see in the code of class B, member of class A are also accessible because class B is child class
of A. In simple words we can say that class B is re-using fields and methods of class A.
An Example:
class A{
private int firstNumber;
private int secondNumber;
void showNumbers(){
//ok because private members are accessed in the their own class
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);
}
int getAddition(){
return (firstNumber + secondNumber);
}
}
class B extends A{
int thirdNumber;
void showThirdNumber(){
//Error! trying to access private members outside their class
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);
void average(){
//Error! tyring to access private member outside their class
[Link]("Average is " + (firstNumber + secondNumber +
thirdNumber) / 3);
//ok
[Link]("Average is " + (getAddition() + thirdNumber) / 3);
}
}
[Link]();
B cd = new B();
[Link](150);
[Link]();
[Link]();
[Link]();
}
}
firstNumber is 100
thirdNumber is 150
Average is 50
In the program given above, we have declared firstNumber & secondNumber as private
members of class A. As we have discussed in previous chapter, private member is only
accessible in their own class. Trying to access these members int showThirdNumber() and
average() leads to error. To get addition of firstNumber & secondNumber, we have created a
method getAddition() in class A, that returns addition of them.
An Example:
class A{
int firstNumber;
int secondNumber;
int getAddition(){
return (firstNumber + secondNumber);
}
}
class B extends A{
int thirdNumber;
void showThirdNumber(){
[Link]("thirdNumber is " + thirdNumber);
}
int average(){
return (firstNumber + secondNumber + thirdNumber) / 3;
}
[Link](10, 20);
[Link]("Addition of numbers for object a is " + [Link]());
[Link]();
B b = new B();
[Link](5, 6);
[Link]("Addition of numbers for new object of B is " +
[Link]());
//Error superclass do not have any knowlegde about sub class' instance
//variable
[Link]("Third numbers for object d is " + [Link]);
}
}
A Realistic Example:
Now its time to take a Realistic Example of using inheritance. So far in previous code we have
used three parameters to calculate price of a mobile that are manufacturingCost, serviceTax
and exciseDuty. Let us consider a scenerio when a new tax has been imposed on mobile price
(say sales tax) in a particular area and now we have two options to implement it in code. first
one is modify the code that we have already created and second is simply apply inheritance, to
reuse already available code. Obviously second choice is better. Not take a look how we can
implement it.
An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
MobilePrice() {
manufacturingCost = 1000;
serviceTax = 2.5f;
exciseDuty = 1.5f;
}
float getMobilePrice(){
return manufacturingCost + manufacturingCost * (serviceTax + exciseDuty)/100;
}
}
MobilePriceWithSaleTax(){
manufacturingCost = 1000;
float getMobilePriceWithSaleTax(){
return manufacturingCost + manufacturingCost * (serviceTax + exciseDuty +
saleTax)/100;
}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1500, 1.7f, 3.3f);
super:
Preceding example that we have discussed above is not implemented efficiently because our
sub class constructor have to explicitly initialize instance members of superclass. In that
scenario we have to grant access of every instance member of superclass to subclass in order
to initialize them. Building code with that approach leave no way to hide instance member of a
superclass that violate encapsulation that is primary concept of OOP.
That approach also leads to duplicating same code again and again that unnecessarily increase
length of program and make it a bit difficult to manage.
To overcome from that situation java provide us super keyword, that have following purpose.
One thing to keep in mind is that super must be first statement inside subclass constructor and if
super is not used inside subclass constructor, default constructor of a superclass is called
implicitly. Hence if a superclass only have parameterized constructor then not using super along
with required parameter to call superclass constructor inside sub class constructor cause error.
An Example:
class MobilePrice {
private int manufacturingCost;
private float serviceTax;
private float exciseDuty;
MobilePrice() {
manufacturingCost = 1000;
serviceTax = 2.5f;
exciseDuty = 1.5f;
}
MobilePrice(int m, float t) {
manufacturingCost = 1000;
serviceTax = t;
int getManufaceuringCost(){
return manufacturingCost;
}
float getServiceTax(){
return serviceTax;
}
float getExcizeDuty(){
return exciseDuty;
}
float getMobilePrice(){
return manufacturingCost + (manufacturingCost * (serviceTax +
exciseDuty))/100;
}
}
MobilePriceWithSaleTax(){
super();
saleTax = 2.0f;
}
MobilePriceWithSaleTax(int m, float t) {
super(m,t);
saleTax = t;
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1500, 1.7f, 3.3f);
super is useful in that situation, To access hidden instance variable of a class inside subclass
simply precede it by with super keyword and dot operator.
An Example:
class B extends A{
int i = 10;
void getInB(){
[Link]("Inside B : i is " + i + " super.i is " + super.i);
}
}
class C extends B{
int i = 100;
int j = -2;
void getInC(){
[Link]("Inside C : i is " + i + " super.i is " + super.i);
[Link]("Inside C : j is " + j + " super.j is " + super.j);
}
}
class SuperDemo {
public static void main(String[] args) {
C c = new C();
[Link]();
B b = new B();
[Link]();
A a = new A();
[Link]();
}
}
As we have discussed in previous example that super must be first statement inside sub class
constructor. Reason for placing super at start of subclass constructor is that constructor must be
called in the order of derivation that is from superclass to sub class. If we are using not super to
call superclass constructor then default (constructor with out parameter) constructor of
superclass is called implicitly.
An Example:
class A{
A(){
[Link]("Hello I am in A");
}
}
class B extends A{
B(){
[Link]("Hello I am in B");
}
}
class C extends B{
class ConstructorOrder {
public static void main(String[] args) {
C cobj = new C();
}
}
Hello I am in A
Hello I am in B
Hello I am in C
and try to compile that code, it will produce an error because we have neither called
parameterized constructor using super keyword nor provided default.
Method Overriding:
When a subclass contains a method that have same name and parameters as its superclass
have, then method defined in sub class is said to override method of its superclass. When an
overridden method is called in sub class then sub class always called its own method i.e
superclass method simply become hidden.
An Example:
class A{
int superInstnace;
A(int si){
superInstnace = si;
}
void getInstance(){
[Link]("Inside super class A");
[Link]("superInstance is " + superInstnace);
}
}
B(int si){
super(si*2);
subInstance = si;
}
void getInstance(){
[Link]("Inside sub class B");
[Link]("subInstance is " + subInstance);
}
void callGetInstance(){
getInstance();
}
}
class OverRidingDemo {
public static void main(String[] args) {
B bobj = new B(10);
[Link]();
[Link]();
[Link]();
}
}
In the example given above we have created a method in superclass A, having name
getInstance and do not accept any parameter and have also created a method in class B having
same prototype. when we are trying to call it from object of class B or inside B it always call
subclass version of method getInstance() hence superclass version is simply hidden. To call
superclass version of getInstance() simply use super keyword inside class B.
An Example:
A(int si){
superInstnace = si;
}
void getInstance(){
[Link]("Inside super class A");
[Link]("superInstance is " + superInstnace);
}
}
class B extends A{
int subInstance;
B(int si){
super(si*2);
subInstance = si;
}
void getInstance(){
[Link]();
[Link]();
class OverRidingDemo {
public static void main(String[] args) {
B bobj = new B(10);
[Link]();
}
}
An Example:
class A{
int i = 0;
}
class B extends A{
int j = 0;
}
class SprClass{
A getInstance(){
[Link]("Inside class SuperClass");
return (new A());
}
}
class CovariantDemo{
public static void main(String a[]){
SbClass sbc = new SbClass();
SprClass spc = new SprClass();
A a = [Link]();
B b = [Link]();
[Link](”i is ” + a.i);
[Link](”i is ” + b.j)
}
}
In the code given above we have created superclasses that are A and SprClass that have
subclasses B and SbClass. We have created a method getInstance() in class SprClass that
returns an object of A and override that method in SbClass that returns an object of B. it is ok to
do so because B is subtype of A. but if alter that code slightly exchange return type for both,
then compiler will produce error.
An Example:
class A{
int i = 0;
}
class B extends A{
int j = 0;
}
class SprClass{
B getInstance(){
[Link]("Inside class SuperClass");
return (new B());
}
}
class CovariantDemo{
public static void main(String args[]){
SbClass sbc = new SbClass();
SprClass spc = new SprClass();
A a = [Link]();
B b = [Link]();
In Code segment given above we have provided just exchanged return type of both and when
we are trying to compile them we are getting error. To correct that code we have to exchange
return type in class SprClass and SbClass.
Let us start our discussion with a statement that superclass reference variable can point to child
class object. Java uses that concept to resolve overridden method calling at run time. Java
determines which version of that method to execute based upon the type of the object being
referred to, at the time the call occurs. Thus, this determination is made at run time. When
different types of objects are referred to, different versions of an overridden method will be
called. Decision of calling a specific implementation of same interface is made at run time on the
basis of object being referred.
Thus if superclass have a method that is also overridden by subclass then when different types
of objects are pointed by superclass reference variables then different version of methods are
executed.
An Example:
class A{
void overRided(){
[Link]("Inside overRided of class A");
}
}
class B extends A{
void overRided(){
[Link]("Inside overRided of class B");
}
}
class C extends B{
void overRided(){
[Link]("Inside overRided of class C");
}
}
A temp;
temp = cobj;
[Link]();
temp = bobj;
[Link]();
temp = aobj;
[Link]();
}
}
In the code segment given above in first three calls of overRided method, object and reference
variables belong to same class hence they call their own methods but in last three cases calling
of specific implementation takes place on the basis of object being referred and that decision is
taken at run time.
class EnggStudent{
int tutionFee;
EnggStudent(int tutionFee){
[Link] = tutionFee;
}
int getFee(){
return tutionFee;
}
}
Also college provide bus facility and hostel facility for students. Student either take bus facility or
hostel facility. To do so we have created subclass of EnggStudent that is
DayScholerEnggStudent, it represent a student that take bus facility.
int getFee(){
return (tutionFee + busFee);
}
}
int getFee(){
return (tutionFee + hostelFee);
and creating a class that contains main method (also known as main class).
class DmdDemo{
public static void main(String args[]){
EnggStudent es = new EnggStudent(55000);
HostelerEnggStudent hes = new HostelerEnggStudent(55000,42000);
DayScholerEnggStudent des = new DayScholerEnggStudent(55000,13200);
es = hes;
[Link]("Total fee of an engineering student with hostel is " +
[Link]());
es = des;
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());
}
}
Now college have decided to conduct certification courses for III year students and let student to
join that course by their choice. For sake of simplicity we are created another subclass of
EnggStudent that is CertifiedEnggStudent as follow.
int getFee(){
return (tutionFee + certificationFee);
}
}
class DmdDemo{
public static void main(String args[]){
EnggStudent es = new EnggStudent(55000);
HostelerEnggStudent hes = new HostelerEnggStudent(55000,42000);
DayScholerEnggStudent des = new DayScholerEnggStudent(55000,13200);
CertifiedEnggStudent ces = new CertifiedEnggStudent(55000,6000);
es = hes;
[Link]("Total fee of an engineering student with hostel is " +
[Link]());
es = des;
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());
es = ces;
[Link]("Total fee of an engineering student with certification course is
" + [Link]());
}
}
Now one interesting thing to note here is that to run that program we just have to compile files
that contain CertifiedEnggStudent class and main class that is DmdDemo. We dont have to
make any alteration and compiling previosly written classes that are DayScholerEnggStudent,
EnggStudent and HostelerEnggStudent. That is main advantange of Dynamic method dispatch.
With the help of method overriding we can allow a subclass to define a general interface and its
implementation at its own level that is common to its all derivatives, along with allowing
derivatives to create their specific implemented. Thus in simple words we can say method
overriding allow us to implement 'Single interface, multiple methods' aspect of polymorphism.
Abstract classes:
Sometime we find our self in situation when it is not possible for a superclass to provide a
meaningful implementation of a method or simply we can say that subclasses want to fulfill a
similar a role in different ways through different implementation. One way to handle such
situation is to provide a meaning less implementation of a method in superclass and let
subclasses to implement them according to their own need, that approach is simply helpful in
debugging but not a very useful solution in case of deployment. Another approach to handle
such situation is creating abstract methods. An abstract method is a method whose
implementation is not provided in superclass just declaration is provided and subclass of that
class must provide implementation of abstract method.
general form of abstract method is:
abstract method-name(parameter-list);
An class that contains abstract method must be declared as abstract. To declare a class
abstract simply place abstract keyword before class declaration. Although it is possible that an
abstract class have some methods with implementation. An abstract class can not be
instantiated i.e. it is not possible to create an object of that class using new keyword. Although it
is possible to create a reference of an abstract class. Any class that extends an abstract class
must implement all abstract method of its superclass or becomes abstract itself.
An Example:
abstract class A {
abstract void abstractMethod();
void concreteMethod(){
[Link]("I am inside concreteMethod of class A");
}
}
void anotherConcreteMethod(){
[Link]("I am inside anotherConcreteMethod of C");
}
}
class AbstractDemo {
public static void main(String[] args) {
//error unable to instantiate class A because it is abstract
//A a = new A();
[Link]();
[Link]();
}
}
In the code that we have given above we have created reference of class A and that reference
is able to point object of class B because superclass reference variable can point to child class
object. With that approach java implements run time polymorphism.
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
figref = r;
[Link]("Area is " + [Link]());
figref = t;
[Link]("Area is " + [Link]());
}
}
An Example:
class A{
final void unOverRided(){
[Link]("I am final, don’t override me");
}
}
class B extends A{
void unOverRided(){
[Link]("I am final, don’t override me");
}
}
class UnOverRidingDemo{
public static void main(String args[]){
A a = new A();
[Link]();
a = new B();
Compiling that program using command javac [Link] will report an error.
An Example:
final class NoSubClass{
int i;
NoSubClass(){
i = 10;
}
}
Unit-X
packages & Interfaces
Packages:
Consider a scenario in which a large number of programmers are working on a project and they
are getting run out of meaningful names because they are putting all their classes in common
namespace. Also all code is accessible for everyone that may cause accidental alteration.
Creating a package:
Simply one thing that we have to understand is, To create a package we must create a folder, or
folder for an operating system is equivalent to packages for JVM.
To put a class in a packages simply put following statement before starting of class
package pkgname;
Here pkgname is placeholder for package name. for any class to be part of a package its .class
file must be stored in directory having name as pkgname. pkgname is case significant, folder
name is same as pkgname. A package may have many classes.
Java allow to create a hierarchy of packages. To do so separate packages names with .(dot).
general form of package hierarchy is
package pkg1.[pkg2.[pkg3]];
An Example:
Create a folder with name mypack then create a file [Link] inside mypack. Now
type following statement
package mypack;
package mypack;
class PackageDemo{
public static void main(String args[]){
[Link]("A short Example of package");
}
}
To compile that program simply move inside mypack directory from terminal and type
javac [Link]
Now first method to run that program is let JVM look for mypack in current directory. To do so
simply move to parent directory of mypack and type fully qualified name of class. Fully qualified
name contains package name and classname separated by dot.
java [Link] emo
In that method we must be in parent directory of package. To run that program from other
location we have to set CLASSPATH environment variable. To do so simply type following
command on terminal
set CLASSPATH=absolute path of package’s parent directory (Inclusive)
Now we can run our java program from any location of computer because JVM read location of
package from CLASSPATH environment variable.
Importing packages
There are two ways so that you can use the public classes stored in package.
1. Using the fully-qualified class name to access class. To create an object of class (say A)
that is stored in a package (say mypack) we will simply write
mypack.A obj-name = new mypack.A([actual-arguments]);
2. Using import keyword: Using fully-qualified name each time requires a lot of typing, To
save a programmer from that, java provides import keyword. import keyword allow to
include entire package or specific class(es) of a package in program. After importing
them no need to use fully-qualified name. General form of import statement is
import package-name.[subpackage-name].(classname|*);
using * tells compiler to add all members of packages. While only if a small number of
classes are required then it is better to import them by their names.
An Example:
//Filename: [Link], Folder: p1
package p1;
public class A{
private int privateVar;
int packagePrivate;//no modifier is here
protected int protectedVar;
public int publicVar;
public A(){
privateVar = 10;
packagePrivate = 20;
package p1;
class B extends A{
B(){
[Link]("Inside class B");
//[Link]("privateVar is " + privateVar);
[Link]("packagePrivate is " + packagePrivate);
[Link]("protectedVar is " + protectedVar);
[Link]("publicVar is " + publicVar);
}
}
package p1;
class C{
C(){
A aObj = new A();
[Link]("\nInside class C");
//[Link]("privateVar is " + [Link]);
[Link]("packagePrivate is " + [Link]);
[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
}
}
package p1;
class Demo{
public static void main(String args[]){
B bObj = new B();
C cObj = new C();
}
}
package p2;
class D extends p1.A{
D(){
[Link]("Inside class D");
//[Link]("privateVar is " + privateVar);
//[Link]("packagePrivate is " + packagePrivate);
[Link]("protectedVar is " + protectedVar);
[Link]("publicVar is " + publicVar);
}
}
package p2;
import p1.A;
class E{
E(){
A aObj = new A();
[Link]("\nInside class E");
//[Link]("privateVar is " + [Link]);
//[Link]("packagePrivate is " + [Link]);
//[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
}
}
package p2;
class Demo{
public static void main(String args[]){
D dObj = new D();
E eObj = new E();
}
package p3;
import p2.*;
import p1.*;
class F{
public static void main(String args[]){
p1.A aObj1 = new p1.A();
[Link]("Inside class F");
//[Link]("privateVar is " + [Link]);
//[Link]("packagePrivate is " + [Link]);
//[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
p2.A aObj2 = new p2.A();
}
}
Let say we have placed all three folder p1,p2 & p3 in a common folder (say mypack). To
compile all classes of p1, open terminal and go inside p1 directory then write
javac *.java
Now to compile classes of folder p2 simply move inside p2 directory from terminal. if we directly
use command
javac *.java
then compiler will report us errors because it does not found classes of p1. By default compiler
looks for classes of p1 in current directory that is p2. To let compiler know about correct location
of p1 we have to set CLASSPATH.
Similarly compile classes of p3 & we can run that program by using fully qualified name of main
class(es).
Interfaces:
Interfaces are similar to classes but all methods defined inside interface are abstract method i.e.
they are lacking body. Other than methods, an interface can only have static final members.
Similar to abstract class it is not permitted to create an object of an interface but it is okay to
create reference of an interface.
Interface allow us to create a standard and public way of specifying the behavior of a
class. An interface specify what a class must do regardless how to do it. In simple words we can
say that an interface allow us to define contract and hide implementation, thus we can say
interface support encapsulation. Interface allow to change implementation without affecting
contract to caller.
Interfaces support dynamic method dispatch. With the help of interface caller does not need
implementation at compile time It only need interface, because object association is made to
interface at run time.
If a class implements an interface, it has to implement all methods of that interface. A single
class can implements any number of interfaces and a single interface can be implemented by
any number of classes. If a class implements an interface but fails to define all method of
interface, then class must be declared as abstract class.
Defining an Interface:
General form of interface is
access-specifier interface interface-name{
static final data-type var-name1 = value;
static final data-type var-name2 = value;
.
.
static final data-type var-nameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
.
.
return-type method-nameN(parameter-list);
}
Only two access specifiers are allowed, no-modifier or public. if interface do not have any
Implementing an Interface:
To implement an interface, a class should include implements clause in class definition, and
provide implementation of all methods that are defined in a interface. General form of a class
implementing an interface is:
access class class-name [extends superclass] implements interface-name1 [,interface-
name2 [,..]] {
//class body with all methods body of interface(s)
}
Here access is either public or default. It is perfectly okay for a class to implement more than
one interface. To do so, just separate interfaces with comma. Implementing more than one
interface provide facility of multiple inheritance. Signature of methods in interfaces and in its
implementing class must be same.
An Example:
interface Demo {
int getValue();
}
A() {
i = 20;
}
int returnSquare() {
return (i*i);
}
In the example given above we have create an interface named as Demo and a class named A
that implement interface Demo and provide implementation of method getValue. class A have
one more methods that is returnSquare(). It is allowed for a class that implement interface(s) to
have their own members.
An Example:
interface Demo {
int getValue();
}
A() {
i = 20;
}
int returnSquare() {
return (i*i);
}
}
B(){
j = 40;
}
int returnCube(){
return (j*j*j);
}
}
class C{
public static void main(String args[]) {
Demo a = new A();
[Link]("Class A implements Demo interface");
[Link]("Value of i is " + [Link]());
A aobj = new A();
[Link]("square is " + [Link]() + "\n");
In the example given above we have created one more class B that implements interface Demo.
In class C we have created reference variables of interface Demo and that variable is pointing to
object of class A. When we are calling methods of getValue() then implementation of class A get
executed similarly another reference variable of interface that is b, is pointing to object of class
B when calling method getValue() from that, implementation of class B is executed. decision of
calling correct version is taken at run time. Thus Interfaces helps to implement run-time
polymorphism in java. Although reference variable of interface do not have any knowledge of
additional members of its implementing class. To access additional members of class we can
not use reference variables of interface, we have to create object of implementing class with
reference of same.
An Example:
interface Demo{
void getValue();
}
Incomplete(){
i = 10;
}
void show(){
[Link](“i is ” + i);
}
}
Variables in interfaces:
Let say we have created an interface that has no methods in it but it has some variables with
initial values. All variables in an interface are static and final, if such interface is implemented by
several classes then all these variables will be available to all classes. Because interface do not
have any methods hence implementing class does not bother to implement anything. Creating
such interfaces are similar to create a header file with constants in C/C++.
A(int i){
this.i = i;
}
boolean isNumberPositive(){
if(i > 0){
return YES;
}
return NO;
}
}
B(int i){
this.i = i;
}
boolean isNumberNegative(){
if(i < 0){
return YES;
}
return NO;
}
}
class C{
public static void main(String a[]){
A adi = new A(-10);
B bdi = new B(-10);
An Example:
interface Constant{
boolean YES = true;
boolean NO = false;
}
interface A{
boolean isGreater();
}
interface B{
boolean isLesser();
}
class D implements C{
static int i, j;
From example given above interface C inherits A,B and Constant. Interfaces supports multiple
inheritance means one interface can inherits more than one interface at a time.
Nested classes:
So far we have learned about classes that are defined directly within a package. such classes
are also known as top level classes. Java provides us facility to define classes inside another
class, such classes that are defined inside another are called nested classes. Let say we have a
class A, that is defined directly inside a package and we have another class B that is defined
inside class A. class B is simply known as nested class and class A is known as enclosing
class. class B can access all members of class A but class A does not have any knowledge
about class B.
Inner class:
Inner classes are defined inside another class but do not have static modifier with it. Such
classes have access to all members of their encapsulating class and they don’t need object for
accessing. Such classes are specific to each object.
Local class:
These are the classes that are defined a block of a class. Similar to a local variable, such
classes are local to block hence they are not visible outside their block. A local can access all
parameters and local variables of its block only if they are declared final.
An Example:
package p2;
void showVar(){
[Link]();
[Link]("Inside inner class");
[Link]("i is " + i);
[Link]("j is " + j);
[Link]("m is " + m);
}
}
void showijn(){
[Link]("Inside top-level class");
[Link]("i is " + i);
[Link]("j is " + j);
//[Link]("n is " + n);
}
void localMethod(){
C c =new C();
[Link]();
}
}
class D{
public static void main(String args[]){
A a = new A();
[Link]();
[Link]();
[Link]();
[Link]("Creating inner class object");
in the code segment we have placed so many java code in single line comments, removing
commenting from these code will produce compile time errors.
We have also created object of inner class B in main method. General from of doing so is:
OuterClass outerClass = new OuterClass();
[Link] innerClass = [Link] InnerClass();
Another type of local class is anonymous class, these are classes that are defined inside a
block but do not have any name. we will discuss about them later.
Here
● c indicates that we want to create a jar file.
● f indicate that output will go to a file rather then to a console.
● jar-file-name is the name of resulting file, by convention jar-file-name should have .jar
extension but it is not mandatory.
● input-file(s) is a space separated list of files that we want to add in directory. To add all
files of directory we can pass * as an arguments.
v Produces verbose output on standard output stream while the jar file
is being built. It tells name of file that are added to jar.
An example
Consider package p1 that we have discussed in example of packages. To create a jar file and
run our program with jar file we have to JVM know about main class. To do so we have to
create a file name as mainClass (without any extension, in parent directory of p1) and put
following content in it
Main-Class: [Link] (with a carriage return)
When we create a JAR file, it automatically receives a default manifest file. There can be only
one manifest file in an archive, and it always has the pathname
META-INF/[Link]
When we create a JAR file, the default manifest file simply contains the following:
Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
These lines show that a manifest's entries take the form of "header: value" pairs. The name of a
header is separated from its value by a colon. The default manifest conforms to version 1.0 of
the manifest specification and was created by the 1.6.0 version of the JDK
Inside class C
packagePrivate is 20
protectedVar is 30
publicVar is 40