KEMBAR78
Java 18CS653 | PDF | Object Oriented Programming | Data Type
0% found this document useful (0 votes)
20 views108 pages

Java 18CS653

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views108 pages

Java 18CS653

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Programming in Java (18CS653) Sangeetha G

__________________________________________________

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

 Object oriented programming (OOP) is the core of Java programming.

 Java is a general purpose, object- oriented programming language developed by Sun


Microsystems. It was invented by James Gosling and his team and was initially called
as Oak.
 The most important feature that made Java very popular was the ―Platform-
Independent‖ approach.
 It was the first programming language that did not tie-up with any particular
operatingsystem (or hardware) rather Java programs can be executed anywhere and
on any system.
 Java was designed for the development of the software for consumer electronic
devices like TVs, VCRs, etc.
Two Paradigms:

 Every program contains 2 components code and data.

 Two approaches are there to solve the problem and in program writing:
Procedureoriented and object oriented.
Procedure Oriented:

 Procedure oriented programs are written based on ―what is happening around,


where the code acts on data.

Example: C etc
 Problems increases in procedure oriented as the program grows larger and more
complex.
Object Oriented:

 Object oriented programs are written based on ―Who is being affected‖


around, which manages the increasing complexity.
 It organizes program around data and well-defined interfaces of that data.

 Characterized as data controlling access to code.

Example: C++, JAVA, Small Talk etc


Abstraction:
__________________________________________________________________________________
MITM 2
Programming in Java (18CS653) Sangeetha G
__________________________________________________
 Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed information in
program without presenting the details.

Example:

A database system hides certain details of the way in which data is stored and
created and maintained.

The Three OOP:

All object-oriented programming languages provide mechanisms that help to implement


the object-oriented model. They are encapsulation, inheritance, and polymorphism. The
features three OOP are:

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:

 Polymorphism is considered one of the important features of Object-Oriented


Programming
 The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
 polymorphism allows you to define one interface and have multiple
implementations.

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.

A First Simple Program

class Example
{
public static void main (String args [])
{
System.out.println("This is a simple Java program.");
}
}

1. Open the notepad and type the above 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

3. Open the command prompt and compile the above program


javac Example.java

From the above compilation the java compiler produces a bytecode(.class file)

4. Finally run the program through the


java Example.java

Output of the program:

Welcome to Programming in Java

Description:
1. A Closer Look at the First Sample Program Example.java, it includes several key
features that are common to all Java programs.

2. The program begins with the following lines:

/* This is a simple Java program. Call this file "Example.java". */

3. This is a comment line.

4. Java supports three styles of comments.

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.

7. The next line of code in the program is shown here:

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:

// Your program begins with a call to main().

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.

9.The next line of code is shown here:

public static void main (String args []) {

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

A Second Short Program


class Example2
{
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
__________________________________________________________________________________
MITM 6
Programming in Java (18CS653) Sangeetha G
__________________________________________________
System.out.println("The value of num * 2 is ");
System.out.println(num);
}
}

Output:
This is num: 100
The value of num * 2 is 200

Description:
1.The first new line in the program is shown here:

int num; // this declares a variable called num

This line declares an integer variable called num.The keyword int specifies an integer type.

2.In the program, the line

num = 100; // this assigns num the value 100

3.The next line of code outputs the value of num preceded by the string “This is num:”.

System.out.println("This is num: " + 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

5.The next two lines in the program:

System.out.print("The value of num * 2 is ");

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.

 The general form of the if statement:

if (condition) statement;

 Here the condition is Boolean expression.

 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:

for(initialization; condition; iteration)

//body

 Initialization sets the loop control variable to initial value.

 Condition is a Boolean expression which tests the loop

 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

Using Blocks of Code


__________________________________________________________________________________
MITM 9
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Java allows two or more statements to be grouped into blocks of code, also called code
blocks. This is done by enclosing the statements between opening and closing curly braces.

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.

 Whitespace is a space, tab, or newline.

Identifiers

 Identifiers are used for class names, method names, and variable names.

 An identifier may be any descriptive sequence of uppercase and lowercase letters,


numbers, or the underscore and dollar-sign characters.

 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.

Examples of valid identifiers are

AvgTemp count a4 $test this_is_ok

Invalid identifier names include:

2count high-temp Not/ok

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

 Documentation Comment: this type of comment is used to produce an HTML file


that documents your program. The documentation comment begins with /**
and ends with */

Keywords
 There are 50 keywords currently defined in the Java language.

 These keywords, combined with the syntax of the operators and separators,

 These keywords cannot be used as names for a variable, class, or method

Java Class Libraries:


Java environment has several built-in class libraries. Java standard library includes
hundreds of classes and methods grouped into several functional packages. Most commonly
used packages are:
(a) Language support Package.
__________________________________________________________________________________
MITM 12
Programming in Java (18CS653) Sangeetha G
__________________________________________________
(b) Utilities packages.

(c) Input/output packages

(d) Networking packages

(e) AWT packages.

(f) Applet packages

__________________________________________________________________________________
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.

 Java does not support unsigned, positive-only integers.

 Many other computer languages support both signed and unsigned integers

Byte

 The smallest integer type is byte.

 This is a signed 8-bit type that has a range from –128 to 127.

 Byte variables are declared by use of the byte keyword

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 is a signed 16-bit type.

 It has a range from –32,768 to 32,767.

 It is probably the least-used Java type

For Example: short variable declaration:

short t;

int

 The most commonly used integer type is int.

 It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647.

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.

 char in Java is not the same as char in C or C++.

 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.

Data Type Default Value Default size


Boolean False 1 bit
Char '\u0000' 2 byte
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d 8 byte

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:

int decimal = 100;


int octal = 0144;
int hexa = 0x64;

Floating point literals:

 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:

0.0314 *10² (i.e 3.14).

Character Literals

 Characters in Java are indices into the Unicode character set.

 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.

 Example of string literals

__________________________________________________________________________________
MITM 17
Programming in Java (18CS653) Sangeetha G
__________________________________________________
“Hello World”

 The ASCII character set includes 128 characters including letters, numerals,
punctuation etc.

 Below table shows a set of these special characters:

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.

 In Java, they can only be assigned to variables declared as boolean, or used in


expressions with Boolean operators.

Variables
 The variable is the basic unit of storage in a Java program.

 A variable is defined by the combination of an identifier, a type, and an optional


initializer.

 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.

2. Uppercase and lowercase are distinct.

3. It should not be a keyword.

4. White space is not allowed.

 One variable should be declared before using. The syntax is


type identifier;
Example:
int a;

Initializing a variable
A variable can be initialized in two ways. They are

(a) Initializing by Assignment statements.

(b) Dynamic Initialization

(a)Initializing by assignment statements:

 One variable can be initialize using assignment statements. The syntax is :


Variable-name = Value;

Example:

int a=10, b, c=16;

Double pi=3.147;

(b)Dynamic Initialization

 Java allows variables to be initialized dynamically, using expression valid at the


timevariable is declared.

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

The Scope and Lifetime of Variables


 Java allows variables to be declared within any block. A block is begun with an
opening curly brace and ended by a closing curly brace. A block defines a scope.
 A scope determines which objects are visible to other parts of the program. It also
determines the lifetime of those objects.
 As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when a variable is declared within a
scope, variables are localized and protecting it from unauthorized access and
modification.

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

Type Conversion and Casting

 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

 Type casting can be done in two ways.


 In Java, type casting is classified into two types:

1.Widening Casting (Implicit)

2.Narrowing Casting (Explicitly done)

1.Widening Casting (Implicit)


Example:

public class Test


{
public static void main (String [] args)
__________________________________________________________________________________
MITM 21
Programming in Java (18CS653) Sangeetha G
__________________________________________________
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}

Output:
Int value 100
Long value 100

Float value 100.0


2.Narrowing or Explicit type conversion

 When larger type value are assigned to a variable of smaller type, then explicit type
casting is to be performed.

Example:

public class Test

public static void main (String [] args)

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:

Double value 100.04

Long value 100

Int value 100

Automatic type promotion in expression


 Type conversions also occurs in expressions.

 Java automatically promotes each byte, short, or char operand to int when
evaluatingan expression.
byte b = 50;

b = b * 2; // Error! Cannot assign an int to a byte!

 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;

b = (byte)(b * 2); which yields the correct value of 100.

 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.

2. Then, if one operand is a long, the whole expression is promoted to long.

3. If one operand is a float, the entire expression is promoted to float.

4. If any of the operands is double, the result is double.

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.

 A specific element in an array is accessed by its index.

Declaring an array Variable:

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:

datatype[] arrayRefVar; or datatype arrayRefVar[];

For Example:

int [] myList; or int myList[];

Creating an array:
 An array can be created by using new operator. The syntax is:

arrayRefVar = new datatype[arraySize];


 The above statement does two things:

1. It creates an array using new datatype[arraySize];

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];

 Alternatively, an array can be created as follows:


dataType[] arrayRefVar = {value0, value1, ..., valuek};

 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.

int [] a = new a [5];

Example:

class TestArray
{

public static void main (String [] args)

double [] myList = {1.9, 2.9, 3.4, 3.5};


// Print all the array elements
or (int i = 0; i < 4; i++)
{

System.out.println(myList[i] + " ");

A Few Words About Strings:


 Java supports string type which is an object. It is used to declare string variables

 Array of strings can also be declared.

 A string variable can be assigned to another string variable.


__________________________________________________________________________________
MITM 25
Programming in Java (18CS653) Sangeetha G
__________________________________________________
 String variable can also be used as
argument.

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

2.Write a java program to calculate area of a circle.


class Area
{
public static void main(String args[])
{
double pi, r, a; r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
__________________________________________________________________________________
MITM 26
Programming in Java (18CS653) Sangeetha G
__________________________________________________
System.out.println("Area of circle is " + a);
}
}

Output:
Area of circle is 366.2496

3.Write a java program to demonstrate character datatype.


class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88;
ch2 = 'Y';
System.out.println("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

Output:
ch1 and ch2: X Y

4.Write a java program to demonstrate char variable as integer type.

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

Operators: Arithmetic Operators, The Bitwise Operators, Relational


Operators, Boolean
Logical Operators, The Assignment Operator, The ? Operator,
Operator Precedence, Using
Parentheses, Control Statements: Java’s Selection Statements, Iteration
Statements, Jump
Statements.
Text book 1: Ch 4, Ch 5
RBT: L1, L2

__________________________________________________________________________________
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;

Write a java program to demonstrate increment operator.


class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;

__________________________________________________________________________________
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 NOT


__________________________________________________________________________________
MITM 32
Programming in Java (18CS653) Sangeetha G
__________________________________________________
 Also called the bitwise complement, the unary NOT operator, ~, inverts all
of the bits of its operand.
For example:
The number 42, which has the following bit pattern: 00101010 becomes
11010101 after the NOT operator is applied.
The Bitwise AND
 The AND operator, &, produces a 1 bit if both operands are also 1.
 A zero is produced in all other cases.
For Example:
00101010 42
& 00001111 15
________________
00001010 10

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

The Bitwise XOR


 The XOR operator, ^, combines bits such that if exactly one operand is 1,
then the result is 1. Otherwise, the result is zero.
For Example:
00101010 42
^ 00001111 15
______________
00100101 37

__________________________________________________________________________________
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

Boolean Logical Operators


 The Boolean logical operators shown here operate only on boolean
operands.
 All of the binary logical operators combine two boolean values to form a
resultant boolean value.
--Table—
The logical Boolean operators, &, |, and ^, operate on boolean values.
. The following table shows the effect of each logical operation:
--table—
Write a java program Demonstrate the boolean logical operators.
class BoolLogic
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
__________________________________________________________________________________
MITM 35
Programming in Java (18CS653) Sangeetha G
__________________________________________________
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false

The Assignment Operator


 The assignment operator is the single equal sign, =
 The general form is:
var = expression;
For Example:
int x, y, z;
x = y = z = 100;
The ? Operator
 Java includes a special ternary (three-way) operator that can replace
certain types of if-then-else statements. This operator is the ?.
 The general form:

__________________________________________________________________________________
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
__________________________________________________

4.The For-Each Version of the for Loop


 The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time, from
beginning to end.
Working:
 With each iteration of the loop, the next element in the collection is
retrieved and stored in itr-var.
 The loop repeats until all elements in the collection have been obtained.
 Because the iteration variable receives values from the collection, type
must be the same as the elements stored in the collection.
 Thus, when iterating over arrays, type must be compatible with the base
type of the array.
 In the below example,with each pass through the loop, x is automatically
given a value equal to the next element in nums. Thus, on the first iteration,
x contains 1, on the second iteration, x contains 2 and so on.
Example:
class ForEach
{
public static void main(String args[])
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums)
{

__________________________________________________________________________________
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.

2.The continue statement


 A continue statement stops the iteration of a loop (while, do or for) and
cause execution to resume at the top of the nearest enclosing loop.
 continue statement is used whenever is needed to execute the remaining
statements in the loop, but do not want to exit the loop itself.
 Label can also be provided for a loop and then use the label in continue
statement.
 The label name is optional, and is usually only used when it is required to
return to the outermost loop in a series of nested loops.
Example:
class Example
__________________________________________________________________________________
MITM 50
Programming in Java (18CS653) Sangeetha G
__________________________________________________
{
public static void main(String args[])
{
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i)
{
if (i % 2 == 0)
continue;
System.out.println(i + "\t");
}
}
}
Output:
Odd Numbers
1
3
5
7
9

 As with the break statement, continue may specify a label to describe


which enclosing loop to continue.
class ContinueLabel
{
public static void main(String args[])
{
outer:
for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(j > i)
{
System.out.println();
__________________________________________________________________________________
MITM 51
Programming in Java (18CS653) Sangeetha G
__________________________________________________
continue outer;
}
System.out.println(" " + (i * j));
}
}
System.out.println();
}
}

 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.

A Closer Look at Argument Passing


In general, there are two ways that a computer language can pass an argument to
a subroutine.
 The first way is call-by-value. This approach copies the value of an
argument into the formal parameter of the subroutine. Therefore, changes
made to the parameter of the subroutine have no effect on the argument.
 The second way an argument can be passed is call-by-reference. In this
approach, a reference to an argument (not the value of the argument) is
passed to the parameter.
 Inside the subroutine, this reference is used to access the actual argument
specified in the call. This means that changes made to the parameter wil

__________________________________________________________________________________
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);
}
}

class Next extends Calculation


{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[ ])


{
int a = 20, b = 10;
Next demo = new Next();
demo.addition(a, b);
__________________________________________________________________________________
MITM 96
Programming in Java (18CS653) Sangeetha G
__________________________________________________
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

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

2.super can be used to invoke parent class method

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.

 For example, given a subclass called B and a superclass called A, is A’s


constructor called before B’s, or vice versa.In a class hierarchy,
constructors are called in order of derivation, from superclass to subclass.

 Further, since super( ) must be the first statement executed in a subclass’


constructor, this order is the same whether or not super( ) is used.

 If super( ) is not used, then the default or parameterless constructor of each


superclass will be executed.
For Example:
class A
{
A( )
{
System.out.println("Inside A's constructor.");
}
}
class B extends A
{
B( )
{
System.out.println("Inside B's constructor.");
}
}
class C extends B
{
C( )
{
System.out.println("Inside C's constructor.");
}
}
class CallingCons
{
public static void main(String args[ ])
__________________________________________________________________________________
MITM 101
Programming in Java (18CS653) Sangeetha G
__________________________________________________
{
C c = new C( );
}
}
The output:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
Method Overriding
 In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its superclass, then the method in the subclass
is said to override the method in the superclass.
 When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden.
For Example:
class A
{
void run( )
{
System.out.println("Vehicle is running");
}
}
class B extends A
{
void run( )
{
System.out.println("Bike is running ");
}
}
class C
{
public static void main(String args[ ])
{
B obj = new B( );
obj.run( );
__________________________________________________________________________________
MITM 102
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
}
Output:
Vehicle is running
Bike is running
Dynamic Method dispatch:
Dynamic method dispatch is the mechanism in which a call to an overridden
method is resolved at run time instead of compile time.
class A
{
void callme( )
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme( )
{
System.out.println("Inside B's callme method");
}

}
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

A method which is declared as abstract and does not have implementation


is known as an abstract method.

general form:

abstract type name(parameter-list);

Example of abstract method

abstract class Bike


{
abstract void run( );
}
class Honda4 extends Bike
{
void run( )
{
System.out.println("running safely");
__________________________________________________________________________________
MITM 104
Programming in Java (18CS653) Sangeetha G
__________________________________________________
}
public static void main(String args[ ])
{
Bike obj = new Honda4( );
obj.run( );
}
}

Output:

running safely

Another Example of abstract class:

abstract class Shape


{
abstract void draw();
}
class Rectangle extends Shape
{
void draw( )
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw( )
{
System.out.println("drawing circle");
}
}
class A
{
public static void main(String args[ ])
{
Shape s=new Circle1( );
Shape s1=new Rectangle( );
s.draw( );
s1.draw( );
}
}

__________________________________________________________________________________
MITM 105
Programming in Java (18CS653) Sangeetha G
__________________________________________________
Using final with Inheritance

The keyword final has three uses.

1.it can be used to create the equivalent of a named constant.

2. Using final to Prevent Overriding

To disallow a method from being overridden, specify final as a modifier at


the start of its declaration. Methods declared as final cannot be overridden. The
following program illustrates final:

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!");
}
}

Because meth( ) is declared as final, it cannot be overridden in B. If it is tried to


override it results a compile-time error.

3. Using final to Prevent Inheritance

Declaring a class as final implicitly declares all of its methods as final, it is


illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete
implementations.

For Example:
__________________________________________________________________________________
MITM 106
Programming in Java (18CS653) Sangeetha G
__________________________________________________
final class A
{
// ...
}
class B extends A
{
// ERROR! Can't subclass A
// ...
}

it is illegal for class B to inherit class A since class A is declared as final.

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.

 The Object class provides multiple methods which are as follows:

__________________________________________________________________________________
MITM 107
Programming in Java (18CS653) Sangeetha G
__________________________________________________

__________________________________________________________________________________
MITM 108

You might also like