You are on page 1of 119

Ramrao Adik Institute of Technology F.E.

Computer Programming II

Computer
Programming2
For F.E All
Branches By
Shalini Puri
Prof. Shalini Puri 1
Ramrao Adik Institute of Technology F.E.Computer Programming II

Syllabus for Computer Programming II:


Module 1: Introduction to Java
 Characterizing Java as enabler of contemporary software engineering pardiagrams as a
platform, Simple programming Environment, Object Oriented, Platform independent,
Safe, High Performance, Java is multithreaded, Dynamically linked, Java is garbage
collected. Saving files on windows, Compiling and running .Increment and decrement
operators. Print statements, Variables and data types, Comments and Command line
arguments, objects, Static fields, Methods, Passing arguments to methods and
returning values from methods
Module 2: Primitive Data Types in JAVA
 Java operators, Literals, Identifiers, Keywords in Java, Addition, Multiplication,
Division and Remainder operators in Java. Operator precedence in Java. Mixing data
types in Java. Converting strings to numbers. Character data type in Java. The if, else,
if-else statement in Java. The While loop, For loop, Do-while loop in Java. Booleans,
Relational Operators and its precedence. Logical operators in Java. Break, Continue
and Switch statement in Java. The ? : operator in Java
 Object Oriented Programming. Constructing objects with new, methods, Invoking
methods. Implied this, member variable vs. local variables. Passing arguments to
methods, returning multiple values from methods, constructors. Access protection and
four levels of access protection
Module 3: Array as a Data Structures in Java
 Declaring arrays, Creating Arrays, Initializing arrays. SystemArraycopy().
Multidimensional Arrays. Strings, toString() Methods, Vectors. Exceptions, try-catch,
the finally keyword, Catch multiple exceptions. The throws keyword, Throwing
exceptions
Module 4: Inheritance
 Inheritance : the super class, Multilevel Inheritance, final and abstract keyword
Interfaces, Implementing interfaces, Overriding Methods, Adding Methods,

Prof. Shalini Puri 2


Ramrao Adik Institute of Technology F.E.Computer Programming II

Subclasses, Polymorphism and static members


Module 5: Multithreaded Programming
 Creating threads, extending the thread class, stopping and blocking a thread, Lifecycle
of a thread, Using Thread methods, thread exceptions, thread priority,
Synchronization.
 The JAVA Packages & Class library, wrapping your own Packages, Naming
Packages, Documentation for the class library, Importing classes, Package Imports,
Name conflicts when importing packages, the java.lang package, the hashCode()
method of java.lang Object, java.lang.Math, java.util.Vector,java.lang.String, java.util.
Random,java.util.hashtable,java.util.Date,and java.util.Calender
Module 6 : HTML
 Attributes, URLs, Links, Applet, The Applet Element, Naming Applets, JAR archives,
the OBJECT Element, Passing parameter to Applets. The Basic Applet Life cycle,
init(), start( ),stop( ) and destroy( ). The coordinate System, Graphic objects, Loading
images .Code and Documentation Bases, Drawing Images as Actual Size. Scaling
images, Color, Fonts

Prof. Shalini Puri 3


Ramrao Adik Institute of Technology F.E.Computer Programming II

List of programs for FE 2008-2009 for Computer Programming II:

Sr.No Name of the program


1 a) Area of triangle
b) Printing the grade of a student
2 Fibonacci series using while
3 Armstrong Number using for
4 G.C.D using do-while
5 Search Elements of an array
6 Printing Sum of diagonal elements in a two dimensional array
7 a) Prime Number using function
b) Reverse a number and sum of elements using Recursive function
8 Implement class using Constructor
9 Implement Array of Objects
10 Implement String methods
11 Exception Handling
12 Multithreading
13 a) Using pre-defined package
b) Creating your own package
14 Graphics in Applet
15 Human face using Applet

Prof. Shalini Puri 4


Ramrao Adik Institute of Technology F.E.Computer Programming II

INDEX
1. Introduction to Java ................................................................................................. 7
1.1 Why is java popular for the Internet ................................................................... 7
1.2 Features of Java: ................................................................................................. 7
1.3 How Java program runs ...................................................................................... 9
2. Object Orientation .................................................................................................. 11
2.1 Features of Object Oriented Language: ............................................................ 11
3. Java Language Basics ............................................................................................. 13
3.1 Introduction:...................................................................................................... 13
3.2 Basic Building Blocks: ..................................................................................... 13
4. Control Structures .................................................................................................. 20
4.1 Simple If statement: .......................................................................................... 20
4.2 If-Else Statement:.............................................................................................. 20
4.3 Switch-Case Statement: .................................................................................... 21
5. Loops ........................................................................................................................ 23
5.1 For Loop: .......................................................................................................... 23
5.2 While Loop: ...................................................................................................... 24
5.3 Do-While Loop: ................................................................................................ 25
5.4 Break and Continue Statement: ........................................................................ 25
5.5 Exercise:............................................................................................................ 27
6. Functions.................................................................................................................. 28
6.1 Methods in Java: ............................................................................................... 28
6.2 Recursive Functions:......................................................................................... 28
6.3 Exercise:............................................................................................................ 29
7. Arrays....................................................................................................................... 32
7.1 Creating an Array:............................................................................................. 32
7.2 Array Index Checking:...................................................................................... 32
7.3 SystemArraycopy():.......................................................................................... 33
7.4 Multidimensional Arrays: ................................................................................. 34
7.5 Exercise:............................................................................................................ 34
8. Introduction Classes: .............................................................................................. 41
8.1 General form of a Class: ................................................................................... 41
8.2 Declaring and Creating Objects:....................................................................... 41
8.3 Accessing Members:......................................................................................... 42
8.4 Introducing Methods:........................................................................................ 42
8.5 Constructors: ..................................................................................................... 44
8.6 Array of Objects:............................................................................................... 45
8.7 Static Variables and Static Methods: ................................................................ 46
9. Wrapper Classes ..................................................................................................... 48
9.1 Introduction:...................................................................................................... 48
9.2 Class Integer: .................................................................................................... 48

Prof. Shalini Puri 5


Ramrao Adik Institute of Technology F.E.Computer Programming II

9.3 Class Float:........................................................................................................ 48


9.4 Class Double: .................................................................................................... 49
9.5 Class Boolean: .................................................................................................. 49
9.6 Class Character: ................................................................................................ 50
10. Strings .................................................................................................................. 51
10.1 Declaring and Constructing a String:................................................................ 51
10.2 Methods of Strings:........................................................................................... 51
10.3 Sorting Strings: ................................................................................................. 53
10.4 Methods valueOf() and toString():.................................................................... 53
10.5 Vector:............................................................................................................... 54
11. Simple Input/Output........................................................................................... 56
11.1 Reading Character fron Console Input: ............................................................ 56
11.2 Reading Strings:................................................................................................ 57
12. Inheritance........................................................................................................... 59
12.1 Types of Inheritance: ........................................................................................ 59
12.2 Multilevel Inheritance:...................................................................................... 63
12.3 Method Overriding: .......................................................................................... 66
12.4 Interface: ........................................................................................................... 66
13. Packages............................................................................................................... 70
13.1 Defining and using your own Package: ............................................................ 70
13.2 Defining and using system Packages:............................................................... 73
13.3 Access Specification in Java:............................................................................ 78
14. Exception Handling ............................................................................................ 80
14.1 Why use Exception handling: ........................................................................... 80
14.2 Exceptions:........................................................................................................ 81
15. Multithreading .................................................................................................... 87
15.1 What are Threads and why use them? .............................................................. 87
15.2 Creating and Running a Thread: ....................................................................... 88
15.3 Life Cycle of a Thread: ..................................................................................... 92
15.4 Thread Priority:................................................................................................. 94
15.5 Synchronization: ............................................................................................... 95
16. Graphics and Java Applets ................................................................................ 97
16.1 Creation of Applet: ........................................................................................... 97
16.2 Applet Life Cycle:............................................................................................. 99
16.3 Using graphic methods in Applet: .................................................................. 101
17. Solved University Question Papers: ................................................................ 104
17.1 May-June 2008: .............................................................................................. 104
17.2 Dec-2008......................................................................................................... 114

Prof. Shalini Puri 6


Ramrao Adik Institute of Technology F.E.Computer Programming II

1. Introduction to Java
Java was developed at Sun Microsystems in 1991, by a team comprising James
Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan as its members.
The language was initially called as Oak. It was later termed as Java. Java was launched
on 23 May, 1995. The Java software was released as a development kit. The first two
versions were named as JDK1.0 and JDK1.1. In 1998 while releasing the next version
Sun Microsystems changed the name from Java Development Kit JDK) to Software
Development Kit (SDK) and the version was referred as Java 2 SDK 1.2. Now we are
using JDK 6.

1.1 Why is java popular for the Internet


Java is popular on the Internet because it offers Applets. Applets are tiny
programs that run on the browser. This means that they inherit the strength of Java and
also support graphical user interface. So surfing on the Internet becomes fun when web
pages are designed with the help of applets.

1.2 Features of Java:


The features of Java, which makes Java a powerful, popular language, can be stated
briefly as:

1.2.1 Simple:
Java is simple to learn and use. In Java it is easy to write and debug programs because
certain complex features like operator overloading, multiple inheritance, pointers, and
explicit memory de allocation are not present in Java language.

1.2.2 Robust and Secure:


Two main reasons for program failure are related to:
 Memory management is very easy since the de allocation is done by the garbage
collector automatically (more on this later)
 Run time errors in Java provides object oriented exception handling to manage run
time errors (covered late in Exception Handling).

Prof. Shalini Puri 7


Ramrao Adik Institute of Technology F.E.Computer Programming II

1.2.3 Multithread
Java is a programming language designed for the distributed environment of the internet
and helps to write interactive programs where in multiple tasks can be performed
simultaneously thus making it a robust programming language. Java is inherently multi-
threaded as there can be multiple executing threads in a single Java program. For
example Java program can run three applets on the same page, provided that each applet
gets equal time from the CPU.

1.2.4 Interpreted:
Java is an interpreted language. When we write a program it is compiled into a class file.
The interpreter executes this class file. However the interpreters 30 years ago were
interpreting the statement in textual form. It was a very slow process. Java interprets byte
code hence it is considerably fast. Java gets all the advantages of interpretation without
suffering from major disadvantages..

1.2.5 Architecture Neutral:


Java is an Interpreter based language. With Java, the program need only be compiled
once, and the code generated by the Java compiler can run on any platform (discussed in
detail later). If you are writing software for the World Wide Web, being able to run the
same program on many different systems is crucial to that program's success. Java is
platform independent at both the source and the binary level. Java can be easily ported on
any type of system and irrespective of the operating system being used. Java achieves this
portability due to its feature of Implementation Independency.

1.2.6 Platform independent and Portable:


Platform independence is one of the most significant advantages that Java has over other
programming languages, particularly for systems that need to work on many different
platforms. Java is platform-independent at both the source and the binary level.
Platform-independence is a program’s capability of moving easily from one computer
system to another. At the source level, Java’s primitive data types have consistent sizes
across all development platforms. Java’s foundation class libraries make it easy to write
code that can be moved from platform to platform without the need to rewrite it to work
with that platform. Platform-independence doesn’t stop at the source level, however. Java

Prof. Shalini Puri 8


Ramrao Adik Institute of Technology F.E.Computer Programming II

binary files are also platform-independent and can run on multiple problems without the
need to recompile the source. How does this work? Java binary files are actually in a
form called byte codes. Byte codes are a set of instructions that looks a lot like some
machine codes, but that is not specific to any one processor. Normally, when you compile
a program written in C or in most other languages, the compiler translates your program
into machine codes or processor instructions. Those instructions are specific to the
processor your computer is running—so, for example, if you compile your code on a
Pentium system, the resulting program will run only on other Pentium systems. If you
want to use the same program on another system, you have to go back to your original
source, get a compiler for that system, and recompile your code.

1.2.7 Distributed
Java is a distributed language as it can be used to create applications to communicate
over the network. Java can communicate over the network because it supports TCP/IP
(Transmission Control Protocol/Internet Protocol). The TCP/IP is a network
communication protocol.

1.2.8 Dynamic
During run time of a Java program, the relevant information is required that is used to
verify and resolve access to objects. This concept of providing run time information is
referred to as dynamically linking the code. This feature of Java adds strength to the
applet environment in which all fragments of bytecode are dynamically updated on a
running system.

1.3 How Java program runs


A computer language is either compiled or interpreted. Java combines both these features
making JAVA a two stage system. First JAVA compiler translates source code into byte
code instructions. Byte codes are not machine instructions and therefore in the second
stage Java interpreter generates machine code that can be directly executed by the
machine that is running the JAVA program.

Prof. Shalini Puri 9


Ramrao Adik Institute of Technology F.E.Computer Programming II

Because the Java VM is available on many different operating systems, the same .class
files are capable of running on Microsoft Windows, the Solaris TM Operating System
(Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java Hotspot virtual
machine, perform additional steps at runtime to give your application a performance
boost. This includes various tasks such as finding performance bottlenecks and
recompiling (to native code) frequently used sections of code
Compilation in Java:

Source Java Java


Code Compiler ByteCode

Running a Java Program:

Java Computer Running Java


ByteCode Virtual Machine ByteCode

Prof. Shalini Puri 10


Ramrao Adik Institute of Technology F.E.Computer Programming II

2. Object Orientation
2.1 Features of Object Oriented Language:
2.1.1 Encapsulation:
The process of binding code and data together in the form of a capsule is Encapsulation.
It is the mechanism that binds together code and data. It manipulates, and keeps it safe
from outside interference and misuse. The data is not accessible to the outside world and
only those functions that are wrapped in the class can access it. These functions provide
the interface between the object’s data and the program. The insulation of the data from
the direct access by the program is called data hiding.
In OOP, code and data are merged into an object so that the user of an object can never
peek inside the box. This is defined as encapsulation (Object is a capsule encapsulating
data and behavior). All communication to it is through messages (function calls which we
use to communicate to the object). Messages define the interface to the object.
Everything an object can do is represented by its message interface. Therefore, we need
not know anything about what is in the object when we use it.

2.1.2 Data Hiding:


The concept of wrapping data and functions in a single unit is known as encapsulation. It
is a mechanism that binds class members (variables and methods) together and prevents
them from being accessed by other classes. The term data hiding implies that the data is
not accessible by other classes and only the methods which are wrapped within the class
can access it.

2.1.3 Data Abstraction:


The process of extracting the essential information and hiding the irrelevant details
Abstraction is the process of exposing the relevant things and hiding the irrelevant
details. The easiest way to understand and appreciate this concept of handling complexity
is by studying the example of Globe, a model/prototype of earth that is used by students
to understand its geography. Globe provides only that information that is required and if
too much of information is mentioned in it i.e. streets, lakes etc, it becomes too complex
to comprehend. Hence Globe abstracts unwanted information and makes it easy to

Prof. Shalini Puri 11


Ramrao Adik Institute of Technology F.E.Computer Programming II

comprehend the complex earth.

2.1.4 Inheritance
The feature by which one class acquires the properties and functionalities of another
class is Inheritance. Inheritance is the process by which one class acquires the properties
and functionalities of another class. This is important because it supports the concept of
hierarchical classification.. Inheritance provides the idea of reusability of code and each
sub class defines only those features that are unique to it.

2.1.5 Polymorphism:
The feature that allows the same interface to be used for a general set of actions
Polymorphism is a feature that allows one interface to be used for a general class of
actions. An operation may exhibit different behavior in different instances. The behavior
depends on the types of data used in the operation. It plays an important role in allowing
objects having different internal structures to share the same external interface.
Polymorphism is extensively used in implementing inheritance.
Ex:
add(int a, int b)
add(int a, float b, int c)
add(int a, int b, float c, double d)
Here different datatypes are being added using the same interface.

Prof. Shalini Puri 12


Ramrao Adik Institute of Technology F.E.Computer Programming II

3. Java Language Basics


The best way of learning a programming language is to start coding right away. Let us
write a simple program in Java program and run it.

3.1 Introduction:
In our first program, we will find the area of a circle with radius 5.
class area
{
public static void main(String args[])
{
int r;
r=5;
System.out.println(3.14*r*r);
}
}
If you run the program, you will get the following output:
/*78.5*/
The structure of a very simple Java program can be explained as follows:
1. A program is written in a file named area.java
2. The file contains a class name as area by rule.
3. The class contains the main. It has to be declared with String arguments.
4. The method main contains declaration and program statements.
5. Java application begins execution at method main.

3.2 Basic Building Blocks:


The basic building block of Java consists of comments, declarations, statements and
methods. The comments are that part of the program which are supposed to give more
information about a particular program to the user and also increases the readability of
the program. So we use /* */ and // to put the comments. The declaration means the
declaring and defining the variables with values and writing conditional and loop
statements to produce the output in the required format with the help of some predefined
or user defined methods. Together with this we also need to declare constant, variables,
keywords and operators to write a program.

Prof. Shalini Puri 13


Ramrao Adik Institute of Technology F.E.Computer Programming II

 Integer Constant:
Integer can be expressed in three possible notations i.e. in octal, decimal and
hexadecimal. We use integer constants in decimal form. These constants are either
positive or negative. Plus sign is optional.
In decimal: 23, -55, +2367.
In Octal: 023, 055, 02367
In Hexdecimal : 0x23, 0x5B, 0XXFF23
 Real Constant:
The Real and floating point constants are written in either fixed point or scientific
notation. Following are examples of valid real constants:
In Fixed: 2.3, -5.54, 236.7
In Scientific: 0.2e3, -5E5, 2E67
Here for both mantissa and exponent sign is optional. Use of capital “E” is allowed in
place of small “e”.
 Character Constant:
If we enclose a single character in single quotes it forms simple character constants.
Example: ‘A’,,’B’,’*’
 String Constant:
A collection of characters is known as string. If we put characters in a pair of double
quotes it forms a string constant. Example: “Hello”, “World”.

3.2.1 Variables:
The variables are used to store values of constants. Any programming language allows us
to change, manipulate the values stored in a variable. There are some rules that are to be
followed while creating a variable name:
1. A variable name is a combination of 1 to 31 alphabets, digits or underscores. Do not
write unnecessary long names as it adds up to your typing effort.
2. The first character in a variable name should be an alphabet.
3. No commas or blanks are allowed in the variable name.
4. No special symbols other than underscores are allowed in a variable name.
5. Try giving some relevant variable names.

Prof. Shalini Puri 14


Ramrao Adik Institute of Technology F.E.Computer Programming II

Example: si_int,m_hra,pop_e_89
 Declaration of Variable:
Variables are declared with the help of a data type . a declaration int j tells the compiler
that j is a variable of type int (integer). If we have more than one variable of type int then
they are separated by commas. int i, j, k; Java or any other programming language aso
allows us to assign values to the variables. int marks = 100;

3.2.2 Keywords:
abstract const Finally implements public this case Switch
boolean continue For instanceof throw transient do While
break float If null short void False Catch
byte default Import int super volatile return Interface
char else Long private static true final New
class extends Goto protected try native throws

3.2.3 Operators:
Operators can perform operations on operands. Operands may be one, two or three.
Operands are either variables or constants. The operands which take single operand are
called unary operator. Those taking two are known as binary operators and one having
three operands is called as ternary operator. Most of the operators are binary operators
few are unary while there is only one ternary operator.

3.2.3.1 Arithmetic Operator:


class Operator
{
public static void main(String args[])
{
int a=25,b=10;
System.out.println("a+b =" +(a+b));
System.out.println("a-b =" +(a-b));
System.out.println("a*b =" +(a*b));
System.out.println("a/b =" +(a/b));
System.out.println("a%b =" +(a%b));
}
}
/*a+b =35
a-b =15

Prof. Shalini Puri 15


Ramrao Adik Institute of Technology F.E.Computer Programming II

a*b =250
a/b =2
a%b =5*/

3.2.3.2 Increment and Decrement Operators:


The ++ and –- are Java’s Increment and Decrement operators. The increment operator
increases its operand by one. The decrement operator decreases the operand by one.
Both are unary operators. For example this statement:
x = x+1;
can be rewritten like this by use of increment operator : x++;.
Similarly, this statement:
x = x-1;
Is equivalent to x--;
class InDec
{
public static void main(String args[])

{
int a =5,b=5;
System.out.println("a++ = "+(a++));
System.out.println("++b = "+(++b));
System.out.println("a-- = "+(a--));
System.out.println("--b = "+(--b));
}
}
/*a++ = 5
++b = 6*/
a-- = 6
--b = 5*/

3.2.3.3 Relational Operator:


The relational operators determine the relationship that one operand has to the other.
They determine equality and ordering.
Operator Meaning
== Equal to
!= Not Equal to
> Greater than
< Less than

Prof. Shalini Puri 16


Ramrao Adik Institute of Technology F.E.Computer Programming II

>= Greater than or equal to


<= Less than or equal to
class ROperator
{
public static void main(String args[])
{
int a=25,b=10,c=67;
System.out.println("a =" +(a));
System.out.println("b =" +(b));
System.out.println("c =" +(c));
System.out.println("a < b =" +(a < b));
System.out.println("a > b =" +(a > b));
System.out.println("a==c =" +(a==c));
System.out.println("a<=c =" +(a<=c));
System.out.println("a>=b =" +(a>=b));
System.out.println("a+b!=c =" +(a+b!=c));
System.out.println("a+b==c =" +(a+b==c));

}
}
/*a =25
b =10
c =67
a < b =false
a > b =true
a==c =false
a<=c =true
a>=b =true
a+b!=c =true
a+b==c =false*/

3.2.3.4 Logical Operator:


The logical operators shown here
class Logical
{ public static void main(String args[])
{ int a =5,b=5;
System.out.println("a ="+a);
System.out.println("b ="+b);
System.out.println("a>b && a==b = "+(a>b && a==b));
System.out.println("a>b || a==b = "+(a>b || a==b));
}
}
/*a =5
b =5
a>b && a==b = false

Prof. Shalini Puri 17


Ramrao Adik Institute of Technology F.E.Computer Programming II

a>b || a==b = true*/

3.2.3.5 Bitwise Operator:


class bit
{
public static void main(String args[])
{
int i=5;
int a=2,b;
int c=4,d=3;
b= i | a;
System.out.println(b+" ");
d=(d & c);
System.out.println(d+ " ");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac bit.java
C:\Java\jdk1.5.0_17\bin>java bit
7
0*/

3.2.3.6 Shift Operators:


A shift operator performs bit manipulation by shifting the bits left or right. The bits of the
first operand are shifted number of places as specified by the second operand. Java has
two operators for this purpose.
Operator Use Operation
>> op1 >> op2 Shift bits of op1 right by distance op2
<< op1 << op2 Shift bits of op1 left by distance op2
class shift
{
public static void main(String args[])
{
int i,j;
i= 6 << 2;
j= 23 >> 2;
System.out.println(i+" ");
System.out.println(j+ " ");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac shift.java
C:\Java\jdk1.5.0_17\bin>java shift
24

Prof. Shalini Puri 18


Ramrao Adik Institute of Technology F.E.Computer Programming II

5*/

3.2.3.7 Conditional Operator:


Java includes a special ternary operator that can replace certain types of if ….else
statements. The character ? :is a ternary operator available in Java. The operator is used
to construct conditional expression of the form:
Expression ? Expression2 : Expression3
The operator ? : works as follows: Expression1 is evaluated first. If it is true then the
Expression2 is evaluated and becomes the value of the conditional expression. If
Expression1 is false, Expression3 is evaluated and its value becomes the value of the
conditional expression. Only one of the expressions either Expression2 or Expression3 is
evaluated. For example consider the following statements:
a = 30;
b = 45;
c = a >b ? a: b
in this example c will be assigned the value of b.
Program to demonstrate Ternary operator:
class Cond
{
public static void main(String args[])
{
int a =10,b=15,c=25,max;
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
max = a > b ? a : b;
max = max > c ? max :c ;
System.out.println("Maxm of 3 nos : "+max);
}
}
/*a = 10
b = 15
c = 25
Maxm of 3 nos : 25*/

Prof. Shalini Puri 19


Ramrao Adik Institute of Technology F.E.Computer Programming II

4. Control Structures
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. Java’s program control

4.1 Simple If statement:


We have been using the If statement on and off like for example If we get minimum
marks then we pass. If we have money we go to theatre. The action depends on a
condition and is characterized in if statement. Its general syntax is as follows:
if ( condition ) statement ;
class area
{
public static void main(String args[])
{
int r;
r=Integer.parseInt(args[0]);
if(r>0)
System.out.println(3.14*r*r);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac area.java
C:\Java\jdk1.5.0_17\bin>java area 6
113.03999999999999
C:\Java\jdk1.5.0_17\bin>java area -9*/

4.2 If-Else Statement:


The if-else statement gives rise to Boolean conditions true or false. Like for example if
we get more than the specified marks we pass otherwise we fail. There are two different
actions depending on a Boolean condition. This is characterized in if-else statement. Its
general syntax is as follows:
If ( condition ) statement1;
else statement2;
class IfElseN
{
public static void main(String args[])
{
int a=325,b=712,c=478;
System.out.println("Largest value is :");
if(a>b)

Prof. Shalini Puri 20


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
if(a>c)
{
System.out.println("a ="+a);
}
else
{
System.out.println("c="+c);
}
}
else
{
System.out.println("b="+b);
}
}
}
/*Largest value is :
b=712*/

4.3 Switch-Case Statement:


The control statement which allows us to make a decision from the number of choices is
called a switch or more correctly a switch case default since these three keywords go
together to make up the control statement. They appear as follows:
switch(expression)
{
case value1 : do this;
break;
case value2 : Do this;
break;
default: do this;
}
The expression must be type byte, short, int or char each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must
be a unique literal. Duplicate case values are not allowed.
The switch statement works like this: the value of the expression is compared with each
of the literal values in the case statements. If a match is found the code sequence
following that case statement is executed. If none of the constants matches the value of
expression then the default statement is executed. However the default statement is
optional. If no case matches and no default is present, then no further action is taken.The
break statement is used in switch to terminate a statement sequence. When a break

Prof. Shalini Puri 21


Ramrao Adik Institute of Technology F.E.Computer Programming II

statement is encountered execution branches to the first line of code that follows the
entire switch statement. This has effect of jumping out of the switch.
The switch statement is used for designing menu driven interactive programs.
class Switch
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
int y= Integer.parseInt(args[1]);
String s =args[2];
char op =s.charAt(0);
switch(op)
{
case '+': System.out.println(x +"+" + y +"="+ (x+y));
break;
case '-': System.out.println(x +"-" + y +"="+ (x-y));
case '/': System.out.println(x +"/" + y +"="+ (x/y));
break;
case '%': System.out.println(x +"%" + y +"="+ (x%y));
break;
}
}
}
/*C:\ava\jdk1.5.0_04\bin>java Switch 23 45 +23+45=68
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 -
23-45=-22
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 /
23/45=0
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 %
23%45=23*/

Prof. Shalini Puri 22


Ramrao Adik Institute of Technology F.E.Computer Programming II

5. Loops
Java‘s iteration statements are for, while, do-while. These statements create what we
commonly call loops.

5.1 For Loop:


The for statement allows us to specify three things about a loop in a single line:
1. Setting a loop counter to initial value
2. Testing the loop counter to determine whether its value has reached the number of
repetitions desired.
3. Increasing the value of loop counter each time a program segment within the loop has
been executed.
The syntax of the for statement is:
for(initialization; condition; update)
{
//body of the loop
}
The initialization expression is used to declare and/or initialize control variables for the
loop. We can have more than one expression separated by comma.
The condition expression is used to determine whether the loop should continue iterating
it is evaluated immediately after the initialization if it is true the statement is executed
otherwise the loop is terminated
The update expression is used to update the control variable it is evaluated after the
statement is executed.
The loop then iterates first evaluating the conditional expression then executing
the body of the loop and then executing the update expression with each pass. This
process repeats until the controlling expression is false.
class ForLoop
{
public static void main(String args[])
{
int a,sum=0;
for(a=1;a<=30;)
{
sum+=a;
a=a+3;

Prof. Shalini Puri 23


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
System.out.println("Sum ="+(sum));
}
}
/*Sum =145*/

5.2 While Loop:


The while loop repeats a statement or block while its controlling expression is
true. The syntax for the while statement is:
while (condition)
{
//body of the loop;
}
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 becomes false control passes
to the next line of code immediately following the loop. The curly braces are unnecessary
if only a single statement is being repeated
class GCD
{
public static void main(String args[])
{
int num1=25,num2=35;
if(num1<num2)
{
int temp=num1;
num1=num2;
num2=temp;
}
int r=1;
while(r>0)
{
r=num1%num2;
num1=num2;
num2=r;
}
System.out.println("GCD is "+num1);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac GCD.java
C:\Java\jdk1.5.0_04\bin>java GCD
GCD is 5*/

Prof. Shalini Puri 24


Ramrao Adik Institute of Technology F.E.Computer Programming II

5.3 Do-While Loop:


The do-while loop is exactly reverse to that of while loop. The while loop checks
the condition prior to the execution of the loop. So the loop may never get executed at all
if the condition is not satisfied. The do-while checks the condition at the end of the loop.
So this loop is executed at least once by default.Its general form is:
do
{
//body of the loop;
}
while(condition);
class Reverse
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
int rev=0,x;
while(num>0)
{
x=num%10;
rev=rev*10+x;
num/=10;
}
System.out.println("The reverse number is: " + rev);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Reverse.java
C:\Java\jdk1.5.0_04\bin>java Reverse 9867
The reverse number is: 7689*/

5.4 Break and Continue Statement:


5.4.1 Break Statement:
In Java the statement has three uses:
1. It terminates a statement a sequence in a switch statement.
2. It can be used to exit a loop.
class Break
{
public static void main(String args[])
{
for(int i=1;i<100;i++)
{
if(i==10)

Prof. Shalini Puri 25


Ramrao Adik Institute of Technology F.E.Computer Programming II

break;
System.out.print(i +" ");
}
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Break.java
C:\Java\jdk1.5.0_04\bin>java Break
123456789 */

5.4.2 Continue Statement:


The continue statement is used to force an early iteration of a loop. This means we
may continue running the loop, but stop processing the remainder of the code in its body
for this particular iteration. The continue statement performs such an action. In the while
and do-while loops a continue statement cause control to be transferred directly to the
conditional expression that controls the loop. In a for loop control goes first to the
iteration portion of the for statement and then to the conditional expression. For all three
loops any intermediate code is bypassed. As with the break statement continue may
specify a label to describe enclosing loop to continue
class Continue
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.print(i +" ");
if(i%2==0)
continue;
System.out.println("");
}
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Continue.java
C:\Java\jdk1.5.0_04\bin>java Continue
01
23
45
67
8 9*/

Prof. Shalini Puri 26


Ramrao Adik Institute of Technology F.E.Computer Programming II

5.5 Exercise:
1. Write a program display table for 15.
2. Write a program for calculating the squares and cubes of the first 10 numbers.
3. Write a program to find the number of and sum of all integers greater than 100 and
less than 200 that are divisible by 7.
4. Write a program to find out first 10 prime numbers.
5. Write a program to find out whether a number is an Armstrong number or not.
6. Write a program to find out whether a number is a palindrome or not.
7. Write a program to find out the factorial of first 10 numbers.
8. Write a program to calculate the Permutation and Combination.
Pr = (n!/r!)
Cr =(n!/r!(n-r)!
9. Write a program to implement x raise to n.
10. Write a program to find out sine series
11. Write a program to find out cosine series
12. Generate Pascal’s triangle.
13. Find the sum of sequence 1 – ½+ 1/3 -1/4+ 1/5.
14. Find the sum of sequence 1 + 1/1! + ½! + 1/3!

Prof. Shalini Puri 27


Ramrao Adik Institute of Technology F.E.Computer Programming II

6. Functions
Functions are small pieces of code doing a particular task. Functions are called
methods in Java.

6.1 Methods in Java:


A method has a header line and a body. The header line consists of optional access
specifier, return type, method name and optional parameter list. The body consists of a
block. Block means zero or more statement within curly brackets. If the return type is
anything other than void, the last statement must be return statement. The methods may
or may not have parameters. Let us take an example where the parameters used are
variables:

6.1.1 Parameters as variables:


class method2
{
public static void main(String args[])
{
int rupees=3,paise=25;
int total;
total=convert(rupees,paise);
System.out.println("Total paise = "+ total);
}
public static int convert(int x,int y)
{
int temp;
temp=x*100+y;
return(temp);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac method2.java
C:\Java\jdk1.5.0_17\bin>java method2
Total paise = 325*/

6.2 Recursive Functions:


Functions when called by them are called as recursive functions. This technique is called
as recursive functions. We say that recursion is a replacement for loops and while writing
the function we should see to it that there is a condition where in the loop should end or it
might get into an infinite state.

Prof. Shalini Puri 28


Ramrao Adik Institute of Technology F.E.Computer Programming II

class Recursive
{
public static void main(String args[])
{
int n=5;
int f;
f=fact(n);
System.out.println("Factorial is = "+ f);
}
public static int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Recursive.java
C:\Java\jdk1.5.0_17\bin>java Recursive
Factorial is = 120*/

6.3 Exercise:
1. Write a program to print the Fibonacci series using recursive function.
class Fibonacci
{
public static void main(String args[])
{
int n=8;
System.out.print("The fibonacci series is :");
for(int i=0;i<n;i++)
{
System.out.print(fib(i)+" ");;
}
}
public static int fib(int n)
{
if(n==0 || n==1)
return(1);
else
return(fib(n-1)+fib(n-2));
}
}
C:\Java\jdk1.5.0_17\bin>javac Fibonacci.java
C:\Java\jdk1.5.0_17\bin>java Fibonacci
The fibonacci series is :1 1 2 3 5 8 13 21

Prof. Shalini Puri 29


Ramrao Adik Institute of Technology F.E.Computer Programming II

2. Write a program to print the Reverse and sum of integers using recursive
function.
class Parameter
{
public static void main(String args[])
{
int n=1234,s=0;
System.out.print("The reverse of number is :");
s=reverse(n,0);
System.out.println();
System.out.println("Sum of Digits is = "+ s);
}
public static int reverse(int x,int y)
{
int d;
if(x==0)
return(y);
else
{
d=x%10;
System.out.print(d+" ");
y=y+d;
}
return(reverse(x/10,y));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Parameter.java
C:\Java\jdk1.5.0_17\bin>java Parameter
The reverse of number is :4 3 2 1
Sum of Digits is = 10*/

3. Write a program to print G.C.D of two number using recursive functions


class GCD
{
static int gcd(int a,int b)
{
int r=a%b;
if(r==0)
return(b);
else
return(gcd(b,r));
}
public static void main(String args[])
{
int a=27,b=81;

Prof. Shalini Puri 30


Ramrao Adik Institute of Technology F.E.Computer Programming II

if(a<b)
System.out.println(gcd(b,a));
else
System.out.println(gcd(a,b));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac GCD.java
C:\Java\jdk1.5.0_17\bin>java GCD
27*/

Prof. Shalini Puri 31


Ramrao Adik Institute of Technology F.E.Computer Programming II

7. Arrays
An array is a group of contiguous or related data items that share a common name. For
instance we can define an array name salary to represent a set of salaries of a group of
employees. A particular value is indicated by writing a number called index number or
subscript in brackets after the array name. For example, salary[10]
represents the salary of the 10th employee. While the complete set of values is referred to
as an array, the individual values are called elements. Arrays can be of any variable type.
The ability to use a single name to represent a collection of items and to refer to an item
by specifying the item number enables us to develop concise and efficient programs. For
example, a loop with the subscript as the control variable can be used to read the entire
array, perform calculations and print out the results.

7.1 Creating an Array:


After declaring an array we need to create it in the memory. Java allows us to create
arrays using new operator only as shown below:
arrayname = new type[size];
Examples:
number = new int [5];
average = new float [10];
These lines create memory locations for the array number and average and designate
them as int and float respectively. Now the variable number refers to an array of integers
and average refers to an array of 10 floating point numbers.
These two steps can be combined into one as shown below:
int number [ ] = new int [5];

7.2 Array Index Checking:


In Java all arrays store the allocated size in a variable named length. We can
access the length of the array a using a.length.
class Array
{
public static void main(String args[])
{
int num[]={55,40,80,65,71},sum=0;

Prof. Shalini Puri 32


Ramrao Adik Institute of Technology F.E.Computer Programming II

int n=num.length;
System.out.println("The List is :");
for(int i=0;i<n;i++)
{
System.out.println(num[i]+" ");
sum+=num[i];
}
System.out.println("Sum ="+(sum));
}
}
/*The List is :
55 40 80 65 71
Sum =311*/

7.3 SystemArraycopy():
If we want to make a true copy of an array we must make a new array of the same
length as the original and copy overall values:
double [] prices = new double[data.length];
for(int i=0;i<data.length;i++)
prices[i] = data[i];
Instead of the for loop you can also use the static System.arrayCopy method. The
method can be used to copy any portion of an array into another array.
System.arrayCopy (from,fromStart,to,toStart,count);
To copy the entire data array into the prices array we say:
System.arrayCopy(data,0,prices,0,data.length);
class ArrayCopy
{ public static void main(String[] args)
{ int x[] = {11,22,33,44,55};
int y[] = new int[5];
System.arraycopy(x,0,y,0,5);
System.out.println("Array y after copying is :");
for(int i=0;i<5;i++)
{System.out.print(" " + y[i]);
}
}
}
/*C:\Java\jdk1.6.0_05\bin>javac ArrayCopy.java
C:\Java\jdk1.6.0_05\bin>java ArrayCopy
Array y after copying is :
11 22 33 44 55 */

Prof. Shalini Puri 33


Ramrao Adik Institute of Technology F.E.Computer Programming II

7.4 Multidimensional Arrays:


There will be situations where a table of values will have to be stored. Say for example if
we want to refer to a data which shows the value of four sales girls selling three different
items in a month.
Item1 Item2 Item3
Salesgirl#1 310 275 365
Salesgirl#2 210 190 325
Salesgirl#3 405 235 240
Salesgirl#4 260 300 380

The table contains a total of 12 values three in each line. We can think of this table as a
matrix consisting of four rows and three columns. Each row represent the value of sales
by a particular salesgirl and each column represents the value of sales of a particular item.
Java allows us to define such tables of items using two dimensional arrays. The table
discussed above can be represented in Java as v[4][3]. For creating two dimensional
arrays we must follow the same steps as a single dimensional array.
int myArray [ ] [ ] = new int [3][4];

7.5 Exercise:
7.5.1 Linear Search:
class search
{
public static void main(String args[])
{
int x[]= {23,55,14,18,67};
int r, n = 5,i;
r=Integer.parseInt(args[0]);
System.out.print("List of elements : ");
for(i=0;i<n;i++)
{
System.out.print(x[i]+ " ");
}
System.out.println();
for(i=0;i<n;i++)
{
if(r==x[i])
{
System.out.println("Element " +r+" found at " + i +" position");
break;
}

Prof. Shalini Puri 34


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
if(i==n)
System.out.println("Element not found");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac search.java
C:\Java\jdk1.5.0_17\bin>java search 18
List of elements : 23 55 14 18 67
Element 18 found at 3 position
C:\Java\jdk1.5.0_17\bin>java search 17
List of elements : 23 55 14 18 67
Element not found*/

7.5.2 Sorting an Array:


class Sort
{
public static void main(String args[])
{
int num[]={55,40,80,65,71},sum=0;
int n=num.length;
System.out.println("The List is :");
for(int i=0;i<n;i++)
{
System.out.println(num[i]+" ");
}
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(num[i]>num[j])
{
int temp = num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
System.out.println("The Sorted List is :");
for(int i=0;i<n;i++)
{
System.out.println(num[i]+" ");
}
}
}
/*The List is :
55 40 80 65 71

Prof. Shalini Puri 35


Ramrao Adik Institute of Technology F.E.Computer Programming II

The Sorted List is :


40 55 65 71 80*/

7.5.3 Checking for duplicate elements:


class search
{
public static void main(String args[])
{
int x[]= {23,55,18,18,67};
int r, n = 5,i,c=0;
r=Integer.parseInt(args[0]);
System.out.print("List of elements : ");
for(i=0;i<n;i++)
{
System.out.print(x[i]+ " ");
}
System.out.println();
for(i=0;i<n;i++)
{
if(r==x[i])
{
System.out.println("Element " +r+" found at " + i +" position");
c++;
}
}
if(c==0)
System.out.println("Element not found");
else
System.out.println("Element found "+ c +" times");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac search.java
C:\Java\jdk1.5.0_17\bin>java search 18
List of elements : 23 55 18 18 67
Element 18 found at 2 position
Element 18 found at 3 position
Element found 2 times
C:\Java\jdk1.5.0_17\bin>java search 17
List of elements : 23 55 18 18 67
Element not found

7.5.4 Matrix Addition:


class matadd
{
public static void main(String args[])
{

Prof. Shalini Puri 36


Ramrao Adik Institute of Technology F.E.Computer Programming II

int ROWS=4,COLS=4;
int x[][]=new int[ROWS][COLS];
int y[][]=new int[ROWS][COLS];
int z[][]=new int[ROWS][COLS];
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
x[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
y[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
z[i][j]=(x[i][j]+y[i][j]);
}
}
System.out.println("The X array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+x[i][j]);
}
System.out.println();
}
System.out.println("The Y array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+y[i][j]);
}
System.out.println();
}
System.out.println("The Z array is :");

Prof. Shalini Puri 37


Ramrao Adik Institute of Technology F.E.Computer Programming II

for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+z[i][j]);
}
System.out.println();
}
}
}
/*C:\Java\jdk1.5.0_17\bin>javac matadd.java
C:\Java\jdk1.5.0_17\bin>java matadd
The X array is :
1234
5678
9 10 11 12
13 14 15 16
The Y array is :
1234
5678
9 10 11 12
13 14 15 16
The Z array is :
2468
10 12 14 16
18 20 22 24
26 28 30 32*/

7.5.5 Matrix Multiplication:


class Matrix
{
public static void main(String args[])
{
int ROWS=4,COLS=4;
int x[][]=new int[ROWS][COLS];
int y[][]=new int[ROWS][COLS];
int z[][]=new int[ROWS][COLS];
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
x[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)

Prof. Shalini Puri 38


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
for(int j=0;j<COLS;j++)
{
y[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
z[i][j]=0;
for(k=0;k<ROWS;k++)
{
z[i][j]+=(x[i][k]*y[k][j]);
}
}
}
System.out.println("The X array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+x[i][j]);
}
System.out.println();
}
System.out.println("The Y array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+y[i][j]);
}
System.out.println();
}
System.out.println("The Z array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+z[i][j]);
}
System.out.println();
}
}

Prof. Shalini Puri 39


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
/*The X array is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The Y array is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The Z array is :
90 100 110 120
202 228 254 280
314 356 398 440
426 484 542 600*/

Prof. Shalini Puri 40


Ramrao Adik Institute of Technology F.E.Computer Programming II

8. Introduction Classes:
Class can be considered as a user defined data type. It is a template for the object to be
created. It holds some data. Let us take an example of time. It consists of hours, minutes
and seconds. To store these quantities, we need three different fields (variables). But
together they constitute a single object.

8.1 General form of a Class:


A class in general has two types of members. They are as follows:
Fields: These are variables associated with the class.
Methods: There are procedures, which define the behavior (executable code) of the object
class time
{
int hour;
int minute;
int second;
};

8.2 Declaring and Creating Objects:


An object is an instantiation of a class. So an object declaration is like any other
variable declaration.
Time t;
However this is not sufficient we have to allocate memory to it.
T = new Time ( );
We may combine the two statements and write.
Time T = new Time ( );
If we start using the object without declaring it we get a compilation error which says that
we are using the object without initializing it.
Let us take an example of class Time and introduce its methods::
class Time
{
int hour;
int minute;
int second;
int total;
void getdata(int a,int b,int c)
{

Prof. Shalini Puri 41


Ramrao Adik Institute of Technology F.E.Computer Programming II

hour=a;
minute=b;
second=c;
}
void putdata()
{
System.out.println("Hour = " +hour);
System.out.println("Minute = " +minute);
System.out.println("Second = " +second);
total=hour*60*60+minute*60+second;
System.out.println("Total Seconds = "+total);
}
}
class TDetail
{
public static void main(String args[])
{
Time T =new Time();
T.getdata(2,25,56);
T.putdata();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TDetail.java
C:\Java\jdk1.5.0_17\bin>java TDetail
Hour = 2
Minute = 25
Second = 56
Total Seconds = 8756*/

8.3 Accessing Members:


There are two types of access specifiers that we will discuss public and private. If
a variable in a class is declared as private then it is not accessible outside the class but can
be accessed by the methods of the same class and if the variables are declared as public
then they can be accessed inside the classes and also to the outside world.

8.4 Introducing Methods:


A class in Java contains data in the form of variables. It also contains functions to work
with these variables. These functions are termed as methods in Java.

8.4.1 Methods with parameters as variables:


class Time
{
int hour,minute;

Prof. Shalini Puri 42


Ramrao Adik Institute of Technology F.E.Computer Programming II

void convert(int n)
{
hour=n/60;
minute=n%60;
}
void display()
{
System.out.println(hour + " " +minute);
}
}
class TDetails
{
public static void main(String args[])
{
Time T =new Time();
T.convert(384);
T.display();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TDetails.java
C:\Java\jdk1.5.0_17\bin>java TDetails
6 24*/

8.4.2 Methods with parameters as Objects:


class Time
{
int hour,minute,second;
void getdata(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
Time convert(Time A)
{
Time temp=new Time();
temp.second=second+A.second;
temp.minute=temp.second/60;
temp.second=temp.second%60;
temp.minute+=minute+A.minute;
temp.hour=temp.minute/60;
temp.minute=temp.minute%60;
temp.hour+=hour+A.hour;
return(temp);
}
void display()

Prof. Shalini Puri 43


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
System.out.println(hour + " " +minute+ " "+second);
}
}
class TMDetail
{
public static void main(String args[])
{
Time T1 =new Time();
Time T2=new Time();
T1.getdata(3,54,45);
T1.display();
T2.getdata(2,44,23);
T2.display();
Time T3=new Time();
T3=T1.convert(T2);
T3.display();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TMDetail.java
C:\Java\jdk1.5.0_17\bin>java TMDetail
3 54 45
2 44 23
6 39 8*/

8.5 Constructors:
All objects that are created must be given initial values. There are two ways of
initializing the variables of objects. The first approach uses the dot operator to access the
instance variables and then assign values to them individually. It can be tedious approach
to initialize all the variables of all the objects. The second approach takes the help of a
method like getdata to initialize each object individually
class Rectangle
{
int length,width;
Rectangle(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
return(length*width);
}

Prof. Shalini Puri 44


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
class RectangleArea
{
public static void main(String args[])
{
Rectangle Room=new Rectangle(10,20);
System.out.println("Area ="+Room.rectarea());
}
}
/*Area =200*/

8.6 Array of Objects:


import java.io.*;
class Employee
{
int empno;
String Name;
float sal;
void get(int a,String n,float s)
{
empno=a;
Name=n;
sal=s;
}
void put()
{
System.out.println(empno+ " "+Name+ " "+sal);
}
}
class EmpDetail
{
public static void main(String args[])throws IOException
{
Employee a[]=new Employee[5];
BufferedReader obj =new BufferedReader(new InputStreamReader(System.in));
String str;
int x; float f;
int i;
for(i=0;i<2;i++)
{
a[i]=new Employee();
}
for(i=0;i<2;i++)
{
System.out.println("Enter Rollno :");

Prof. Shalini Puri 45


Ramrao Adik Institute of Technology F.E.Computer Programming II

x=Integer.parseInt(obj.readLine());
System.out.println("Enter Name :");
str=obj.readLine();
System.out.println("Enter Salary :");
f=Float.parseFloat(obj.readLine());
a[i].get(x,str,f);
}
for(i=0;i<2;i++)
{
a[i].put();
}
}
}
/*E:\\Java\jdk1.5.0_16\bin>javac EmpDetail.java
E:\Java\jdk1.5.0_16\bin>java EmpDetail
Enter Rollno :1
Enter Name :shalini
Enter Salary :5000
Enter Rollno :2
Enter Name :ajay
Enter Salary :6000
1 shalini 5000.0
2 ajay 6000.0*/

8.7 Static Variables and Static Methods:


A class basically contains two sections. One declares variables and the other declares
methods. These variables and methods are called as instance variables and instance
methods. This is because every time the class is instantiated a new copy of each of them
is created. They are accessed using the objects (with dot operator).
Let us assume that we want to define a member that is common to all objects & accessed
without using a particular object. That is the member belongs to the class as a whole
rather than the objects created from the class. Such members can be defined as follows:
static int count;
static int max(int x, int y);
The members that are declared static as shown above are called static members. Since
these members are associated with the class itself rather than individual objects, the static
variables and static methods are often referred to as class variables and class methods in
order to distinguish them from their counterparts, instance variable and instance methods.
Static variables are used when we want to have a variable common to all instances of a

Prof. Shalini Puri 46


Ramrao Adik Institute of Technology F.E.Computer Programming II

class. One of the most common examples is to have a variable that could keep a count of
how many objects of a class have been created. Java creates only one copy for a static
variable which can be used even if the class is actually instantiated. Like static variables
static methods can be called without using the objects. They are also available for use by
other classes, methods that are of general utility but do not directly affect an instance of
that class are usually declared as class methods. The static methods are called using class
names. No objects have been created for use. Static methods have several instructions:
1. They can call only call other static methods.
2. They can access only static data.
3. They cannot refer to this or super in any way.
class MathOperation
{
static int mul(int x,int y)
{
return(x*y);
}
static int divide(int x,int y)
{
return(x/y);
}
}
class MathApplication
{
public static void main(String args[])
{
int a = MathOperation.mul(3,5);
int b = MathOperation.divide(a,2);
System.out.println("b ="+b);
}
}
/*C:\Java\jdk1.6.0_05\bin>javac MathApplication.java
C:\Java\jdk1.6.0_05\bin>java MathApplication
b =7*/

Prof. Shalini Puri 47


Ramrao Adik Institute of Technology F.E.Computer Programming II

9. Wrapper Classes
When we give gifts, we wrap them nicely in a box. The gift may be a doll or a toy car or
something else. The box and the glossy paper round it make it attractive. We have
worked with simple data types. Now java will wrap them and make it attractive. For this
Java provides an interesting concept of wrapper classes.

9.1 Introduction:
We have studied the basic data type float. It holds the floating-point number. Now Java
provides a class Float. As identifiers are case sensitive float and Float are different. The
new class Float is for storing floating-point. Similarly an int is wrapped in a class Integer.
It also has methods that work within this class. The other wrapper classes are Byte, Short,
Integer, Long and Double.

9.2 Class Integer:


The Integer Wrapper class is the Java class that converts the value of a primitive data
type int into an object of the Integer Wrapper class.
class IntWrapper
{
public static void main(String args[])
{
int n =25;
Integer val = new Integer(n);
System.out.println("Value of Integer object is ="+val);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac IntWrapper.java
C:\Java\jdk1.5.0_17\bin>java IntWrapper
Value of Integer object is =25*/

9.3 Class Float:


The Float Wrapper class is the Java class that converts the value of a primitive data type
float into an object of the Float Wrapper class.
class float1
{
public static void main(String args[])
{
Float f1=new Float(2.5);
Float f2 = new Float(2.6F);

Prof. Shalini Puri 48


Ramrao Adik Institute of Technology F.E.Computer Programming II

Float f3 = new Float("2.7");


System.out.println("f1 ="+f1);
System.out.println("f2 ="+f2);
System.out.println("f3 ="+f3);
System.out.println("Max Value = "+Float.MAX_VALUE);
System.out.println("Min Value = "+Float.MIN_VALUE);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac float1.java
C:\Java\jdk1.5.0_17\bin>java float1
f1 =2.5
f2 =2.6
f3 =2.7
Max Value = 3.4028235E38
Min Value = 1.4E-45*/

9.4 Class Double:


The Double Wrapper class is the Java class that converts the value of a primitive data
type double into an object of the Double Wrapper class.
class DWrapper
{
public static void main(String args[])
{
double d=2.14;
Double val = new Double(d);
System.out.println("Value of Double object is ="+val);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac DWrapper.java
C:\Java\jdk1.5.0_17\bin>java DWrapper
Value of Double object is =2.14*/

9.5 Class Boolean:


The Boolean Wrapper class is the Java class that converts the value of a primitive data
type Boolean into an object of the Boolean Wrapper class.
class BWrapper
{
public static void main(String args[])
{
boolean b =true;
Boolean val = new Boolean(b);
System.out.println("Value of Boolean object is ="+val);
}
}

Prof. Shalini Puri 49


Ramrao Adik Institute of Technology F.E.Computer Programming II

/*C:\Java\jdk1.5.0_17\bin>javac BWrapper.java
C:\Java\jdk1.5.0_17\bin>java BWrapper
Value of Boolean object is =true*/

9.6 Class Character:


The Character Wrapper class is the Java class that converts the value of a primitive data
type character into an object of the Character Wrapper class.
class CWrapper
{
public static void main(String args[])
{
char b ='D';
Character val = new Character(b);
System.out.println("Value of Character object is ="+val);
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac CWrapper.java
C:\Program Files\Java\jdk1.5.0_17\bin>java CWrapper
Value of Character object is =D*/

Prof. Shalini Puri 50


Ramrao Adik Institute of Technology F.E.Computer Programming II

10. Strings
Strings are very important part of the programming language as they are used to process
long textual/symbolic information. For example when we visit a bank to open an account
then we are asked for information such as name, address. The information we provide is
in the form of ordered sequence of characters and symbols. The ordered sequence of
characters and symbols is known as String.

10.1 Declaring and Constructing a String:


Strings represent a sequence of characters a java string is an instantiated object of the
string class. Strings may be declared and created as follows:
String stringName;
stringName = new String(“string”);

10.2 Methods of Strings:


The String class defines a number of methods that allows us to accomplish a variety of
string manipulation tasks. The below table lists some of the most commonly used string
methods and their tasks.
Method Call Task performed
s2 = s1.toLowerCase() Converts the string s1 to all lower case
s2 = s1.toUpperCase() Converts the string s1 to all upper case
s2 = s1.replace(‘x’,’y’); Replaces all appearances of ‘x’ with ‘y’
s2 = s1.trim() Removes white spaces at the beginning & end of the s1.
s1.equals(s2) Returns true if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns true if s1 is equal to s2 ignoring the case of characters
s.length() Gives the length of s.
s1.charAt(n) Gives the nth character of s1.
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2 & zero if s1 = s2.
s1.concat(s2) Concatenates s1 and s2.
s1.substring(n) Gives substring starting from the nth character
s1.substring(n,m) Gives substring starting from the nth character to mth character
s1.indexOf(‘x’) Give the position of the first occurrence of ‘x’ in the string s1.

Prof. Shalini Puri 51


Ramrao Adik Institute of Technology F.E.Computer Programming II

S1.lastindexOf(‘x’) Give the position of the last occurrence of ‘x’ in the string s1.

class DString
{
public static void main(String args[])
{
String Name =new String("Shalini");
System.out.println("Name = " +Name);
int len=Name.length();
System.out.println("Length = "+len);
String N1=new String();
N1=Name.toLowerCase();
System.out.println("Lower Case of Name = " +N1);
String N2=new String();
N2=Name.toUpperCase();
System.out.println("Upper Case of Name = " +N2);
String N3=new String();
N3=Name.replace('i','b');
System.out.println("Upper Case of Name = " +N3);
System.out.println("Name equals N1 = " +Name.equals(N1));
System.out.println("Name equals N1 = " +Name.equalsIgnoreCase(N1));
System.out.println("Name compares N1 = " +Name.compareTo(N1));
System.out.println("N1 compares Name = " +N1.compareTo(Name));
System.out.println("Concatenate Name with string = " +Name.concat("Puri"));
System.out.println("Substring of Name = " +Name.substring(3));
System.out.println("Substring of Name = " +Name.substring(2,5));
System.out.println("Index of i in Name = " +Name.indexOf('i'));
}
}
/*Name = Shalini
Length = 7
Lower Case of Name = shalini
Upper Case of Name = SHALINI
Upper Case of Name = Shalbnb
Name equals N1 = false
Name equals N1 = true
Name compares N1 = -32
N1 compares Name = 32
Concatenate Name with string = ShaliniPuri
Substring of Name = lini
Substring of Name = ali
Index of i in Name = 4*/

Prof. Shalini Puri 52


Ramrao Adik Institute of Technology F.E.Computer Programming II

10.3 Sorting Strings:


class Sort
{
public static void main(String args[])
{
String name[]={"raj","ajay","amar","sita","nitin"};
String temp;
int n=name.length;
int i,j;
System.out.println("Names before sorting :");
for(i=0;i<n;i++)
System.out.print(name[i]+ " ");
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
int x=name[i].compareTo(name[j]);
if(x>0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
System.out.println();
System.out.println("Names after sorting :");
for(i=0;i<n;i++)
System.out.print(name[i]+" ");
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac Sort.java
C:\Program Files\Java\jdk1.5.0_17\bin>java Sort
Names before sorting :
raj ajay amar sita nitin
Names after sorting :
ajay amar nitin raj sita*/

10.4 Methods valueOf() and toString():


The representation of any object on paper or on screen requires a string. Java
offers methods valueOf() and toString() to convert an integer and a float value into a
String.

Prof. Shalini Puri 53


Ramrao Adik Institute of Technology F.E.Computer Programming II

10.5 Vector:
Java provides a feature of a vector class contained in the java.util package. This class
can be used to create generic dynamic array known as vector that can be used to hold
objects of any type & any number. The objects do not have to be homogeneous. Arrays
can be easily implemented as vectors. Vectors can be created like arrays as follows:
Vector intVect = new Vector( ); // Declaring without size.
Vector list = new Vector(3). // Declaring with size.
Note that a vector can be declared without specifying any size explicitly. A vector can
accommodate an unknown number of items. Even when a size is specified it can be
overlooked and a different number of items may be put into the vector. But if we
compare it with an array the size of the array has to be specified. Vectors possess a
number of advantages over arrays.
 It is convenient to use vectors to store objects.
 A vector can be used to store a list of objects that may vary in size.
 We can add and remove objects from the list as and when required.
Important vector methods:
Method call Task Performed
list.addElement(item) Add the item specified to the list at the end
list.elementAt(10) Gives the name of the 10th object
list.size() Gives the number of objects present
list.removeElement(item) Removes the specified item from the list
list.removeElementAt(n) Removes the item stored in the nth position of the list
list.removeAllElements() Removes all elements in the list.
list.copyInto(array() Copies all items from the list to array
List.insertElementAt(item,n) Inserts the item at nth position

The above program illustrates the use of arrays, strings and vectors. This program
converts a string vector into an array of strings and displays the strings.
import java.util.*;
class LanguageVector
{
public static void main(String[] args)

Prof. Shalini Puri 54


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
Vector list =new Vector( );
int length = args.length;
for(int i=0;i<length;i++)
{
list.addElement(args[i]);
}
list.insertElementAt("COBOL",2);
int size =list.size( );
String listArray[] = new String[size];
list.copyInto(listArray);
System.out.println("List of languages :");
for(int i=0;i<length;i++)
{
System.out.println(listArray[i]);
}
}
}
/*C:Java\jdk1.6.0_05\bin>javac LanguageVector.java
C:\Java\jdk1.6.0_05\bin>java LanguageVector Ada Basic C++ FORTRAN Java
List of languages :
Ada
Basic
COBOL
C++
FORTRAN
Java
C:\Java\jdk1.6.0_05\bin>*/

Prof. Shalini Puri 55


Ramrao Adik Institute of Technology F.E.Computer Programming II

11. Simple Input/Output


Modern computers have many input/output services. Any modern programming language
should provide methods to work with them. Receiving values from a user helps in
generating dynamic results as every time user may enter different values. Receiving
value/data from a user is known as input and producing output by an application is
known as I/O operations. Java allows users to perform I/O operations with the help of
stream. A stream can be defined as a path to communicate between the program and the
source or destination of any information. The source of information can be a file or
console and the information can be saved in a file or displayed on console. Streams are
considered as the basic of all I/O operations as all I/O operations are performed through
streams. There are two types of streams:
 Byte Streams are used to handle I/O operations on binary data. All the classes of byte
stream are derived from InputStream and OutputStream classes. The InputStream and
OutputStream classes are considered as the main classes of byte stream. They are further
divided into DataInputStream, DataOutputStream, FileInputStream & FileOutputStream.
 Character Streams are the streams that represent data in the form of characters. They
are used to handle I/O operations on characters. To use the character stream classes we
have to import java.io package in our java program. The two main classes of the
character stream are Reader and Writer. Some of the examples of character stream classes
are Reader, Writer, InputStreamReader, OutputStreamWriter, BufferedReader,
BufferedWriter, FileReader and FileWriter.
Java also uses some predefined stream objects like in, out and err available in the System
class. The system class is available in the System package that comes by default with the
java.lang package. These predefined stream objects are use to specify the input and
output streams. The System.out represents the standard output stream which is the
console. On the other hand the System.in represents the standard input stream which is
the keyboard. Here are some I/O operations in Java.

11.1 Reading Character fron Console Input:


Java allows user to read data from the standard input device to be displayed on the
console. The System.in is used to read input from the standard input device. Once the

Prof. Shalini Puri 56


Ramrao Adik Institute of Technology F.E.Computer Programming II

data is being read from the standard input device, the System.in should be wrapped in the
DataInputStream object. This wrapping of the DataInputStream object allows users to
obtain the byte stream attached with the console. The following code is used to wrap the
System.in in the DataInputStream. And further a read () method is used to read the data.
import java.io.*;
class ReadChar
{
public static void main(String args[])
{
DataInputStream obj=new DataInputStream(System.in);
char ch =' ';
try
{
System.out.println("Enter Q to exit ");
while(ch!='Q')
{
ch=(char)obj.read();
System.out.println(ch);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/* C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java
C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar
Enter Q to exit
ShaliniQ
ShaliniQ*/

11.2 Reading Strings:


Java allows users to read strings of text from the console. Here we use a readLine ( ), a
method of BufferedReader class.
import java.io.*;
class ReadChar
{
public static void main(String args[]) throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, Q to quit");
String str[]=new String[200];

Prof. Shalini Puri 57


Ramrao Adik Institute of Technology F.E.Computer Programming II

int i;
for(i=0;i<10;i++)
{
str[i]=obj.readLine();
if(str[i].equals("Q"))
break;
}
System.out.println("Text entered by is :");
for(i=0;i<10;i++)
{
if(str[i].equals("Q"))
break;
System.out.println(str[i]);
}

}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java
C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar
Enter some text, Q to quit
Welcome to the World of Java
Q
Text entered by is :
Welcome to the World of Java*/

Prof. Shalini Puri 58


Ramrao Adik Institute of Technology F.E.Computer Programming II

12. Inheritance
In object oriented programming the term Inheritance refers to the fact that one class can
inherit part or all of its structure and behavior from another class. The class that does the
inheriting is said to be a subclass of the class from which it inherits. If class B is a
subclass of A we also say that class A is a super class of class B. A subclass can add to
the structure and behavior that it inherits .It can also modify inherited behavior. The
relationship between subclass and super class is shown by the below diagram.

Class A
(superclass)

Class B
(subclass)

Java uses the ‘extends’ keyword to set the relationship between a child class and a parent
class. For example to create a class named “B” as a subclass of class named “A” we
would write:
Class B extends A
{
………………..
}

12.1 Types of Inheritance:


Inheritance may take different forms:
1. Single Inheritance:
A sub class with only one super class is called single inheritance.

B
A program that illustrates Single level Inheritance:
class Room
{
int length,breadth;
Room(int l,int b)

Prof. Shalini Puri 59


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
length=l;
breadth=b;
}
int area()
{
return(length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class InherTest
{
public static void main(String args[])
{
BedRoom Room1=new BedRoom(10,20,30);
int area1=Room1.area();
int volume1=Room1.volume();
System.out.println("Area = "+area1);
System.out.println("Volume = "+volume1);
}
}
/*Area = 200
Volume = 6000*/

2. Hierarchical Inheritance : ( one super class and many subclasses)


The features of one class may be inherited by more than one class this process is
known as Hierarchical Inheritance.

B C D
Prof. Shalini Puri 60
Ramrao Adik Institute of Technology F.E.Computer Programming II

The below program illustrates Hierarchical Inheritance:


class Shape
{ protected double bs,ht,area;
void getdata(double b,double h)
{
bs=b;
ht=h;
}
}
class Triangle extends Shape
{
void display()
{
area=0.5*bs*ht;
System.out.println("Area of triangle is "+area);
}
}
class Rectangle extends Shape
{
void display()
{
area=bs*ht;
System.out.println("Area of triangle is "+area);
}

}
class HITest
{
public static void main(String args[])
{
Triangle T = new Triangle();
Rectangle R = new Rectangle();
T.getdata(3.5,7.5);
T.display();
R.getdata(4,4);
R.display();
}

}
/*Area of triangle is 13.125
Area of triangle is 16.0*/

12.1.1 Super:
A sub class can call a constructor method defined by its super class by the use of
the following form of super:

Prof. Shalini Puri 61


Ramrao Adik Institute of Technology F.E.Computer Programming II

super(parameter list);
Here parameter list specifies any parameters needed by the constructor in the super class.
super( ) must always be the first statement executed inside a sub class’s constructor. To
see how super is used consider the following program:

Vehicle

Two Wheeler Four Wheeler

class Vehicle
{
private String Make;
private double Milage;
Vehicle(String m,double d)
{
Make=m;
Milage=d;
}
void display()
{
System.out.println("Name of the company :"+Make);
System.out.println("Milage of the Vehicle :"+Milage);
}
}
class TwoWheeler extends Vehicle
{
private char clutch;
TwoWheeler(String m,double d,char c)
{
super(m,d);
clutch=c;
}
void display()
{
super.display();
System.out.println("Clutch present :"+clutch);
}
}
class FourWheeler extends Vehicle
{
private char Ac;

Prof. Shalini Puri 62


Ramrao Adik Institute of Technology F.E.Computer Programming II

FourWheeler(String m,double d,char c)


{
super(m,d);
Ac=c;
}
void display()
{
super.display();
System.out.println("AC present :"+Ac);
}
}
class transport
{
public static void main(String args[])
{
TwoWheeler T =new TwoWheeler("Hero Honda",70,'y');
FourWheeler F =new FourWheeler("Maruti",17,'y');
T.display();
F.display();
}
}
/*Name of the company :Hero Honda
Milage of the Vehicle :70.0
Clutch present :y
Name of the company :Maruti
Milage of the Vehicle :17.0
AC present :y*/

12.2 Multilevel Inheritance:


The mechanism of deriving a class from another derived class is known as Multilevel
Inheritance.

Prof. Shalini Puri 63


Ramrao Adik Institute of Technology F.E.Computer Programming II

The program below illustrates Multilevel Inheritance:


class Student
{
int RollNo;
String Name;
Student(int a,String n)
{
RollNo=a;
Name=n;
}
void display()
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+Name);
}
}
class Test extends Student
{
float m1,m2;
Test(int a,String m,float x,float y)
{
super(a,m);
m1=x;
m2=y;
}
void show()
{
System.out.println("Marks 1 = "+m1);
System.out.println("Marks 2 = "+m2);
}
}
class Result extends Test
{
float total;
Result(int a,String m,float x,float y)
{
super(a,m,x,y);
}
void showRes()
{
System.out.println("Result = "+(m1+m2));
}
}
class MulTest
{
public static void main(String args[])

Prof. Shalini Puri 64


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
Result R = new Result(1,"Shalini",50,67);
R.display();
R.show();
R.showRes();
}
}
/*Roll No = 1
Name = Shalini
Marks 1 = 50.0
Marks 2 = 67.0
Result = 117.0*/

12.2.1 Protected:
The access specifier works as private for the outside world but works as public
for derived classes. Let us take the following example:
class Student
{
protected int RollNo;
protected String Name;
Student(int a,String n)
{
RollNo=a;
Name=n;
}
}
class Test extends Student
{
protected float m1,m2;
Test(int a,String m,float x,float y)
{
super(a,m);
m1=x;
m2=y;
}
void show()
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+Name);
}
}
class Result extends Test
{
float total;
Result(int a,String m,float x,float y)

Prof. Shalini Puri 65


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
super(a,m,x,y);
}
void showRes()
{
System.out.println("Marks 1 = "+m1);
System.out.println("Marks 2 = "+m2);
System.out.println("Result = "+(m1+m2));
}
}
class MulTest
{
public static void main(String args[])
{
Result R = new Result(1,"Shalini",50,67);
R.show();
R.showRes();
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac MulTest.java
C:\Program Files\Java\jdk1.5.0_17\bin>java MulTest
Roll No = 1
Name = Shalini
Marks 1 = 50.0
Marks 2 = 67.0
Result = 117.0*/

12.3 Method Overriding:


When same name appears for methods in both the super and sub class only method from
sub class is invoked. So we say that the method of the sub class overrides the super class
method. However super class method is not lost, it is available. It has to be called using
the keyword super as we have seen in the 12.1.1 section.

12.4 Interface:
The object oriented programming languages such as C++ allows a class to extend two or
more super classes. This is called multiple inheritance. But Multiple Inheritance is not
allowed in Java so it provides an alternate approach as interfaces to support it.
Interface is basically a kind of class. The difference is that interfaces do not specify any
code to implement these methods and data fields contain only constants. Therefore it is
the responsibility of the class that implements an interface to define the code for
implementation of these methods. The syntax for defining an interface is very similar to

Prof. Shalini Puri 66


Ramrao Adik Institute of Technology F.E.Computer Programming II

that for defining a class. The general form of an interface definition is:
interface InterfaceName
{
Variable declaration;
Method declaration;
}
Here interface is the keyword and InterfaceName is any valid Java variable (just like the
class names). Variables are declared as follows:
interface Area
{
float pi =3.142F;
float compute (float x, float y);
void show( );
}

12.4.1 Implementing Interfaces:


Interfaces are used as “super classes “ whose properties are inherited
interface Area
{
final float pi =3.14F;
float compute(float x,float y);
}
class Rectangle implements Area
{
public float compute (float x,float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute (float x,float y)
{
return(pi*x*x);
}
}
class InterfaceTest
{
public static void main(String[] args)
{
Rectangle R =new Rectangle();
Circle C =new Circle();
System.out.println("Area of Rectangle :"+ R.compute(10,20));
System.out.println("Area of Circle :"+ C.compute(10,0));

Prof. Shalini Puri 67


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
}
/*C:\Java\jdk1.6.0_05\bin>javac InterfaceTest.java
C:\Java\jdk1.6.0_05\bin>java InterfaceTest
Area of Rectangle :200.0
Area of Circle :314.0*/

12.4.2 Implementing Hybrid Inheritance:


class Student
{
int RollNo;
void getNumber(int n)
{
RollNo=n;
}
void putNumber()
{
System.out.println("Roll No :"+RollNo);
}
}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putMarks()
{
System.out.println("Marks obtained :");
System.out.println("Part 1 ="+part1);
System.out.println("Part 2 ="+part2);
}
}
interface Sports
{
float sportWt =6.0F;
void putWt();
}
class Result extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println("Sporst Wt ="+sportWt);

Prof. Shalini Puri 68


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
void display()
{
total=part1+part2+sportWt;
putNumber();
putMarks();
System.out.println("Total Score ="+total);
}
}
class Hybrid
{
public static void main(String[] args)
{
Result student1 = new Result();
student1.getNumber(234);
student1.getMarks(27.5F,33.05F);
student1.display();
}
}
/*C:\Java\jdk1.6.0_05\bin>javac Hybrid.java
C:\Java\jdk1.6.0_05\bin>java Hybrid
Roll No :234
Marks obtained :
Part 1 =27.5
Part 2 =33.05
Total Score =66.55*/

Prof. Shalini Puri 69


Ramrao Adik Institute of Technology F.E.Computer Programming II

13. Packages
The main feature of OOP is its ability to reuse the code already created. One way of
achieving this is by extending classes and implementing the interfaces but it creates a
limitation of reusing the classes within a program. What if we need to reuse classes from
other programs without physically copying them into the program under development?
This can be accomplished in Java by using what is known as packages a concept similar
to “class libraries” in other languages.
Packages area way of grouping a variety of classes and/or interfaces together. The
grouping is usually done according to the functionality. By organizing our classes into
packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused
2. In packages classes can be unique compared with classes in other packages. That is
two classes in two different packages can have the same name. They are anyways
referred by package name and the class name.

13.1 Defining and using your own Package:


Creating our own package involves the following steps:
1. Declaring the package at the beginning of a file using the form:
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a sub directory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created
5. Compile the file. This creates .class file in the subdirectory.
The sub directory name must match the package name exactly.
We have use the word import in order to have an access to the files present in the
package.
import packagename.*;
Access protection:
package Report;
public class Student
{
private int RollNo;

Prof. Shalini Puri 70


Ramrao Adik Institute of Technology F.E.Computer Programming II

String Name;
protected String DOB;
public String Add;
public Student(int x,String n,String d,String a)
{
RollNo=x;
Name=n;
DOB=d;
Add=a;
}
public void display()
{
System.out.println("Display called from Student :");
System.out.println("Roll No :" + RollNo);
System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
}
}
package Report;
class Test extends Student
{
int m1,m2;
Test(int x,String n,String d,String a,int y,int z)
{
super(x,n,d,a);
m1=y;
m2=z;
}
public void display()
{
super.display();
System.out.println("Display called from Test :");
System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
System.out.println("Marks 1 :" + m1);
System.out.println("Marks 2 :" + m2);
}
}
package SReport;
import Report.Student;
public class Sports extends Student
{
int score;
public Sports(int x,String n,String d,String a,int s)

Prof. Shalini Puri 71


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
super(x,n,d,a);
score=s;
}
public void display()
{
super.display();
System.out.println("Display called from Sports :");
//System.out.println("Roll No :" + RollNo);
//System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
System.out.println("Sports score :" +score);
}
}
package Report;
class Result extends Test
{
int total;
Result(int x,String n,String d,String a,int y,int z)
{
super(x,n,d,a,y,z);
}
public void display()
{
super.display();
System.out.println("Display called from Result :");
System.out.println("Name :" + Name);
System.out.println("Address :" + Add);
System.out.println("Marks 1 :" + m1);
System.out.println("Marks 2 :" + m2);
System.out.println("Total Marks :" + (m1+m2));
}
}
package Report;
import SReport.Sports;
class Demo
{
public static void main(String args[])
{
Result R =new Result(1,"Shalini","01/01/1975","Vashi",65,75);
R.display();
Sports s =new Sports(2,"Amar","01/01/1972","NaviMumbai",60);
S.display();
}
}

Prof. Shalini Puri 72


Ramrao Adik Institute of Technology F.E.Computer Programming II

/*C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Student.java


C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Test.java
C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Result.java
C:\Program Files\Java\jdk1.6.0_05\bin>javac SReport/Sports.java
C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Demo.java
C:\Program Files\Java\jdk1.6.0_05\bin>java Report/Demo
Display called from Student :
Roll No :1
Name :Shalini
Date of Birth :01/01/1975
Address :Vashi
Display called from Test :
Name :Shalini
Date of Birth :01/01/1975
Address :Vashi
Marks 1 :65
Marks 2 :75
Display called from Result :
Name :Shalini
Address :Vashi
Marks 1 :65
Marks 2 :75
Total Marks :140
Display called from Student :
Roll No :2
Name :Amar
Date of Birth :01/01/1972
Address :NaviMumbai
Display called from Sports :
Date of Birth :01/01/1972
Address :NaviMumbai
Sports score :60*/

13.2 Defining and using system Packages:


13.2.1 The java.lang package:
Language support classes. These are classes that Java compiler uses and therefore
they are automatically imported. They include classes for primitive type’s strings, math
functions, threads and exceptions.

13.2.2 The java.lang.Math package:


abs(int) Returns the absolute integer value of a.

Prof. Shalini Puri 73


Ramrao Adik Institute of Technology F.E.Computer Programming II

abs(long) Returns the absolute long value of a.


abs(float) Returns the absolute float value of a.
abs(double) Returns the absolute double value of a.
acos(double) Returns the arc cosine of a, in the range of 0.0 through Pi.
asin (double) Returns the arc sine of a, in the range of -Pi/2 through Pi/2.

atan(double) Returns the arc tangent of a, in the range of -Pi/2 through Pi/2.
atan2(double,do Converts rectangular coordinates (a, b) to polar (r, theta).
uble)
ceil(double) Returns the "ceiling" or smallest whole number greater than or equal
to a.
cos(double) Returns the trigonometric cosine of an angle.
exp(double) Returns the exponential number e(2.718...) raised to power of a.
floor(double) Returns the "floor" or largest whole number less than or equal to a.
log(double) Returns the natural logarithm (base e) of a.
max(int, int) Takes two int values, a and b,& returns the greater number of the two.
max(long, long) Takes two long values, a & b & returns the greater number of the two.
max(float, float) Takes two float values, a & b& returns the greater number of the two.
max(double, Takes two double values, a & b, & returns the greater number of the
double) two.
min(int, int) Takes 2 int values, a & b, & returns the smallest number of the two.
min(long, long) Takes 2 long values, a & b, and returns the smallest number of the two
min(float, float) Takes 2 float values, a &b, and returns the smallest number of the two.
min(double, Takes two double values, a and b, and returns the smallest number of
double) the two.
pow(double, Returns the number a raised to the power of b.
double)
random() Generates a random number between 0.0 and 1.0.
Random number generators are often referred to as pseudorandom
number generators because the numbers produced tend to repeat
themselves after a period of time.

Prof. Shalini Puri 74


Ramrao Adik Institute of Technology F.E.Computer Programming II

rint(double) Converts a double value into an integral value in double format


round(float) Rounds off a float value by first adding 0.5 to it and then returning the
largest integer that is less than or equal to this new value.
Rounds off a double value by first adding 0.5 to it and then returning
round(double) the largest integer that is less than or equal to this new value.
sin(double) Returns the trigonometric sine of an angle.
sqrt(double) Returns the square root of a.
tan(double) Returns the trigonometric tangent of an angle.
E The float representation of the value E.

PI The float representation of the value Pi.

13.2.3 The java.util.Vector:


Each vector tries to optimize storage management by maintaining a capacity and a
capacityIncrement. The capacity is always at least as large as the vector size; it is usually
larger because as elements are added to the vector, the vector's storage increases in
chunks the size of capacityIncrement. Setting the capacity to what you want before
inserting a large number of objects will reduce the amount of incremental reallocation.
You can safely ignore the capacity and the vector will still work correctly.
capacityIncrement The size of the increment.
elementCount The number of elements in the buffer.
Vector(int, int) Constructs an empty vector with the specified storage
capacity and the specified capacityIncrement.
Vector(int) Constructs an empty vector with the specified storage
capacity.
Vector() Constructs an empty vector.
addElement(Object) Adds the specified object as the last element of the vector.

capacity() Returns the current capacity of the vector.

copyInto(Object[]) Copies the elements of this vector into the specified array.
elementAt(int) Returns the element at the specified index

Prof. Shalini Puri 75


Ramrao Adik Institute of Technology F.E.Computer Programming II

removeAllElements() Removes all elements of the vector.


removeElement(Object) Removes the element from the vector.
removeElementAt(int) Deletes the element at the specified index.

13.2.4 The java.util.Random


Random class generates a stream of pseudo-random numbers. To create a new random
number generator, use one of the following methods:
new Random()
new Random(long seed)
The form new Random() initializes the generator to a value based on the current time.
The form new Random(long seed) seeds the random number generator with a specific
initial value; use this if an application requires a repeatable stream of pseudo-random
numbers. The random number generator uses a 48-bit seed, which is modified using a
linear congruential formula. The generator's seed can be reset with the following method:
setSeed(long seed)
To create a pseudo-random number, use one of the following functions:
Random() Creates a new random number generator.
Random(long) Creates a new random number generator using a single long seed.
nextDouble() Generates a pseudorandom uniform ally distributed double value
between 0.0 and 1.0.
nextFloat() Generates a pseudorandom uniformally distributed float value
between 0.0 and 1.0.
nextGaussian() Generates a pseudorandom Gaussian distributed double value with
mean 0.0 and standard deviation 1.0.
nextInt() Generates a pseudorandom uniformally distributed int value.
nextLong() Generate a pseudorandom uniformally distributed long value.
setSeed(long) Sets the seed of the random number generator using a single long seed.

13.2.5 java.util.hashtable,:
Hashtable class.maps keys to values. Any object can be used as a key and/or
value. To sucessfully store and retrieve objects from a hash table the object used as the

Prof. Shalini Puri 76


Ramrao Adik Institute of Technology F.E.Computer Programming II

key must implement the hashCode() and equals() methods. This example creates a
hashtable of numbers. It uses the names of the numbers as keys:
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
To retrieve a number use:
Integer n = (Integer)numbers.get("two");
if (n != null)
{
System.out.println("two = " + n);
}
Hashtable(int, float) Constructs a new, empty hashtable with the specified initial
capacity and the specified load factor.
Hashtable(int) Constructs a new, empty hashtable with the specified initial
capacity.
Hashtable() Constructs a new, empty hashtable.
clear() Clears the hash table so that it has no more elements in it.
isEmpty() Returns true if the hashtable contains no elements
put(Object, Object) Puts the specified element into the hashtable, using the specified
key.
keys() Returns an enumeration of the hashtable's keys.
rehash() Rehashes the content of the table into a bigger table.
remove(Object) Removes the element corresponding to the key.
size() Returns the number of elements contained in the hashtable.

clone() Creates a clone of the hashtable.


contains(Object) Returns true if the specified object is an element of the hashtable.
containsKey(Object) Returns true if the collection contains an element for the key.

13.2.6 The java.util.Date,:


A wrapper for a date. This class lets you manipulate dates in a system independent way.
To print today's date use:
Date d = new Date();

Prof. Shalini Puri 77


Ramrao Adik Institute of Technology F.E.Computer Programming II

System.out.println("today = " + d);


To find out what day corresponds to a particular date:
Date d = new Date(63, 0, 16); // January 16, 1963
System.out.println("Day of the week: " + d.getDay());
The date can be set and examined according to the local time zone into the year, month,
day, hour, minute and second.
Date() Creates today's date/time.
Date(int, int, int) Creates a date.
UTC(int, int, int, int, int, int) Calculates a UTC value from YMDHMS.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getHours() Returns the hour.
getMinutes() Returns the minute.
getMonth() Returns the month.
getSeconds() Returns the second.
getTime() Returns the time in milliseconds since the epoch.
getYear() Returns the year after 1900.
after(Date) Checks whether this date comes after the specified date.
before(Date) Checks whether this date comes before the specified date.
setDate(int) Sets the date
setDay(int) Sets the day of the week.
setHours(int) Sets the hours.
setMinutes(int) Sets the minutes.
setMonth(int) Sets the month.
setSeconds(int) Sets the seconds.
setTime(long) Sets the time.
setYear(int) Sets the year.

13.3 Access Specification in Java:


During Inheritance the private, public and protected access modifier behave in a different
format. The public access modifier is the least restrictive of all the access modifiers. A
public variable can be accessed within the class in which is declared or within its sub

Prof. Shalini Puri 78


Ramrao Adik Institute of Technology F.E.Computer Programming II

class. In addition a public variable is accessible from any class inside and outside the
package it is declared. If the members of a superclass are public then they are accessed
from a sub class either inside or outside a package without any difficulty. The protected
members are those members that are accessible from all the sub classes of the same
package and also from the subclasses of another package. The private access modifier is
the most restrictive of all the access modifiers. The private members are not accessible
outside their class. They cannot be accessed by their sub classes either from the current
package or from another package. Thus the private members cannot be inherited
Access Location Public Protected Default private
Same class Yes Yes Yes Yes
Sub class in same
Yes Yes Yes No
package
Other classes in
Yes No Yes No
same package
Subclass in another
Yes Yes No No
package
Non-subclass in
Yes No No No
other packages

Prof. Shalini Puri 79


Ramrao Adik Institute of Technology F.E.Computer Programming II

14. Exception Handling


The program rarely runs successfully in the first attempt. It is common to make mistakes
while developing as well as typing a program. A mistake might lead to an error causing
the program to produce unexpected results.

14.1 Why use Exception handling:


An error may produce an incorrect output or may terminate the execution of the program
abruptly or may even cause a system to crash. It is therefore important to detect and
manage properly all possible error conditions in a program so that the program will not
crash down during execution. Let us start our study with a simple example:
class Error
{
public static void main(String args[])
{
int a = 10;
int b= 5;
int c=5;
int x=a/(b-c);
System.out.println(x);
int y= a/(b+c);
System.out.println(y);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Error.java
C:\Java\jdk1.5.0_04\bin>java Error
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Error.main(Error.java:8)*/
At run time the divide by zero message is displayed and the program stops.
Errors may be classified into two categories as Compile time and Run time errors.
Compile Time Errors: All syntax errors will be detected and displayed by the Java
compiler and therefore these errors are called as compile time errors. Whenever the
compiler displays an error it will create the .class file. It is therefore necessary that we fix
the errors before we successfully compile and run the program. The most common
problems are:
 Missing semicolons
 Missing brackets in classes and methods

Prof. Shalini Puri 80


Ramrao Adik Institute of Technology F.E.Computer Programming II

 Misspelling of identifiers and keywords


 Missing double quotes in strings
 Use of undeclared variables
 Incompatible type in assignments / initialization
 Bad reference to objects
Run Time errors: A program may compile successfully creating a .class file but may not
run properly. Such programs may produce wrong results due to wrong logic or may
terminate such as stack overflow. Most common run time errors are:
 Dividing an integer by zero.
 Accessing an element that is out of bound of in an array.
 Trying to store a value into an array of an incompatible class or type.
 Passing a parameter that is not in a valid range or value for a method
 Attempting to use a negative size for an array
 Use a null object reference as a legitimate object reference to access a method or a
variable
 Converting an invalid string into a number
When such errors are encountered, Java typically generates an error message and aborts
the program.

14.2 Exceptions:
An exception is a condition that is caused by a run time error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
If the exception object is not caught and handled properly, the interpreter will
display an error message as shown in the output of program and will terminate the
program. If we want the program to continue with the execution of the remaining code,
then we should try to catch the exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This is called as exception
handling.
The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken. The

Prof. Shalini Puri 81


Ramrao Adik Institute of Technology F.E.Computer Programming II

mechanism suggests incorporation of a separate error handling code that performs the
following tasks:
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throws the exception)
3. Receive the error information (Catch the exception)
4. Take the corrective actions (Handle the exception)
The error handling code basically consists of two segments one to detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions. While
writing programs we must always be on the look out for places in the program where an
exception could be generated. Some common exceptions that we must watch out for
catching are listed in the table:
Exception type Cause of Exception
ArithmeticException Caused by Math errors such as divide by zero
ArrayIndexOutOfBoundException Caused by error indexes
ArrayStoreException Caused when a program tries to store wrong data in
array
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures such as inability to
read from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when conversion between strings and
number fails
OutOfMemoryException Caused when there is not enough memory to
allocate a new object
SecurityException Caused when an applet tries to perform action not
allowed by browser’s security
StackOverflowException Caused when the system runs out of stack space
StringIndexOutOfBoundsException Caused when a program attempts to access a
nonexistent character position in a string

Syntax of Exception Handling code:

Prof. Shalini Puri 82


Ramrao Adik Institute of Technology F.E.Computer Programming II

try Block
{
Statement that causes the exception
}
Catch Block
{
Statement that handles the exception
}
Java uses a keyword try to prefer a block of code that is likely to cause an error
condition and “throw” an exception. A catch block defined by the keyword catch
“catches” the exception “thrown” by the try block and handles it appropriately. The catch
block is added after the try block.

14.2.1 Arithmetic Exception:


class Error
{
public static void main(String args[])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y=a/(b+c);
System.out.println("y = " +y);
}
}
/*Divide by zero
y = 1*/

14.2.2 Catching Invalid Command line arguments:


class ClineInput
{
public static void main(String args[])
{
int invalid=0,count=0,num;

Prof. Shalini Puri 83


Ramrao Adik Institute of Technology F.E.Computer Programming II

for(int i=0;i<args.length;i++)
{
try
{
num=Integer.parseInt(args[i]);
}
catch(NumberFormatException e)
{
invalid++;
System.out.println("Invalid arguments :"+args[i]);
continue;
}
count++;
}
System.out.println("Valid arguments :"+count);
System.out.println("InValid arguments :"+invalid);
}
}

/*C:\Java\jdk1.5.0_04\bin>javac ClineInput.java
C:\Java\jdk1.5.0_04\bin>java ClineInput Java 10 17.5 18 you
Invalid arguments :Java
Invalid arguments :17.5
Invalid arguments :you
Valid arguments :2
InValid arguments :3*/

14.2.3 Catch multiple exceptions


It is possible to have more than one catch statement in the catch block as illustrated
below:
…………………
…………………
try
{
statement;
}
catch(ExceptionType1 e)
{
statement;
}
catch(ExceptionType2 e)
{
statement;
}
catch(ExceptionType3 e)

Prof. Shalini Puri 84


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
statement;
}
…………………
………………..
When an exception in a try block is generated, Java treats the multiple catch
statements like cases in switch statement. The first statement whose parameter
matches with the exception object will be executed and the remaining statements will
be skipped.
class Error
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division byb zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Datatype");
}
int y=a[1]/a[0];
System.out.println("y= "+y);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Error.java
C:\Java\jdk1.5.0_04\bin>java Error
Array Index Error
y= 2*/

14.2.4 The finally keyword


Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements. finally block can be

Prof. Shalini Puri 85


Ramrao Adik Institute of Technology F.E.Computer Programming II

used to handle any exception generated within a try block. It may be added immediately
after the try block or after the last catch block shown as follows:
try
{
……………
}
catch(………..)
{
……………..
}
catch(………..)
{
……………..
}
finally
{
……………..
}

14.2.5 Throwing our Exception:


There may be times when we would like to throw our own exceptions. We can do this by
using the keyword throw as follows:
throw new Throwable_subclass
example:
throw new ArithmeticException( ) ;
throw new NumberFormatException( ) ;

Prof. Shalini Puri 86


Ramrao Adik Institute of Technology F.E.Computer Programming II

15. Multithreading
Multithreading is a conceptual programming paradigm where a program is divided into
two or more subprograms (processes) which can be implemented at the same time in
parallel. For example one subprogram can display an animation on the screen while
another may build the next animation to be displayed. This is something similar to
dividing a task into subtasks and assigning them to different people for execution
independently and simultaneously.
Multithreading is a powerful programming tool that makes java distinctly different from
its fellow programming languages. Multithreading is useful in a number of ways. It
enables programmers to do multiple things at one time. They can divide a long program
(containing operations that are conceptually concurrent) into threads and execute them in
parallel. For example we can send tasks such as printing into the background and
continue to perform some other task in the foreground. This approach would considerably
improve the speed of other programs.

15.1 What are Threads and why use them?


It is increasingly common for computers to have more than one processing unit and such
computers can literally work on several tasks simultaneously. It is likely that from now
on most of the increase in computing power will come from adding additional processors
to computers rather than increasing the speed of individual processors.
To use the full power of these multiprocessing computers a programmer must do parallel
programming which means writing a program as a set of several tasks that can be
executed simultaneously computers. Even on a single processor computer parallel
programming techniques can be tackled most naturally by breaking the solution into a set
of simultaneous tasks that cooperate to solve the problem use.
In java a single thread is called a thread. The term “thread” refers to a “thread of control”
or “thread of execution” meaning a sequence of instructions that are executed one after
another the thread extends through time, connecting each instruction to the next. In a
multithreaded program there can be many threads of control weaving through time in
parallel and forming the complete fabric of the program. Every Java program has at least
one thread when the Java virtual machine runs your program it creates a thread that is

Prof. Shalini Puri 87


Ramrao Adik Institute of Technology F.E.Computer Programming II

responsible for executing the main routine of the program. The main thread can in turn
create other threads that can continue even after the main thread has terminated.
The above figure illustrates four threads one main thread and three others. The main
thread is designed to create other three threads namely A,B and C. Once initiated by the
main thread the threads A,B and C run currently and share the resources jointly. The
ability of a language to support multithreads is referred to as concurrency. Since threads
in java subprograms of a main application program and share the same memory space
they are known as lightweight threads or light weighted processes.

15.2 Creating and Running a Thread:


Java’s multithreading system is built upon the Thread class, and its companion
interface, Runnable. A new thread can be treated in two ways:
1. Program can implement the java.lang.Runnable interface.
2. Program can either extend java.lang.Thread class.

15.2.1 Creating Multiple Thread:


We can make our class runnable as a thread by extending the class java.lang.Thread.
This gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method that is responsible for executing the sequence of
code that the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
Declaring the class:
The Thread class can be extended as follows:
class MyThread extends Thread
{
………………..
………………..
}
Now we have a new type of thread MyThread.
Implementing the run( ) method:
The run( ) method has been inherited by the class MyThread. We have to
override this method in order to implement the code to be executed by our thread. The
basic implementation of run( ) will look like this:

Prof. Shalini Puri 88


Ramrao Adik Institute of Technology F.E.Computer Programming II

public void run( )


{
……………………..
……………………….
}
When we start the new thread, Java calls the thread’s run() method, so it is the run()
where all the action takes place.
Starting New Thread:
To actually create and run an instance of our thread class, we must write the following:
MyThread athread = new MyThread( );
athread.start( );
The first line instantiates a new object of class MyThread. Note that this statement just
creates the object. The thread is in a newborn state. The second line calls the start( )
method causing the thread to move into the runnable state. Then the java runtime will
schedule the thread to run by invoking its run( ) method. Now the thread is said to be in
running state. The below program illustrates an example extending the Thread class.
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Thread A : i ="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Thread B : j ="+j);
}
System.out.println("Exit from B");
}
}

Prof. Shalini Puri 89


Ramrao Adik Institute of Technology F.E.Computer Programming II

class C extends Thread


{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Thread C : k ="+k);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
/*C:\Java\jdk1.6.0_05\bin>javac ThreadTest.java
C:\Java\jdk1.6.0_05\bin>java ThreadTest
From Thread A : i =1
From Thread A : i =2
From Thread A : i =3
From Thread A : i =4
From Thread A : i =5
Exit from A
From Thread B : j =1
From Thread B : j =2
From Thread B : j =3
From Thread B : j =4
From Thread B : j =5
Exit from B
From Thread C : k =1
From Thread C : k =2
From Thread C : k =3
From Thread C : k =4
From Thread C : k =5
Exit from C*/

15.2.2 Implementing Runnable Interface:


The runnable interface defines a single method, public void run ( ) that is required for
implementing threads in our programs. The run( ) method is the entry point for the new
thread. It makes up the entire body of the thread and is the only method in which the

Prof. Shalini Puri 90


Ramrao Adik Institute of Technology F.E.Computer Programming II

thread’s behavior can be implemented. The run( ) method can call other methods use
other classes and declare variables just like the main thread can. We must perform the
steps listed below:
Step 1: Declare the class as implementing the Runnable interface.
Step 2: Implement the Run( ) method.
Step 3: Pass an object that implements the Runnable interface as a parameter to the
constructor of an object of type Thread.
Step 4: Call the thread’s start( ) method to run the thread.
When the thread’s start( ) method is called the thread will execute a call to run( ) method
in the Runnable object. Following program illustrates implementation of the above steps:
class NamedRunnable implements Runnable
{
private String Name;
NamedRunnable(String name)
{
this.Name=name;
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Greetings from "+Name);
}
System.out.println("End of Child thread");
}
}
class RunnableTest
{
public static void main(String args[])
{
NamedRunnable greetings = new NamedRunnable("Child thread");
Thread greetingsThread = new Thread(greetings);
greetingsThread.start();
for(int i=1;i<=10;i++)
{
System.out.println("Main Thread");
}
System.out.println("End of Main thread");
}
/*C:\Java\jdk1.5.0_04\bin>javac RunnableTest.java
C:\Java\jdk1.5.0_04\bin>java RunnableTest

Prof. Shalini Puri 91


Ramrao Adik Institute of Technology F.E.Computer Programming II

Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
End of Child thread
Main Thread
Main Thread
Main Thread
Main Thread
End of Main thread*/

15.3 Life Cycle of a Thread:


During the life time of a thread, there are many states it can enter. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked State
5. Dead state
A thread is always in one of these five states. It can move from one state to another via
variety of ways:
Newborn state:
When we create a thread object, the thread is born and is said to be in a newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the
following things with it:
 Schedule it for running using start( ) method.
 Kill it using stop( ) method.

Prof. Shalini Puri 92


Ramrao Adik Institute of Technology F.E.Computer Programming II

New Thread
start() New Born
stop()

Active Thread stop()


Running Runnable Dead
yield
yield() resume()
wait ( ) notify () stop( )
sleep()
suspend( )
Blocked
If scheduled it moves to the runnable state. If we attempt to use any other method at this
stage an exception will be thrown.
Scheduling a newborn thread:
NewBorn

Dead
Runnable
State
State

Runnable state: The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is the thread has joined the queue of
threads that are waiting for execution. If all the threads have equal priority then they are
given time slots for execution in round robin fashion i.e. first come first serve. The thread
relinquishes control joins the queue at the end and again waits for its turn. The process of
assigning time to threads is known as time slicing. However if we want a thread to
relinquish control to another thread of equal priority before its turn comes we can do so
by using the yield( ) method.

Prof. Shalini Puri 93


Ramrao Adik Institute of Technology F.E.Computer Programming II

Running state: Running means that the processor has given its time to the thread for
execution. The thread until it relinquishes control on its own or it is preempted by a
higher priority thread. A running thread may relinquish its control in one of the following
situations.
1. It has been suspended using suspend ( ) method. A suspended thread can be revived
by using the resume ( ) method. This approach is useful when we want to suspend a
thread for some time due to certain reason but do not want to kill it.
2. It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep (time) where time is in milliseconds. This means that the
thread is out of the queue during this time period. The thread re-enters the runnable
state as soon as this period is elapsed.
3. It has been made to wait until some event occurs. This is done using the wait ( )
method. The thread can be scheduled to run again using the notify () method.
Blocked state: A thread is said to be blocked when it is prevented from entering into the
runnable state subsequently the running state. This happens when the thread is
suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread
is considered “not runnable” but not dead and therefore fully qualified to run again.
Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed executing its run() method. It is natural death. However we can kill it by
sending the stop message to it at any state thus causing a premature death to it. A thread
can be killed as soon it is born or while it is running or even when it is in “not runnable”
condition

15.4 Thread Priority:


In Java each thread is assigned a priority which affects the order in which it is scheduled
for running. The threads that we have discussed so far are of the same priority. The
threads of the same priority are given equal treatment by the Java scheduler and therefore
they share the processor on first come first serve basis. Java permits us to se priority of a
thread using the setPriority( ) method as follows:

Prof. Shalini Puri 94


Ramrao Adik Institute of Technology F.E.Computer Programming II

ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10. note
that the default priority is NORM_PRIORITY. Most user level processes should use
NORM_PRIORITY. Background processes such as network and I/O and screen
repainting should use a value MIN_PRIORITY. By assigning priorities to threads we can
ensure that we give them the attention they deserve. Whenever multiple threads are ready
for execution the Java stream chooses the highest priority thread and executes it. The use
of priority threads can be explained

15.5 Synchronization:
We have seen threads that use their own data and methods provided inside their run( )
methods. What happens when they try to use data and methods outside themselves? On
such occasions they may compete for same resources they may lead to serious problem.
For example one thread may try to read a record from a file while another is trying to
read a record from a file while another is still writing to the same file. Depending on the
situation we may get strange results. Java enables us to overcome the problem using a
technique known as synchronization. The keyword synchronized helps us in keeping the
watch on such locations. When we declare a method synchronized, Java creates a
“monitor” and hands it over to the thread that calls the method first time. As long as the
thread holds the “monitor” and hands it over to the thread that calls the first time. As long
as the threads hold the monitor, no other thread can enter the synchronized section of the
code. A monitor is like a key and the thread that holds the key can only open the lock. It
is also possible to mark a block of code as synchronized as shown below:
synchronized (lock object)
{……………..
……………….}

Prof. Shalini Puri 95


Ramrao Adik Institute of Technology F.E.Computer Programming II

Whenever a thread has completed its work of using synchronized method (or block of
code), it will hand over the monitor to the next thread is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain control
of a resource. Due to some reason, the condition on which the waiting threads rely on to
gain control does not happen. This results in a deadlock. For example assume that the
threadA must access Method1 before it can release Method2 but the threadB cannot
release Method until it gets hold of Method2. Because they are mutually exclusive
conditions a deadlock occurs. The code below illustrates this:
Thread A
synchronized method2 ( )
{
synchronized method1( )
{
……………………
……………………..
}
}
Thread B
synchronized method1 ( )
{
synchronized method2( )
{
……………………
……………………..
}
}

Prof. Shalini Puri 96


Ramrao Adik Institute of Technology F.E.Computer Programming II

16. Graphics and Java Applets


Java programs are classified into two groups namely applications and applets. So far we
have been dealing with classes that contain a main method and run as stand alone
applications. All those programs are called java application programs. Java code can also
be executed under the control of a web browser. Code written under the control of a
browser is called as an applet.
A Java applet is an applet delivered in the form a java byte code. Java applets can run in a
web browser using java virtual machine or in Sun’s Applet Viewer a stand alone tool for
testing applets. These applets have access to a subset of the normal java network and file
I/O access. Applets can be used to provide dynamic user interfaces and a variety of
graphical effect for web pages.

16.1 Creation of Applet:


Before we try to write applet we have to make sure that java is installed properly and also
ensure that either the java interpreter or java enabled browser is available. The steps
involved in developing and testing an applet are:
1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Designing a Web page using HTML tags
4. Preparing <APPLET> tag
5. Incorporating <APPLET> tag into the web page
6. Creating HTML file
7. Testing the applet code

16.1.1 Building an applet code (.java file):


It is essential that our applet code uses the services of two classes namely Applets and
Graphics from the Java class library. The Applet class which is contained in the
java.applet package provides life and behavior to the applet through its methods such as
init( ), start ( ) and paint ( ). Unlike with applications where Java calls the main( )
method directly to initiate the execution of the program when an applet is loaded, Java
automatically calls a series of Applet class methods for staring , running and stopping
the applet code. The applet class therefore maintains the lifecycle of an applet.

Prof. Shalini Puri 97


Ramrao Adik Institute of Technology F.E.Computer Programming II

The paint( ) method of the Applet class when it is called actually displays the result of
the applet code on the screen. The output may be text, graphics or sound. The paint ( )
method which requires a Graphics object as argument, is defined as follows:
public void paint (Graphics g)
This requires that the applet code imports the java.awt package that contains the
Graphics class. All output operations of an applet are performed is using the methods
defined in the Graphics class. The general form of applet code is shown below:
import java.awt.*;
import java.applet.*;
………………
public class appletclassname extends Applet
{
…………………………
………………………
public void paint(Graphics g)
{
………………………..
……………………..
}
……………………….
}
The appletclassname is the main class for the applet. When the applet is loaded, Java
creates an instance of this class and the n series of Applet class methods are called on
that instance to execute the code. The program shows a simple Hello.java applet.
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Java",10,100);
}
}

<HTML>
<APPLET
CODE ="HelloJava.class"
WIDTH = 400
HEIGHT = 200>
</APPLET>
</HTML>

Prof. Shalini Puri 98


Ramrao Adik Institute of Technology F.E.Computer Programming II

The applet contains only one executable statement:


g.drawString("Hello Java",10,100); hich when executed draws the string
Hello Java at the position 10,00 (pixels) of the applet’s reserved space.

16.2 Applet Life Cycle:


Every Java applet inherits a set of default behaviors from the Applet class. As a result
when an applet is loaded, it undergoes a series of changes in its state as shown in figure.
The applet states include:
 Born or initialization state
 Running state
 Idle state
 Dead or Destroyed state

Born Initialization

start()
Running

stop() Idle stopped


paint()
destroy()

Destroyed End
Dead

Exit of Browser
Initialization state:
Applet enters the initialization state when it is first loaded. This is achieved by calling the
init( ) method of Applet class. The applet is born. At this stage, we may do the following
if required.
 Create objects needed by the applet
 Set up initial values
 Load images or fonts
 Set up colors

Prof. Shalini Puri 99


Ramrao Adik Institute of Technology F.E.Computer Programming II

The initialization occurs only once in the applet’s life. To provide any of the behaviors
mentioned above, we must override the init( ) method:
public void init( )
{
……………….
……………….
}
Running state:
Applet enters the running state when system calls the start( ) method of Applet class.
This occurs automatically after the applet is initialized. Starting can also occur if the
applet is already in “stopped” (idle) state. For ex: we may leave the web page containing
the applet temporarily to another page and return back to the page. This again starts the
applet running. Note that unlike init( ) method, the start ( ) method may be called more
than once. We may override the start() method to create a thread to control the applet.
public void start( )
{
……………….
……………….
}
Idle or Stopped State:
An applet becomes idle when it is stopped from running. Stopping occurs automatically
when we leave the page containing the currently running applet. We can also do so by
calling the stop( ) method explicitly. If we use a thread to run the applet then we must use
stop( ) method to terminate the thread. We can achieve this by overriding stop( ) method
public void stop( )
{
……………….
……………….
}
Dead state:
An applet is said to be dead when it is removed from memory. This occurs automatically
by invoking the destroy() method when we quit the browser. Like initialization
destroying stage occurs once in the applet’s life cycle. If the applet has created any
resources like threads we may override the destroy() method to clean up these resources.
public void destroy( )
{
……………….

Prof. Shalini Puri 100


Ramrao Adik Institute of Technology F.E.Computer Programming II

……………….
}
Display State:
Applet moves to display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The
paint() is called to accomplish this task. Almost every applet will have a paint() method.
Like other methods in the life cycle the default version of paint() method does
absolutely nothing. We must therefore override this method if we want anything to be
displayed on the screen.
public void paint( )
{
……………….
……………….
}

16.3 Using graphic methods in Applet:


The Graphics class:
clearRect() Erases a rectangular area of the canvas
copyArea() Copies a rectangular area of the canvas to another area
drawArc() Draw a hollow arc
drawLine() Draw a straight line
drawOval() Draw a hollow Oval
drawPolygon() Draw a hollow polygon

drawRect() Draw a hollow rectangle


drawRoundRect() Draw a hollow rectangle with rounded corners
drawString() Displays a string
fillArc() Draws a filled arc
fillOval() Draws a filled oval
fillPolygon() Draws a filled polygon
fillRect() Draws a filled rectangle
fillRoundRect() Draws a filled rectangle with rounded corners
getColor() Retrieves the current drawing color
getFont() Retrieves the currently used font

Prof. Shalini Puri 101


Ramrao Adik Institute of Technology F.E.Computer Programming II

getfontMetrics() Retrieves information about the current font


setColor() Sets the drawing color
setFont() Sets the font

Lines and Rectangles:


The simplest shape we ca draw with the Graphics class is a line. The drawLine()
method takes two pair of coordinates (x,y1) and (x2,y2) as arguments and draws a line
between them. For example the following statement draws a straight line from the
coordinate point (10,10) to (50,50):
g.drawLine(10,10,50,50);
The g is the Graphics object passed to paint() method.
We can draw a rectangle using the drawRect() method. This method takes four
arguments. The first two represent the x and y coordinates of the top corner of the
rectangle and the remaining two represent the width and height of the rectangle. For
example the statement
g.drawRect(10.60,40,30);
The drawRect () method draws only the outline of the box.
We can draw a solid box by using the method fillRect(). This also takes four
parameters corresponding to the starting point the width and height of the rectangle. For
example the statement:
g.fillRect(60,10,30,80);
We can also draw rounded rectangles using the methods drawRoundRect() and
fillRoundRect(). These two methods are similar to drawRect() and fillRect() except that
they take two extra arguments representing the width and height of the angle of corners.
These extra parameters indicate how much of corners will be rounded. Example:
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(10,100,80,50,0,10);
Circles and Ellipses:
The Graphics class does not have any method for circles or ellipses. However the
drawOval() method can be used to draw a circle or an ellipse. The drawOval() method
takes four arguments the first two represent the top left corner of the imaginary rectangle

Prof. Shalini Puri 102


Ramrao Adik Institute of Technology F.E.Computer Programming II

and the other two represent the width and height of the oval itself. If the width and height
is the same then the oval turns into a circle. The drawOval() method draws the outline of
the Oval and the fillOval() method draws a solid oval.
g.drawOval(20,20,200,120);
g.fillOval(70,30,100,100);
Drawing arcs:
An arc is part of an Oval. The drawArc() designed to draw arcs takes six
arguments. The first four are the same as the arguments of the oval and the next two
arguments specify the starting angle of the arc and the number of degrees around the arc.
In drawing arcs, Java actually formulates the arc as an Oval and then draws only part of it
as dictated by the last two arguments. Java considers the three O’ clock position as zero
degree position and degrees increase in anti-clockwise direction. So to draw an arc
from12.00 O’clock position to 6.00 o’clock position, the starting angle would be 90 and
the sweep angle would be 180. We can also draw an arc in backward direction by
specifying the sweep angle as negative. We can use fillArc() method to fill the arc.

Prof. Shalini Puri 103


Ramrao Adik Institute of Technology F.E.Computer Programming II

17. Solved University Question Papers:


17.1 May-June 2008:
1. a) Explain applets in Java in terms of the following:
 Creating an executable applet
 Designing a web page that references an applet
 Adding applets to an HTML file
 Running the applet
 Explaining the basic applet life cycle: init(), start(),stop() and destroy()
Ans : Already explained in 16.1 and 16.2.
b) Write object oriented programs in Java to exemplify different types of visibility
modifiers such as: Public, Protected, Private and Default.
Ans: Already explained in 13.3.
2. a) Write an object oriented program in java that uses Euclid’s algorithm to display
greatest common divisor of two integers. The greatest common divisor of two
numbers is the largest number that divides both the numbers. Here is how the
algorithm works:
 Find the remainder after dividing the larger number by smaller number using the
modulus operator
 Change the larger number to the smaller number and change the smaller number
to the remainder from step i)
 Keep doing this until the remainder is zero.
Incorporate member functions for data input and displaying the result, default
constructor and constructor with two parameters. Also create objects to reference the
member functions.
Ans: class great
{ int num1,num2;
void getdata(int x,int y)
{
num1=x;
num2=y;
}
int gcd()
{

Prof. Shalini Puri 104


Ramrao Adik Institute of Technology F.E.Computer Programming II

if(num1<num2)
{
int temp=num1;
num1=num2;
num2=temp;
}
int r=1;
while(r>0)
{
r=num1%num2;
num1=num2;
num2=r;
}
return(num1);
}
void putdata()
{
System.out.println(num1+ " " +num2+ " "+gcd());
}
}
class GCD
{
public static void main(String args[])
{
great g =new great();
g.getdata(35,25);
g.putdata();
}
}
/*E:\Java\jdk1.5.0_16\bin>javac GCD.java
E:\Java\jdk1.5.0_16\bin>java GCD
35 25 5*/

b) Develop a Java program that determines the number of days in a given semester.
Input data to the program consists of the year, month and day information of the first and
last days of a semester. The program should accept the date information as a single string
instead of accepting the year, month and day information separately. The input string
must be in MM/DD/YYYY.
Ans: import java.util.Calendar;
class Demo
{
public static void main(String args[])
{

Prof. Shalini Puri 105


Ramrao Adik Institute of Technology F.E.Computer Programming II

System.out.println("Enter the starting date in MM/DD/YYYY:");


String S,SA;
S=args[0];
String S1 = S.substring(0,2);
String S2 = S.substring(3,5);
String S3 = S.substring(6,10);
int MM1=Integer.parseInt(S1);
int DD1=Integer.parseInt(S2);
int YY1=Integer.parseInt(S3);
SA=args[1];
S1 = SA.substring(0,2);
S2 = SA.substring(3,5);
S3 = SA.substring(6,10);
int MM2=Integer.parseInt(S1);
int DD2=Integer.parseInt(S2);
int YY2=Integer.parseInt(S3);
Calendar C1 =Calendar.getInstance();
Calendar C2 =Calendar.getInstance();
C1.set(YY1,MM1,DD1);
C2.set(YY2,MM2,DD2);
System.out.println("No.of days in Semester :"+(C2.getTimeInMillis()-
C1.getTimeInMillis())/(24*60*60*1000));
}
}
/*C:\Java\jdk1.5.0_17\bin>java Demo 01/19/2009 04/30/2009
Enter the starting date in MM/DD/YYYY:
1 19 2009
4 30 2009
No.of days in Semester :100*/

3. a) Write a Java program to compute the distance S fallen by an object in freefall. The
formula is : S=S0+V0*t+1/2*a*t2
Ans: class Distance
{
public static void main(String args[])
{
int S0=Integer.parseInt(args[0]);
int V0=Integer.parseInt(args[1]);
int a=Integer.parseInt(args[2]);
int i=0,t;
for(t=5;t<=100;i++)
{
System.out.println();
System.out.print("S"+i+":");
S0=S0+V0+(1/2)*a*(t*t);

Prof. Shalini Puri 106


Ramrao Adik Institute of Technology F.E.Computer Programming II

System.out.print(S0);
t=t+5;
}
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Distance.java
C:\Java\jdk1.5.0_17\bin>java Distance 7 5 6
S0:12 S1:17 S2:22 S3:27 S4:32 S5:37
S6:42 S7:47 S8:52 S9:57 S10:62 S11:67
S12:72 S13:77 S14:82 S15:87 S16:92 S17:97
S18:102 S19:107 */
b) Write an object oriented program to arrange names of students in descending order of
their total marks. Input data consists of student details such as name, Id no and marks
obtained in Mathematics, Physics and Chemistry. Use the concept of array of objects.
Ans: import java.io.*;
class Student
{
int RollNo;
String Name;
float maths,physics,chem,marks;
void get(int a,String n,float m,float p,float c)
{
RollNo=a;
Name=n;
physics=p;
maths=m;
chem=c;
marks=physics+chem+maths;
}
void put()
{
System.out.println(RollNo+ " "+Name+ " "+marks);
}
}
class StudDetail
{
public static void main(String args[])throws IOException
{
Student s[]=new Student[5];
Student temp=new Student();
BufferedReader obj =new BufferedReader(new InputStreamReader(System.in));
String str;
int x; float fp,fc,fm;
int i,j;
for(i=0;i<3;i++)

Prof. Shalini Puri 107


Ramrao Adik Institute of Technology F.E.Computer Programming II

{
s[i]=new Student();
}
for(i=0;i<3;i++)
{
System.out.println("Enter Rollno :");
x=Integer.parseInt(obj.readLine());
System.out.println("Enter Name :");
str=obj.readLine();
System.out.println("Enter Physics :");
fp=Float.parseFloat(obj.readLine());
System.out.println("Enter Chemistry :");
fc=Float.parseFloat(obj.readLine());
System.out.println("Enter Maths :");
fm=Float.parseFloat(obj.readLine());
s[i].get(x,str,fp,fc,fm);
}
System.out.println("Student Details:");
for(i=0;i<3;i++)
{
s[i].put();
}
System.out.println("Student Details in the descending order of marks:");
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if(s[i].marks<s[j].marks)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
for(i=0;i<3;i++)
{
s[i].put();
}
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>java StudDetail
Enter Rollno :
1
Enter Name :
shalini

Prof. Shalini Puri 108


Ramrao Adik Institute of Technology F.E.Computer Programming II

Enter Physics :
45
Enter Chemistry :
46
Enter Maths :
33
Enter Rollno :
2
Enter Name :
ajay
Enter Physics :
46
Enter Chemistry :
45
Enter Maths :
44
Enter Rollno :
3
Enter Name :
abhi
Enter Physics :
45
Enter Chemistry :
49
Enter Maths :
49
Student Details:
1 shalini 124.0
2 ajay 135.0
3 abhi 143.0
Student Details in the descending order of marks:
3 abhi 143.0
2 ajay 135.0
1 shalini 124.0*/
4. With the help of a suitable Java program describe the following:
1. Overloading of functions
2. Overriding functions
3. Final methods and classes
4. Abstract methods and classes:
Ans: Abstract class is a class that has no direct instances, but whose descendants may
have direct instances. There are cases in which it is useful to define classes for which the
programmer never intends to instantiate any objects; because such classes normally are

Prof. Shalini Puri 109


Ramrao Adik Institute of Technology F.E.Computer Programming II

used as base-classes in inheritance hierarchies, we call such classes as abstract classes. In


some cases, abstract classes constitute the top few levels of the hierarchy, for Example
abstract class Shape with abstract method Draw() has two derived abstract class Shape2D
& Shape3D inherits the method Draw() & also do not provide any implementation for it.
Now we have normal classes Rectangle, Square & Circle inherits from Shape2D, and
another group of classes Sphere, Cylinder & Cube inherits from Shape3D. All classes at
the bottom of the hierarchy must override the abstract method Draw().
public abstract class Shape
{
//...Class implementation

public abstract void Draw(int x, int y)


{
//this method mustn't be implemented here.
//If we do implement it, the result is a Syntax Error.
}
}
public abstract class Shape2D : Shape
{
//...Class implementation
//...you do not have to implement the the method Draw(int x, int y)
}
public class Circle : Shape2D
{
//here we should provide an implemetation for Draw(int x, int y)
public override void Draw(int x, int y)
{
//must do some work here
}
}
5. Finalize() method
5. a) Write a detailed note on exception handling in Java in terms of the following:
 Try-catch,
 The finally keyword,
 Catch multiple exceptions,
 The throws keyword throwing exception
Ans: Already explained in Section 14.2.
b) With the help of a suitable program, explain multithreaded programming in terms of
the following:

Prof. Shalini Puri 110


Ramrao Adik Institute of Technology F.E.Computer Programming II

 Creating threads and extending the thread class.


 Stopping and blocking a thread
 Define lifecycle of a thread
Ans: Already explained in Section 15.1, 15.2, 15.3.
6. interface Matrix
{
final static int M=5, N=5;
void readMatrix()
void displayMatrix();
void addMatrix();
void multMatrix();
void transposeMatrix();
}
Implementing the preceding interface by using suitable Java class programs
Ans: interface Matrix
{
final static int M=5, N=5;
public void readMatrix();
public void displayMatrix();
public void addMatrix(int x[][]);
public void multMatrix(int x[][]);
public void transposeMatrix();
}

class abc implements Matrix


{
int x[][]=new int[3][3];
public void readMatrix()
{
int k=1;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
x[i][j]=k;
k++;
}
}
}
public void displayMatrix()
{
System.out.println("Displaying Matrix :");
for(int i=0;i<3;i++)
{

Prof. Shalini Puri 111


Ramrao Adik Institute of Technology F.E.Computer Programming II

for(int j=0;j<3;j++)
{
System.out.print(x[i][j]+ " ");
}
System.out.println();
}
}
public void addMatrix(int y[][])
{
int z[][]= new int[3][3];
System.out.println("Displaying Addition Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
z[i][j]=x[i][j]+y[i][j];
System.out.print(z[i][j]+ " ");
}
System.out.println();
}
}
public void multMatrix(int y[][])
{
int z[][]= new int[3][3];
System.out.println("Displaying Multiplicated Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(int k=0;k<3;k++)
{
z[i][j]+=x[i][k]+y[k][j];
}
System.out.print(z[i][j]+ " ");
}
System.out.println();
}
}
public void transposeMatrix()
{
System.out.println("Displaying Transposed Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(x[j][i]+ " ");

Prof. Shalini Puri 112


Ramrao Adik Institute of Technology F.E.Computer Programming II

}
System.out.println();
}
}
}
class abc1
{
public static void main(String args[])
{
abc a =new abc();
a.readMatrix();
a.displayMatrix();
a.transposeMatrix();
int k=1;
int z[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
z[i][j]=k;
k++;
}
}
a.addMatrix(z);
a.multMatrix(z);
}
}
/*E:\Java\jdk1.5.0_16\bin>javac abc1.java
E:\Java\jdk1.5.0_16\bin>java abc1
Displaying Matrix :
123
456
789
Displaying Transposed Matrix :
147
258
369
Displaying Addition Matrix :
246
8 10 12
14 16 18
Displaying Multiplicated Matrix :
18 21 24
27 30 33
36 39 42*/

Prof. Shalini Puri 113


Ramrao Adik Institute of Technology F.E.Computer Programming II

7. Write notes on the following with the help of suitable program segments in Java:
 Vectors: Already explained in Section 10.5.
 Strings: Already explained in Section 10-.1 and 10.2.
 Packages: Already explained in Section 13.1 and 13.2.
 Interfaces: Already explained in Section 12.4.

17.2 Dec-2008
1. a) Explain life cycle of a thread.
Ans: Already explained in Section 12.4.
b) Write a program in java to find nCr and nPr.
Ans: class PComb
{
static int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
int r=Integer.parseInt(args[1]);
int P,C;
P=fact(n)/fact(n-r);
C=fact(n)/fact(r)*fact(n-r);
System.out.println("P ="+P);
System.out.println("C ="+C);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac PComb.java
C:\Java\jdk1.5.0_17\bin>java PComb 7 5
P =2520
C =84*/
c) Explain JVM in brief.
Ans: The JVM stands for Java Virtual Machine. An abstract computing machine, or
virtual machine, JVM is a platform-independent execution environment that converts
Java byte code into machine language and executes it. Most programming languages
compile source code directly into machine code that is designed to run on a specific

Prof. Shalini Puri 114


Ramrao Adik Institute of Technology F.E.Computer Programming II

microprocessor architecture or operating system, such as Windows or UNIX. A JVM


machine within a machine mimics a real Java processor, enabling Java bytecode to be
executed as actions or operating system calls on any processor regardless of the operating
system. For example, establishing a socket connection from a workstation to a remote
machine involves an operating system call. Since different operating systems handle
sockets in different ways, the JVM translates the programming code so that the two
machines that may be on different platforms are able to connect.
d) Write a program to demonstrate the sum of series for a given value of n.
1+1/2+1/3+………..+1/n
Ans: class series
{
public static void main(String args[])
{
float n=Float.parseFloat(args[0]);
float i;
float sum=0.0F;
for(i=1.0F;i<=n;i++)
{
sum+=1/i;
}
System.out.println("Series ="+sum);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac series.java
C:\Java\jdk1.5.0_17\bin>java series 7
Series =2.5928574*/
2. a) Compare and contrast overriding and overloading method with examples
Ans : Already explained in 12.3 Section and calling different body of the function by
different names is function overloading.
b) Write a program in Java for fitting a straight line through a set of points (xi,yi)
where i = 1…n. The straight line equation is y = mx +c and the values of m and c are
given by: m = (∑(xi,yi) - ∑(xi,) (∑yi) ) / n(∑xi,)2 -(∑yi)2 C= 1/n (∑yi - m∑xi)
3. a) Write a program to display the following menus and submenus.
b) Explain different types of Inheritance with suitable examples.
Ans : Already explained in 12.1 and 12.2 Section.
4. a) What is vector? How it is different from an array?
Ans: Already explained in 10.5 Section.

Prof. Shalini Puri 115


Ramrao Adik Institute of Technology F.E.Computer Programming II

b) What are applications of wrapper classes?


Ans: Already explained in 9 Section.
c) Assume that a bank maintains two kind of account for its customers. The saving
account provides compound interest and withdrawal facilities but no cheque book
facility. The current account provides cheque book facility but no interest. Current
account holders maintain a minimum balance and if the balance falls below this level a
service charge is imposed. Create a class account that stores customer name, account
number and type of account. From this derive the classes’ current account and saving
account to make them more specific to their requirements. Include the necessary method
in order to achieve the following tasks:
i) Accept deposit from a customer and update the balance.
ii) Display the balance
iii) Compute and deposit interest
iv) Permit withdrawal and update the balance.
v) Check for minimum balance, impose penalty, if necessary, and update the balance.
Ans :
5. a) Explain Java Exception Handling with different examples.
Ans : Already explained in 14 Section
b) Write a program to create multiple threads.
Ans : Already explained in 15.2 Section.
c) Write a program to check whether given string is palindrome or not.
Ans: class StringDemo {
public static void main(String[] args) {
String palindrome = args[0];
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] = palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new String(charArray);

Prof. Shalini Puri 116


Ramrao Adik Institute of Technology F.E.Computer Programming II

if(palindrome.equals(reversePalindrome))
System.out.println("palindrome");
else
System.out.println("not a palindrome");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac StringDemo.java
C:\Java\jdk1.5.0_17\bin>java StringDemo MADAM
palindrome
C:\Program Files\Java\jdk1.5.0_17\bin>java StringDemo MADAMA
not a palindrome*/

6. a) How do you add a class or an interface to a package? Explain with examples?


Ans : Already explained in 13.1 Section.
b) Will the code compile? If not, why? If yes, write output.
i) import circle
class Import Class
{
public static void main(String args[])
{
Circle.NewCircle nc =new circle.NewCircle();
System.out.println(“Hello World”);
}
}
Ans: The program does not compile. It gives the following errors.
C:\Java\jdk1.5.0_17\bin>javac "Import Class.java"
Import Class.java:1: '{' expected
class Import Class
^
Import Class.java:9: '}' expected
^
2 errors
C:\java\jdk1.5.0_17\bin>javac "Import Class.java"
Import Class.java:5: package Circle does not exist
Circle.NewCircle nc =new circle.NewCircle();
^
Import Class.java:5: package circle does not exist
Circle.NewCircle nc =new circle.NewCircle();
^
2 errors
ii) int m = 10;
int n = 7;
while(m%n>=0)
{

Prof. Shalini Puri 117


Ramrao Adik Institute of Technology F.E.Computer Programming II

m=m+1;
n=n+2;
}
Ans: The program will compile but will get into an infinite state.

c) Explain Type Conversion and Type Casting in Java with examples.


Ans : Type Casting refers to changing an entity of one data type into another. This is
important for the type conversion in developing any application. If you will store an int
value into a byte variable directly, this will be illegal operation. For storing your
calculated int value in a byte variable you will have to change the type of resultant data
which has to be stored. In this example we will see that how to convert the data type by
using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t
which is Boolean type variable is true then value of c which is the char type variable will
be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode
value. But in this line c = (char)(t?'1':'0'); 1 is already given as a character which will be
stored as it is in the char type variable c.
c = (char)(t?'1':'0');
System.out.println("Value of c after conversion : " + c);
class Casting
{
public static void main(String args[])
{
float sum;
int i;
sum=0.0F;
for(i=1;i<=10;i++)
{
sum=sum+1/(float)i;
System.out.print(" i = "+i);
System.out.println(" sum = "+sum);
}
}
}
/* i = 1 sum = 1.0
i = 2 sum = 1.5
i = 3 sum = 1.8333334
i = 4 sum = 2.0833335
i = 5 sum = 2.2833335
i = 6 sum = 2.4500003
i = 7 sum = 2.5928574

Prof. Shalini Puri 118


Ramrao Adik Institute of Technology F.E.Computer Programming II

i = 8 sum = 2.7178574
i = 9 sum = 2.8289685
i = 10 sum = 2.9289684*/

7. Write short notes on (Any four):-


a) HTML Applet tags
b) Parameter passing Applets
c) Abstract Methods and classes: Already explained in 4.4 of May 2008.
d) Synchronization: Already explained in 15.5 Section.
e) String Methods: Already explained in 10.2 Section.

Prof. Shalini Puri 119

You might also like