Java 18CS653
Java 18CS653
__________________________________________________
MODULE 1
An Overview of Java:
Object-Oriented Programming, A First Simple Program, A
Second Short Program, Two Control Statements, Using Blocks of Code, Lexical
Issues, The Java Class Libraries,
Data Types, Variables, and Arrays:
Java Is a Strongly Typed Language, The Primitive Types,
Integers, Floating-Point Types, Characters, Booleans, A Closer Look at Literals,
Variables, Type Conversion and Casting, Automatic Type Promotion in
Expressions, Arrays, A Few Words About Strings
Text book 1: Ch 2, Ch 3
RBT: L1, L2
__________________________________________________________________________________
MITM 1
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Object Oriented Programming
Two approaches are there to solve the problem and in program writing:
Procedureoriented and object oriented.
Procedure Oriented:
Example: C etc
Problems increases in procedure oriented as the program grows larger and more
complex.
Object Oriented:
Example:
A database system hides certain details of the way in which data is stored and
created and maintained.
1. Encapsulation
2. Inheritance
3. Inheritance
4. Polymorphism
1.Encapsulation:
Encapsulation is the mechanism that binds together code and data it manipulates, and
keeps both safe from outside interference and misuse.
In Java the basis of encapsulation is the class. A class defines the state and behavior
(data & code) that will be shared by set of objects.
When a class is created, the code and data is specified that constitute that class.
Collectively, these elements are called members of the class.
The data defined by the class are referred to as member variables or instance variables.
The code that operates on that data is referred to as member methods or methods.
__________________________________________________________________________________
MITM 3
Programming in Java (18CS653) Sangeetha G
__________________________________________________
2.Inheritence:
Inheritance is the process by which one object acquires the properties of another object.
By the use of inheritance, a class has to define only those qualities that make it unique.
The general qualities can be derived from the parent class or base class.
Example: A child inheriting behavioral properties from parents.
3.Polymorphism:
Example:
A person at the same time can have different characteristics. Like a man
at the same time is a father, a husband, an employee. So, the same person
possesses different behavior in different situations. This is called
polymorphism.
class Example
{
public static void main (String args [])
{
System.out.println("This is a simple Java program.");
}
}
__________________________________________________________________________________
MITM 4
Programming in Java (18CS653) Sangeetha G
__________________________________________________
2. Save the above program with .java extension, here file name and class name
should be same,
For Example: Example.java
From the above compilation the java compiler produces a bytecode(.class file)
Description:
1. A Closer Look at the First Sample Program Example.java, it includes several key
features that are common to all Java programs.
5. The one shown at the top of the program is called a multiline comment. This type of
comment must begin with /* and end with */.
6. Anything between these two comment symbols is ignored by the compiler. As the name
suggests, a multiline comment may be several lines long.
class Example {
This line uses the keyword class to declare that a new class is being defined.
Example is an identifier that is the name of the class. The entire class definition, including
all of its members, will be between the opening curly brace ({) and the closing curly brace
(}).
__________________________________________________________________________________
MITM 5
Programming in Java (18CS653) Sangeetha G
__________________________________________________
8.The next line in the program is the single-line comment, shown here:
This is the second type of comment supported by Java. A single-line comment begins
with a // and ends at the end of the line.
This line begins the main ( ) method. All Java applications begin execution by calling
main ( ),the line at which the program will begin executing. All Java applications begin
execution by calling main( ).The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a class member is preceded by
public, then that member may be accessed by code outside the class in which it is
declared.Static keyword defines the method as one that belongs to the entire class and not for
a particular object of the class. The main must always be declared as static.
10.The next line of code is shown here.
System.out.println("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by a new
line on the screen. Output is actually accomplished by the built-in println( ) method. In this
case, println() displays the string which is passed to it.
11.The first } in the program ends main( ), and the last } ends the Example class
definition
Output:
This is num: 100
The value of num * 2 is 200
Description:
1.The first new line in the program is shown here:
This line declares an integer variable called num.The keyword int specifies an integer type.
3.The next line of code outputs the value of num preceded by the string “This is num:”.
In this statement, the plus sign causes the value of num to be appended to the string that
precedes it, and then the resulting string is output.
4.The next line of code assigns num ,the value of num 2 times .Java uses the * operator to
indicate multiplication. After this line executes, num will contain the value 200
System.out.println(num);
First, the built-in method print( ) is used to display the string “The value of num * 2 is
”.Second line displays the value of num.
__________________________________________________________________________________
MITM 7
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Control Statements:
if statement
The if- statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluatesto
true.
if (condition) statement;
If the condition is true then the statement is executed, if false then statement will
beskipped
For Example:
class IfSample
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
if(x < y)
System.out.println("x is less than y");
}
}
Output:
x is less than y
In the above program ,if statement checks whether x is greater than y.if it is true then
it prints “x is less than y”
for loop
__________________________________________________________________________________
MITM 8
Programming in Java (18CS653) Sangeetha G
__________________________________________________
The general form of the traditional for statement:
//body
Iteration expression tells hoe the control variable has to change at each
iteration. Generally the increment or decrement operator is used to perform
iteration.
Example:
class ForTest
{
public static void main(String args[])
{
int x;
for(x = 0; x<5; x = x+1)
System.out.println("This is x: " + x);
}
}
output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
Example:
class Example
{
public static void main(String args[])
{
int
a=10;
if(a>0
)
{ // begin of block
System.out.println(―a is positive number‖);
System.out.println(― inside block‖);
}// end of block
}
}
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace
Java is a free from language- it means there is no need to follow any indentation rules.
Identifiers
Identifiers are used for class names, method names, and variable names.
They must not begin with a number, lest they be confused with a numeric literal.
__________________________________________________________________________________
MITM 10
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Java is case-sensitive, so VALUE is a different identifier than Value.
Literals
Literals in Java are sequence of characters that represents constant values to be
stored invariables. Java language specifies five major types of Literals. They are:
1. Integer Literals - Example: 100
2. Floating-point Literals- Example: 96.5
3. Character Literals-Example: ‘A’
4. String Literals - Example: “Hello”
5. Boolean Literals - Example: True
Separators:
Separators are the symbols that indicates where group of code are divided and
arranged. Some of the operators are:
Comments:
__________________________________________________________________________________
MITM 11
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Java supports three styles of comments:
Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
Single line comments: this type of comment begins with // and ends at the end
ofcurrent line
Ex: // Welcome to java Programming
Keywords
There are 50 keywords currently defined in the Java language.
These keywords, combined with the syntax of the operators and separators,
__________________________________________________________________________________
MITM 13
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Data Types, Variables, and Arrays
The Primitive Types Java defines eight primitive types of data: byte, short, int, long, char,
float, double, and boolean.
The primitive types are also commonly referred to as simple types, . These include four groups:
1.Integers :This type includes byte, short, int, and long, which are for whole-valued signed
numbers.
2.Floating-point numbers :This type includes float and double, which represent numbers
with fractional precision.
3.Characters:This group includes char, which represents symbols in a character set, like
letters and numbers.
4.Boolean :This group includes Boolean, which is a special type for representing true/false
values.
1.Integers
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values.
Many other computer languages support both signed and unsigned integers
Byte
This is a signed 8-bit type that has a range from –128 to 127.
For example, the following declares two byte variables called b and c:
__________________________________________________________________________________
MITM 14
Programming in Java (18CS653) Sangeetha G
__________________________________________________
byte b, c;
Short:
short t;
int
Floating point:
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively
Booleans Java has a primitive type, called boolean, for logical values. It can
have only one of two possible values, true or false.
The type float specifies a single-precision value that uses 32 bits of storage.
Double
Double precision, as denoted by the double keyword, uses 64 bits to store a value
Characters
__________________________________________________________________________________
MITM 15
Programming in Java (18CS653) Sangeetha G
__________________________________________________
In Java, the data type used to store characters is char.
Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are
no negative values.
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one
of two possible values, true or false.
Literals:
A constant value in Java is created by using a literal representation of it. There are 5
types ofliterals.
Integer Literals.
Floating-point Literals.
Character Literals.
String Literals.
Boolean Literals.
Integer literals:
Any whole number value is an integer literal.
__________________________________________________________________________________
MITM 16
Programming in Java (18CS653) Sangeetha G
__________________________________________________
These are all decimal values describing a base 10 number.
There are two other bases which can be used in integer literal, octal( base 8) where
0 is prefixed with the value, hexadecimal (base 16) where 0X or 0x is prefixed with
the integer value.
For Example:
The default type when you write a floating-point literal is double, but you
candesignate it explicitly by appending the D (or d) suffix
However, the suffix F (or f) is appended to designate the data type of a floating-
point literal as float.
We can also specify a floating-point literal in scientific notation using Exponent
(shortE ore), for instance: the double literal 0.0314E2 is interpreted as:
For Example:
Character Literals
They are 16-bit values that can be converted into integers and manipulated with the
integer operators, such as the addition and subtraction operators.
A literal character is represented inside a pair of single quotes. All of the visible ASCII
characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and ‘@’.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing
a sequence of characters between a pair of double quotes.
__________________________________________________________________________________
MITM 17
Programming in Java (18CS653) Sangeetha G
__________________________________________________
“Hello World”
The ASCII character set includes 128 characters including letters, numerals,
punctuation etc.
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can
have, true and false.
The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0.
Variables
The variable is the basic unit of storage in a Java program.
All variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
__________________________________________________________________________________
MITM 18
Programming in Java (18CS653) Sangeetha G
__________________________________________________
In Java, all variables must be declared before they can be used.
To declare one identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
Initializing a variable
A variable can be initialized in two ways. They are
Example:
Double pi=3.147;
(b)Dynamic Initialization
Example:
class Example
__________________________________________________________________________________
MITM 19
Programming in Java (18CS653) Sangeetha G
__________________________________________________
public static void main (String args[])
double a=10,
b=2.6; double
c=a/b;
System.out.println(“value of c is”+c);
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
__________________________________________________________________________________
MITM 20
Programming in Java (18CS653) Sangeetha G
__________________________________________________
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
It is often necessary to store a value of one type into the variable of another type.
In these situations, the value that is to be stored should be casted to destination type.
Assigning a value of one type to a variable of another type is known as Type Casting
Output:
Int value 100
Long value 100
When larger type value are assigned to a variable of smaller type, then explicit type
casting is to be performed.
Example:
double d = 100.04;
long l = (long)d;//explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
__________________________________________________________________________________
MITM 22
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Output:
Java automatically promotes each byte, short, or char operand to int when
evaluatingan expression.
byte b = 50;
The operands were automatically promoted to int when the expression was
evaluated, the result has also been promoted to int. Thus, the result of the
expression is now of type int, which cannot be assigned to a byte without the
use of a cast.
byte b = 50;
Java defines several type promotion rules that apply to expressions. They are as
follows:
1. First, all byte, short, and char values are promoted to int, as just described.
Arrays
An array is a group of like-typed variables that are referred to by a common name.
__________________________________________________________________________________
MITM 23
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Arrays of any type can be created and may have one or more dimensions.
To use an array in a program, an array variable must be declared to reference the array,
and the type of array must be specified. The syntax for declaring an array variable:
For Example:
Creating an array:
An array can be created by using new operator. The syntax is:
2. It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the
array tothe variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
The array elements are accessed through the index. Array indices always starts
from 0 to arrayRefVar_length-1.
__________________________________________________________________________________
MITM 24
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Example:
Following statement declares an array variable, a, creates an array of 5 elements of inttype and
assigns its reference to a. In order to access array elements for loop or foreach loop is used.
Example:
class TestArray
{
Example:
String str = "this is a test";
System.out.println(str);
Programs:
1.Write a java program to compute distance light travels using long variables.
class Light
{
public static void main (String args [])
{
int lightspeed; long days;
long seconds;
long distance; // approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.println("In " + days);
System.out.println(" days light will travel about);
System.out.println(distance + " miles.");
}
}
Output:
In 1000 days light will travel about 16070400000000 miles
Output:
Area of circle is 366.2496
Output:
ch1 and ch2: X Y
class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output:
ch1 contains X ch1 is now Y
__________________________________________________________________________________
MITM 27
Programming in Java (18CS653) Sangeetha G
__________________________________________________
5.Write a java program to demonstrate type conversion
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Output:
Conversion of int to byte.
I and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
__________________________________________________________________________________
MITM 28
Programming in Java (18CS653) Sangeetha G
__________________________________________________
MODULE 2
__________________________________________________________________________________
MITM 29
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions.
The operands of the arithmetic operators must be of a numeric type.
The following table lists the arithmetic operators:
For Example:
class BasicMath
{
public static void main (String args [])
{
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}
Output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
The Modulus Operator
The modulus operator, %, returns the remainder of a division operation.
It can be applied to floating-point types as well as integer types.
__________________________________________________________________________________
MITM 30
Programming in Java (18CS653) Sangeetha G
__________________________________________________
For Example:
class Modulus
{
public static void main(String args[])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output:
x mod 10 = 2
y mod 10 = 2.25
Increment and Decrement
The ++ and the – – are Java’s increment and decrement operators.
The increment operator increases its operand by one.
The decrement operator decreases its operand by one.
For example,
x = x + 1;
__________________________________________________________________________________
MITM 31
Programming in Java (18CS653) Sangeetha G
__________________________________________________
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output:
a=2
b=3
c=4
d=1
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer
types, long, int, short, char, and byte.
These operators act upon the individual bits of their operands.
--Table--
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~.The below table shows bitwise
logical operator.
A B A|B A&B A^B ~A
0 0 0 0 0 0
0 1 1 0 1 0
1 0 1 0 1 1
1 1 1 1 0 1
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the
operands is a 1, then the resultant bit is a 1.
For Example:
00101010 42
| 00001111 15
______________
00101111 47
__________________________________________________________________________________
MITM 33
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Write a java program to Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output:
a = 0011
b = 0110
__________________________________________________________________________________
MITM 34
Programming in Java (18CS653) Sangeetha G
__________________________________________________
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Operator Result
= Equal to
!= Not equal to
> Greater than
< Less than
Greater than or
>= equal to
<= Less than or equal to
Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
__________________________________________________________________________________
MITM 36
Programming in Java (18CS653) Sangeetha G
__________________________________________________
expression1 ? expression2 : expression3
Where expression1 can be any expression that evaluates to a Boolean
value. If expression1 is true, then expression2 is evaluated. Otherwise,
expression3 is evaluated. The result of the ? operation is that of the expression
evaluated. Both expression2 and expression3 are required to return the same
type.
For Example:
i < 0 ? -i : i
Write a java program to find the Largest of three numbers using
ternary operator:
class MaximumNumber
{
public static void main(String args[])
{
int a = 10, b = 25, c = 15, max;
max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("Maximum number among " + a+ ", " + b + " and
" + c + " is "+ max);
}
}
Output:
Maximum number among 10, 25 and 15 is 25
Operator Precedence
The Precedence of the operators is nothing but the priority given to each
operator in an expression
__________________________________________________________________________________
MITM 37
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Using Parentheses
Parentheses raise the precedence of the operations that are inside them.
For example,
consider the following expression:
a *( b + 3)
This expression first adds 3 to b and then multiples a right by that result.
__________________________________________________________________________________
MITM 38
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Control Statements
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program.
In java, control statements can be put into the following categories:
selection, iteration, and jump.
Selection statements allow your program to choose different paths of
execution based upon the outcome of an expression or the state of a
variable.
Iteration statements enable program execution to repeat one or more
statements
Jump statements allow your program to execute in a nonlinear fashion.
Selection Statements
Java supports two selection statements: if and switch. These statements
allow to control the flow of program’s execution based upon conditions
known only during run time.
__________________________________________________________________________________
MITM 39
Programming in Java (18CS653) Sangeetha G
__________________________________________________
1.The if statement
The if statement executes a block of code only if the specified expression
is true.
If the condotion is false, then the if block is skipped and execution
continues with the rest of the program.
Syntax:
if (<conditional expression>)
{
<statements>
}
Example:
public class Example
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
System.out.println("b > a");
}
}
Output:
b>a
2.The if else statement
If the condition is true, then statement1 is executed. Otherwise,
statement 2 is executed.
__________________________________________________________________________________
MITM 40
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Syntax:
if (condition)
{
statement1;
}
else
{
statement2;
}
Example:
class Example
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
else
System.out.println("b > a");
}
}
Output:
b>a
3.The if-else-if Ladder
The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be
executed.
__________________________________________________________________________________
MITM 41
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Example:
class Ladder
{
public static void main(String[] args)
{
int i = 20;
if (i == 10)
System.out.println("i is 10\n");
else if (i == 15)
System.out.println("i is 15\n");
else if (i == 20)
System.out.println("i is 20\n");
else
System.out.println("i is not present\n");
System.out.println("Outside if-else-if");
}
}
Output:
__________________________________________________________________________________
MITM 42
Programming in Java (18CS653) Sangeetha G
__________________________________________________
i is 20
Outside if-else-if
4.The switch statement
The switch case statement is a multi-way branch with several choices. A
switch is easier to implement than a series of if/else statements.
Structure of Switch:
The switch statement begins with a keyword, followed by an expression
that equates to a no long integral value.
Following the controlling expression is a code block that contains zero or
more labeled cases.
Each label must equate to an integer constant and each must be unique.
Working of switch case:
When the switch statement executes, it compares the value of the
controlling expression to the values of each case label.
The program will select the value of the case label that equals the value
of the controlling expression and branch down that path to the end of the
code block.
If none of the case label values matches, then none of the codes within the
switch statement code block will be executed. Java includes a default label
to use in cases where there are no matches.
Example:
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
__________________________________________________________________________________
MITM 43
Programming in Java (18CS653) Sangeetha G
__________________________________________________
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements
1.The while loop
The while statement is a looping construct control statement that executes
a block of code while a condition is true.
The condition can be any Boolean expression. The body of the loop will
be executed as long as the conditional expression is true. When condition
__________________________________________________________________________________
MITM 44
Programming in Java (18CS653) Sangeetha G
__________________________________________________
becomes false, control passes to the next line of code immediately
following the loop.
Syntax:
while(condition)
{
// body of loop
}
Example:
public class Example
{
public static void main(String args[])
{
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10)
{
System.out.println(count++);
}
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
__________________________________________________________________________________
MITM 45
Programming in Java (18CS653) Sangeetha G
__________________________________________________
2.The do-while loop
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop
terminates.
Example:
public class Example
{
public static void main(String args[])
{
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do
{
System.out.println(count++);
}while (count <= 10);
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
__________________________________________________________________________________
MITM 46
Programming in Java (18CS653) Sangeetha G
__________________________________________________
3.The for loop
The for loop is a looping construct which can execute a set of instructions a
specified number of times. It is a counter controlled loop.
Syntax:
for (<initialization>; <loop condition>; <increment expression>) {
<loop body>
}
Example:
public class Example
{
public static void main(String args[])
{
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++)
{
System.out.println(count);
}
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
__________________________________________________________________________________
MITM 47
Programming in Java (18CS653) Sangeetha G
__________________________________________________
__________________________________________________________________________________
MITM 48
Programming in Java (18CS653) Sangeetha G
__________________________________________________
sum += x;
}
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 55
Jump Statements
Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of your program.
1.The break statement
The break statement transfers control out of the enclosing loop (for, while,
do or switch statement).
A break statement is used when there is need to jump immediately to the
statement following the enclosing control structure.
Label can also be provided for a loop, and then label is used in the break
statement.
The Label name is optional, and is usually only used when it is to terminate
the outermost loop in a series of nested loops.
Syntax:
break; // the unlabeled form
break <label>; // the labeled form
Example:
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
__________________________________________________________________________________
MITM 49
Programming in Java (18CS653) Sangeetha G
__________________________________________________
{
if(i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
The continue statement in this example terminates the loop counting j and
continues with the next iteration of the loop counting i.
Output:
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
3.The return statement
The return statement exits from the current method, and control flow
returns to where the method was invoked.
Example:
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
__________________________________________________________________________________
MITM 52
Programming in Java (18CS653) Sangeetha G
__________________________________________________
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Output:
Before the return.
__________________________________________________________________________________
MITM 53
Programming in Java (18CS653) Sangeetha G
__________________________________________________
MODULE 3
Introducing Classes:
Class Fundamentals, Declaring Objects, Assigning Object Reference,
Variables, Introducing Methods, Constructors, The this Keyword, Garbage
Collection, The finalize( ) Method, A Stack Class.
A Closer Look at Methods and Classes:
Overloading Methods, Using Objects as Parameters, A Closer Look at
Argument Passing, Returning Objects, Recursion, Introducing Access Control,
understanding static, introducing final, Arrays Revisited.
Inheritance:
Inheritance, using super, creating a Multilevel Hierarchy, When
Constructors Are Called, Method Overriding, Dynamic Method Dispatch, Using
Abstract Classes, Using final with Inheritance, The Object Class.
Text book 1: Ch 6, Ch 7.1-7.9, Ch 8.
RBT: L1, L2
__________________________________________________________________________________
MITM 54
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Introducing Classes
The class is at the core of Java.
It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
Class Fundamentals
Class defines a new data type. Once defined, this new type can be used to
create objects of that type. Thus, a class is a template for an object, and an
object is an instance of a class.
Because an object is an instance of a class, you will often see the two words
object and instance used interchangeably.
The General Form of a Class
When a class is defined, its exact form and nature is declared. The data and
code is specified that operates on that data.
A class is declared by use of the class keyword.
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
….
type methodnameN(parameter-list)
{
// body of method
__________________________________________________________________________________
MITM 55
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
}
The data, or variables, defined within a class are called instance
variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class are called
members of the class.
Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy
of these variables.
Thus, the data for one object is separate and unique from the data for
another.
A Simple Class
Here is a class called Box that defines three instance variables: width, height,
and depth.
class Box
{
double width;
double height;
double depth;
}
As stated, a class defines a new type of data.In this case, the new data type
is called Box.
Create an object for the class.
Box mybox = new Box(); // create a Box object called mybox
After this statement executes, mybox will be an instance of Box.
Thus, every Box object will contain its own copies of the instance variables
width,height, and depth.
__________________________________________________________________________________
MITM 56
Programming in Java (18CS653) Sangeetha G
__________________________________________________
To access these variables, the dot (.) operator is used.The dot operator links
the name of the object with the name of an instance variable.
For example, to assign the width variable of mybox object with the value
100, the following statement is used.
mybox.width = 100;
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
__________________________________________________________________________________
MITM 57
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Declaring Objects
When a class is created, a new data type is created. Obtaining objects of a
class is a two-step process.
1.First, a variable of the class type must be declared. This variable does not define
an object. Instead, it is simply a variable that can refer to an object.
2.Second, acquire a physical copy of the object and assign it to that variable by
using new operator.
The new operator dynamically allocates memory for an object and returns
a reference to it.
This reference is, more or less, the address in memory of the object
allocated by new.This reference is then stored in the variable.
Thus, in Java, all class objects must be dynamically allocated.
Box mybox = new Box();
Below shows in declaring objects in two steps:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box.After
this line executes, mybox contains the value null, which indicates that it
does not point to an actual object.
Next line allocates an actual object and assigns a reference to it to mybox.
mybox holds the memory address of the actual Box object. class-var is a
variable of the class type being created. The classname is the name of the
class that is being instantiated.
The class name followed by parentheses specifies the constructor for the
class.
Constructor:
A constructor defines when an object of a class is created.
Constructors are an important part of all classes and have many significant
__________________________________________________________________________________
MITM 58
Programming in Java (18CS653) Sangeetha G
__________________________________________________
attributes.
It is important to understand that new allocates memory for an object
during run time.
The advantage of this approach is that a program can create as many or as
few
objects as it needs during the execution of the program.
However, since memory is finite, it is possible that new will not be able to
allocate memory for an object because insufficient memory exists.
A class creates a new data type that can be used to create objects.
That is, a class creates a logical framework that defines the relationship
between its members. When an object of a class is declared, an instance is
created of that class.
Thus, a class is a logical construct. An object has physical reality.Assigning
object Reference Variables.Object reference variables act differently when
an assignment takes place.
Box b1 = new Box();
Box b2 = b1;
After this fragment executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part
of the original object.
It simply makes b2 refer to the same object as does b1.Thus, any changes
made to the object through b2 will affect the object to which b1 is referring,
since they are the same object.
Although b1 and b2 both refer to the same object, they are not linked in
any other way.
Box b1 = new Box();
Box b2 = b1;
// ...
__________________________________________________________________________________
MITM 59
Programming in Java (18CS653) Sangeetha G
__________________________________________________
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Introducing methods
The general form of a method:
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any
valid type, including class types that is created.
If the method does not return a value, its return type must be void.
The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs separated
by commas.
Parameters are essentially variables that receive the value of the arguments
passed to the method when it is called.
If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling
routine
using the following form of the return statement:
return value;
Here, value is the value returned.
Adding a Method to the Box Class
class Box {
double width;
double height;
double depth;
// display volume of a box
__________________________________________________________________________________
MITM 60
Programming in Java (18CS653) Sangeetha G
__________________________________________________
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of first box
mybox1.volume();
}
}
Output:`
Volume is 3000.0
Volume is 162.0
The following two lines of code:
mybox1.volume();
The first line invokes the volume( ) method on mybox1. That is, it calls
volume( ) relative to the mybox1 object, using the object’s name followed
by the dot operator.Thus, the call to mybox1.volume( ) displays the
volume of the box defined by mybox1.
The instance variables width, height, and depth are referred to directly,
__________________________________________________________________________________
MITM 61
Programming in Java (18CS653) Sangeetha G
__________________________________________________
without preceding them with an object name or the dot operator.
When a method uses an instance variable that is defined by its class,
directly without explicit reference to an object and without use of the dot
operator.
Returning a Value
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume( )
{
return width * height * depth;
}
}
class BoxDemo4
{
public static void main(String args[])
{
Box mybox1 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// get volume of first box
vol = mybox1.volume();
__________________________________________________________________________________
MITM 62
Programming in Java (18CS653) Sangeetha G
__________________________________________________
System.out.println("Volume is " + vol);
}
}
when volume( ) is called, it is put on the right side of an assignment
statement.On the left is a variable, in this case vol, that will receive the
value returned by volume( ).
Thus, after vol = mybox1.volume(); executes, the value of
mybox1.volume( ) is 3,000 and this value then is stored in vol.
There are two important things to understand about returning values:
1.The type of data returned by a method must be compatible with the return
type specified by the method. For example, if the return type of some method
is boolean,the variable receiving the value returned by a method must also be
Boolean.
Adding a Method That Takes Parameters
A parameterized method can operate on a variety of data and to be used in a
number of slightly different situations
int square( )
{
return 10 * 10;
}
Above method,return the value of 10 squared,
The same method with a parameter can be written as:
int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called with. That
is,square( ) is now a general-purpose method that can compute the square of any
__________________________________________________________________________________
MITM 63
Programming in Java (18CS653) Sangeetha G
__________________________________________________
integer value, rather than just 10.
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
In the first call to square( ), the value 5 will be passed into parameter i.
In the second call, i will receive the value 9.
The third call, passes the value of y, which is 2 in this example.
As these examples show, square( ) is able to return the square of whatever
data it is passed. A parameter is a variable defined by a method that
receives a value when the method is called.
For example, in square( ), i is a parameter.
An argument is a value that is passed to a method when it is Invoked.
For example, square(100) passes 100 as an argument. Inside square( ), the
parameter i receives that value.Thus, a better approach to setting the
dimensions of a box is to create a method that takes the dimensions of a
box in its parameters and sets each instance variable appropriately.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume( )
{
return width * height * depth;
__________________________________________________________________________________
MITM 64
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
// sets dimensions of box
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}
class BoxDemo5
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The setDim( ) method is used to set the dimensions of each box.
__________________________________________________________________________________
MITM 65
Programming in Java (18CS653) Sangeetha G
__________________________________________________
For example:
when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter w,
20 is copied into h, and 15 is copied into d.Inside setDim( ) the values of w, h,
and d are then assigned to width, height, and depth, respectively.
Constructors
A constructor initializes an object immediately upon creation.It has the
same name as the class in which it resides and is syntactically similar to a
method.
Once defined, the constructor is automatically called immediately after the
object is created, before the new operator completes.
Constructors have no return type, not even void.This is because the
implicit return type of a class constructor is the class type itself.
It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object
immediately.
For Example:
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box( )
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
__________________________________________________________________________________
MITM 66
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
// compute and return volume
double volume( )
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[ ])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume( );
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
When this program is executed, it generates the following results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
__________________________________________________________________________________
MITM 67
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Using new operator:
class-var = new classname( );
Box mybox1 = new Box( );
new Box( ) is calling the Box( ) constructor new .
When a constructor explicitly is not defined for a class, then Java creates a
default constructor for the class
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box
object, it is not useful when all boxes have the same dimensions.The easy solution
is to add parameters to the constructor.
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume( )
{
return width * height * depth;
}
}
__________________________________________________________________________________
MITM 68
Programming in Java (18CS653) Sangeetha G
__________________________________________________
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
The this keyword
Sometimes a method will need to refer to the object that invoked it.To
allow this, Java defines the this keyword. this can be used inside any
method to refer to the current object
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
__________________________________________________________________________________
MITM 69
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
Uses of this:
To overcome shadowing or instance variable hiding.
To call an overload constructor
Instance Variable Hiding
It is illegal in Java to declare two local variables with the same name inside
the same or enclosing scopes.
However, when a local variable has the same name as an instance variable,
the local variable hides the instance variable.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
Since objects are dynamically allocated by using the new operator, it is yet
to be known how such objects are destroyed and their memory released for
later reallocation. The deallocation is done automatically. The technique
that accomplishes this is called garbage collection.
when no references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed.
There is no explicit need to destroy objects as in C++.
Garbage collection only occurs sporadically (if at all) during the execution
of the program.
It will not occur simply because one or more objects exist that are no longer
used.
__________________________________________________________________________________
MITM 70
Programming in Java (18CS653) Sangeetha G
__________________________________________________
The finalize( ) Method
Sometimes an object need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or
character font, then it is needed to make sure these resources are freed before an
object is destroyed.
To handle such situations, Java provides a mechanism called finalization.
By using finalization, specific actions can be defined that will occur when an
object is just about to be reclaimed by the garbage collector.
The general form of finalize( ) method is:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by
code defined outside its class. It is important to understand that finalize( ) is only
called just prior to garbage collection.Therefore, program should provide other
means of releasing system resources,
etc., used by the object.
A Stack Class
class Stack
{
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
top = -1;
}
// Push an item onto the stack
__________________________________________________________________________________
MITM 71
Programming in Java (18CS653) Sangeetha G
__________________________________________________
void push(int item)
{
if(top==9)
System.out.println("Stack is full.");
else
stck[++top] = item;
}
// Pop an item from the stack
int pop( )
{
if(top < 0)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++)
mystack1.push(i);
__________________________________________________________________________________
MITM 72
Programming in Java (18CS653) Sangeetha G
__________________________________________________
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
Output:
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
__________________________________________________________________________________
MITM 73
Programming in Java (18CS653) Sangeetha G
__________________________________________________
14
13
12
11
10
Overloading Methods
In Java it is possible to define two or more methods within the same class
that share the same name, as long as their parameter declarations are
different.
When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
Method overloading is one of the ways that Java supports
polymorphism.When an overloaded method is invoked, Java uses the type
and/or number of arguments as its guide to determine which version of the
overloaded method to be called.Thus, overloaded methods must differ in
the type and/or number of their parameters.
While overloaded methods have different return types, the return type
alone is insufficient to distinguish two versions of a method.
class OverloadDemo
{
void test( )
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
__________________________________________________________________________________
MITM 74
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[ ])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
__________________________________________________________________________________
MITM 75
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
When an overloaded method is called, Java compiler looks for a match
between the arguments used to call the method and the method’s
parameters.
For example:
// Automatic type conversions apply to overloading.
class OverloadDemo
{
void test( )
{
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a)
{
System.out.println("Inside test(double) a: " + a);
}
}
__________________________________________________________________________________
MITM 76
Programming in Java (18CS653) Sangeetha G
__________________________________________________
class Overload
{
public static void main(String args[ ])
{
OverloadDemo ob = new OverloadDemo( );
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
Output:
No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
When test( ) is called with an integer argument inside Overload, no
matching method is found.Java can automatically convert an integer into a
double, and this conversion can be used to resolve the call.
Therefore, after test(int) is not found, Java elevates i to double and then
calls test(double). if test(int) had been defined, it would have been called
instead. Java will employ its automatic type conversions only if no exact
match is found.
When a method is overloaded, each version of that method can be
performed any desired activity. There is no rule that overloaded methods
must relate to one another.
__________________________________________________________________________________
MITM 77
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Overloading Constructors
In addition to overloading normal methods, a constructor methods can also be
overloaded.
For Example:
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box( )
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
__________________________________________________________________________________
MITM 78
Programming in Java (18CS653) Sangeetha G
__________________________________________________
// compute and return volume
double volume( )
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[ ])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
__________________________________________________________________________________
MITM 79
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Volume of mycube is 343.0
Using Objects as Parameters
simple types as parameters to methods is being used till now. However, it
is both correct and common to pass objects to methods.
For example, consider the following program:
// Objects may be passed to methods.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o)
{
if(o.a == a && o.b == b)
return true;
else
return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
__________________________________________________________________________________
MITM 80
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Output:
ob1 == ob2: true
ob1 == ob3: false
In the above program, the equals( ) method inside Test compares two
objects for equality and returns the result.
That is, it compares the invoking object with the one that it is passed. If
they contain the same values, then the method returns true. Otherwise, it
returns false. Although Test is a class type created by the program, it is
used in just the same way as Java’s built-in types.
One of the most common uses of object parameters involves constructors.
__________________________________________________________________________________
MITM 81
Programming in Java (18CS653) Sangeetha G
__________________________________________________
affect the argument used to call the subroutine.
Java uses both approaches, when a primitive type is passed to a method, it
is passed by value. Thus, the parameter that receives the argument has no
effect outside the method.
For example, consider the following program:
// Primitive types are passed by value.
class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[ ])
{
Test ob = new Test( );
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
Output:
a and b before call: 15 20
a and b after call: 15 20
__________________________________________________________________________________
MITM 82
Programming in Java (18CS653) Sangeetha G
__________________________________________________
When an object is passed to a method, the situation changes dramatically,
because objects are passed by call-by-reference.
Thus, when this reference to a method is passed, the parameter that receives
it will refer to the same object as that referred to by the argument.
For example, consider the following program:
// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[ ])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
__________________________________________________________________________________
MITM 83
Programming in Java (18CS653) Sangeetha G
__________________________________________________
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Returning Objects
A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen( ) method returns an
object in which the value of a is ten greater than it is in the invoking object.
// Returning an object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen( )
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[ ])
{
__________________________________________________________________________________
MITM 84
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Recursion
Java supports recursion. Recursion is the process of defining something in
terms of itself. As it relates to Java programming, recursion is the attribute
that allows a method to call itself.
A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a
number. The factorial of a number N is the product of all the whole
numbers between 1 and N.
For example,
3 factorial is 1 × 2 × 3, or 6.
// A simple example of recursion.
class Factorial
{
// this is a recursive method
int fact(int n)
__________________________________________________________________________________
MITM 85
Programming in Java (18CS653) Sangeetha G
__________________________________________________
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[ ])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
When a method calls itself, new local variables and parameters are
allocated storage on the stack, and the method code is executed with these
new variables from the start.
As each recursive call returns, the old local variables and parameters are
removed from the stack, and execution resumes at the point of the call
inside the method.
Many recursive calls to a method could cause a stack overrun. Because
__________________________________________________________________________________
MITM 86
Programming in Java (18CS653) Sangeetha G
__________________________________________________
storage for parameters and local variables is on the stack and each new call
creates a new copy of these variables, it is possible that the stack could be
exhausted.
If this occurs, the Java run-time system will cause an exception.
One more example of recursion. The recursive method printArray( ) prints the
first i elements in the array values.
// Another example that uses recursion.
class RecTest
{
int values[ ];
RecTest(int i)
{
values = new int[i];
}
// display array -- recursively
void printArray(int i)
{
if(i==0) return;
else
printArray(i-1);
System.out.println("[" + (i-1) + "] " + values[i-1]);
}
}
class Recursion2
{
public static void main(String args[ ])
{
RecTest ob = new RecTest(10);
__________________________________________________________________________________
MITM 87
Programming in Java (18CS653) Sangeetha G
__________________________________________________
int i;
for(i=0; i<10; i++)
ob.values[i] = i;
ob.printArray(10);
}
}
Output:
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
Introducing Access Control
encapsulation provides another important attribute: access control.
Through encapsulation, parts of a program can be controlled which can
access the members of a class.
Java’s access specifiers are public, private, and protected.
Java also defines a default access level. protected applies only when
inheritance is involved.
When a member of a class is modified by the public specifier, then that
member can be accessed by any other code.
When a member of a class is specified as private, then that member can
only be accessed by other members of its class.
__________________________________________________________________________________
MITM 88
Programming in Java (18CS653) Sangeetha G
__________________________________________________
When no access specifier is used, then by default the member of a class
is public within its own package, but cannot be accessed outside of its
package.
For example:
public int i;
private double j;
private int myMethod(int a, char b)
{ // ...
class Test
{
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i)
{ // set c's value
c = i;
}
int getc( )
{ // get c's value
return c;
}
}
class AccessTest
{
public static void main(String args[ ])
{
Test ob = new Test( );
__________________________________________________________________________________
MITM 89
Programming in Java (18CS653) Sangeetha G
__________________________________________________
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
In the above program, inside the Test class, a uses default access, as public. b is
explicitly specified as public.Member c is given private access. This means that
it cannot be accessed by code outside of its class.So, inside the AccessTest class,
c cannot be used directly. It must be accessed through its public methods: setc( )
and getc( ).
Understanding static
There are some cases when a class member to be defined that will be used
independently of any object of that class.
Normally, a class member must be accessed only in conjunction with an
object of its class.
However, it is possible to create a member that can be used by itself,
without reference to a specific instance.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
Both methods and variables can be declared to be static.The most common
example of a static member is main( ) function. main( ) is declared as static
because it must be called before any objects exist.
__________________________________________________________________________________
MITM 90
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Instance variables declared as static are, essentially, global variables.When
objects of its class are declared, no copy of a static variable is made.Instead,
all instances of the class share the same static variable.
Methods declared as static have several restrictions:
1.They can only call other static methods.
2.They must only access static data.
3.They cannot refer to this or super in any way
The following example shows a class that has a static method, some static
variables, and a static initialization block:
// Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[ ])
{
meth(42);
__________________________________________________________________________________
MITM 91
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
}
As soon as the UseStatic class is loaded, all of the static statements are
executed.
First, a is set to 3,then the static block executes, which prints a message
and then initializes b to a * 4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x.The three
println( ) statements refer to the two static variables a and b, as well as to
the local variable x.
Output:
Static block initialized.
x = 42
a=3
b = 12
Outside of the class in which they are defined, static methods and variables
can be used independently of any object.To do so, the name of their class
must be specified followed by the dot operator.
For example, if a static method is to be called from outside its class, The
general form is:
classname.method( )
Here, classname is the name of the class in which the static method is
declared. This format is similar to that used to call non-static methods
through object-reference variables.
A static variable can be accessed in the same way with the use of the dot
operator on the name of the class.
Here is an example. Inside main( ), the static method callme( ) and the
static variable b are accessed through their class name StaticDemo.
__________________________________________________________________________________
MITM 92
Programming in Java (18CS653) Sangeetha G
__________________________________________________
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme( )
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[ ])
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Output:
a = 42
b = 99
Introducing final
A variable can be declared as final to prevents its contents from being
modified. This means that a final variable must be intialized when it is
declared.
For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
__________________________________________________________________________________
MITM 93
Programming in Java (18CS653) Sangeetha G
__________________________________________________
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
In a program can now use FILE_OPEN, etc., as if they were constants,
without fear that a value has been changed.It is a common coding
convention to choose all uppercase identifiers for final variables.
Variables declared as final do not occupy memory on a per-instance basis.
Thus, a final variable is essentially a constant.
The keyword final can also be applied to methods, but its meaning is
substantially different than when it is applied to variables.
Arrays Revisited
There is a special array attribute ,the size of an array that is, the number of
elements that an array can hold is found in its length instance variable.
//This program demonstrates the length array member.
class Length
{
public static void main(String args[ ])
{
int a1[ ] = new int[10];
int a2[ ] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[ ] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
Output:
length of a1 is 10
length of a2 is 8
length of a3 is 4
__________________________________________________________________________________
MITM 94
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Inheritance
Inheritance can be defined as the process where one class acquires the
properties) of another.
The class which inherits the properties of other is known as subclass
(derived class, child class).
The class whose properties are inherited is known as superclass (base class,
parent class).
Types of Inheritance:
There are various types of inheritance as demonstrated below.
Java does not support multiple inheritance. This means that a class cannot
extend more than one class.
__________________________________________________________________________________
MITM 95
Programming in Java (18CS653) Sangeetha G
__________________________________________________
extends Keyword
extends is the keyword used to inherit the properties of a class. Following
is the syntax of extends keyword.
General Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example:
class Calculation
{
int z;
void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
Using Super:
1.The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
2.super keyword can be used to access the data member or field of parent class.
It is used if parent class and child class have same fields.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super( ) can be used to invoke immediate parent class constructor.
1. super keyword can be used to access the data member or field of parent class.
It is used if parent class and child class have same fields.
For Example:
class A
{
String color="white";
}
class D extends A
{
String color="black";
void printColor( )
{
System.out.println(color);
System.out.println(super.color);
}
}
__________________________________________________________________________________
MITM 97
Programming in Java (18CS653) Sangeetha G
__________________________________________________
class B
{
public static void main(String args[ ])
{
D d=new D( );
d.printColor( );
}
}
Output:
black
white
The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class. In other
words, it is used if method is overridden.
For Example:
class A
{
void eat( )
{
System.out.println("Started eating...");
}
}
class D extends A
{
void eat( )
{
System.out.println("Still eating ...");
}
void work( )
{
super.eat( );
}
}
class B
{
__________________________________________________________________________________
MITM 98
Programming in Java (18CS653) Sangeetha G
__________________________________________________
public static void main(String args[])
{
D d=new D( );
d.work();
}
}
Output:
Started eating…
Still eating..
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor
class A
{
A( )
{
System.out.println("Constructor A is called");
}
}
class D extends A
{
D( )
{
super( );
System.out.println("Constructor D is called ");
}
}
class B
{
public static void main(String args[ ])
{
D d=new D( );
}
}
Output:
Constructor A is called
Constructor D is called
__________________________________________________________________________________
MITM 99
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Creating a Multilevel Hierarchy
Multilevel inheritance is when a derived class inherits properties from a base
class, and then another class inherits from that derived class
For Example:
class Shape
{
public void display( )
{
System.out.println("Inside display");
}
}
class Rectangle extends Shape
{
public void area( )
{
System.out.println("Inside area");
}
}
class Cube extends Rectangle
{
public void volume( )
{
System.out.println("Inside volume");
}
}
public class Tester
{
public static void main(String args[ ])
{
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
Output:
Inside display
Inside area
Inside volume
__________________________________________________________________________________
MITM 100
Programming in Java (18CS653) Sangeetha G
__________________________________________________
When Constructors Are Called
When a class hierarchy is created, the order in which the constructors for
the classes are called.
}
class C extends A
{
void callme( )
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[ ])
{
A a = new A( );
B b = new B( );
C c = new C( );
A r;
r = a;
__________________________________________________________________________________
MITM 103
Programming in Java (18CS653) Sangeetha G
__________________________________________________
r.callme( );
r = b;
r.callme( );
r = c;
r.callme( );
}
}
Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Using Abstract Classes
Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.
Abstract Method in Java
general form:
Output:
running safely
__________________________________________________________________________________
MITM 105
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Using final with Inheritance
class A
{
final void meth( )
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth( )
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
For Example:
__________________________________________________________________________________
MITM 106
Programming in Java (18CS653) Sangeetha G
__________________________________________________
final class A
{
// ...
}
class B extends A
{
// ERROR! Can't subclass A
// ...
}
Object class
The Object class is the parent class of all the classes in java by default. In
other words, it is the topmost class of java.
Object class is present in java.lang package.
Every class in Java is directly or indirectly derived from the Object class.
If a class does not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
Therefore the Object class methods are available to all Java classes.
Hence Object class acts as a root of the inheritance hierarchy in any Java
Program.
__________________________________________________________________________________
MITM 107
Programming in Java (18CS653) Sangeetha G
__________________________________________________
__________________________________________________________________________________
MITM 108