48210796 cp 2 notes java mumbai university

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

Upload: abhishek-gaikwad

Post on 29-Nov-2014

60 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 1

Computer

Programming2

For F.E All

Branches By

Shalini Puri

Page 2: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 2

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,

Page 3: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 3

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

Page 4: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 4

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

Page 5: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 5

INDEX

1. Introduction to Java ................................................................................................. 7

1.1 Why is java popular for the Internet ................................................................... 71.2 Features of Java: ................................................................................................. 71.3 How Java program runs ...................................................................................... 9

2. Object Orientation .................................................................................................. 11

2.1 Features of Object Oriented Language: ............................................................ 113. Java Language Basics ............................................................................................. 13

3.1 Introduction:...................................................................................................... 133.2 Basic Building Blocks: ..................................................................................... 13

4. Control Structures .................................................................................................. 20

4.1 Simple If statement: .......................................................................................... 204.2 If-Else Statement:.............................................................................................. 204.3 Switch-Case Statement: .................................................................................... 21

5. Loops ........................................................................................................................ 23

5.1 For Loop: .......................................................................................................... 235.2 While Loop: ...................................................................................................... 245.3 Do-While Loop: ................................................................................................ 255.4 Break and Continue Statement: ........................................................................ 255.5 Exercise:............................................................................................................ 27

6. Functions.................................................................................................................. 28

6.1 Methods in Java: ............................................................................................... 286.2 Recursive Functions:......................................................................................... 286.3 Exercise:............................................................................................................ 29

7. Arrays....................................................................................................................... 32

7.1 Creating an Array:............................................................................................. 327.2 Array Index Checking:...................................................................................... 327.3 SystemArraycopy():.......................................................................................... 337.4 Multidimensional Arrays: ................................................................................. 347.5 Exercise:............................................................................................................ 34

8. Introduction Classes: .............................................................................................. 41

8.1 General form of a Class: ................................................................................... 418.2 Declaring and Creating Objects:....................................................................... 418.3 Accessing Members:......................................................................................... 428.4 Introducing Methods:........................................................................................ 428.5 Constructors: ..................................................................................................... 448.6 Array of Objects:............................................................................................... 458.7 Static Variables and Static Methods: ................................................................ 46

9. Wrapper Classes ..................................................................................................... 48

9.1 Introduction:...................................................................................................... 489.2 Class Integer: .................................................................................................... 48

Page 6: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 6

9.3 Class Float:........................................................................................................ 489.4 Class Double: .................................................................................................... 499.5 Class Boolean: .................................................................................................. 499.6 Class Character: ................................................................................................ 50

10. Strings .................................................................................................................. 51

10.1 Declaring and Constructing a String:................................................................ 5110.2 Methods of Strings:........................................................................................... 5110.3 Sorting Strings: ................................................................................................. 5310.4 Methods valueOf() and toString():.................................................................... 5310.5 Vector:............................................................................................................... 54

11. Simple Input/Output........................................................................................... 56

11.1 Reading Character fron Console Input: ............................................................ 5611.2 Reading Strings:................................................................................................ 57

12. Inheritance........................................................................................................... 59

12.1 Types of Inheritance: ........................................................................................ 5912.2 Multilevel Inheritance:...................................................................................... 6312.3 Method Overriding: .......................................................................................... 6612.4 Interface: ........................................................................................................... 66

13. Packages............................................................................................................... 70

13.1 Defining and using your own Package: ............................................................ 7013.2 Defining and using system Packages:............................................................... 7313.3 Access Specification in Java:............................................................................ 78

14. Exception Handling ............................................................................................ 80

14.1 Why use Exception handling: ........................................................................... 8014.2 Exceptions:........................................................................................................ 81

15. Multithreading .................................................................................................... 87

15.1 What are Threads and why use them? .............................................................. 8715.2 Creating and Running a Thread: ....................................................................... 8815.3 Life Cycle of a Thread: ..................................................................................... 9215.4 Thread Priority:................................................................................................. 9415.5 Synchronization: ............................................................................................... 95

16. Graphics and Java Applets ................................................................................ 97

16.1 Creation of Applet: ........................................................................................... 9716.2 Applet Life Cycle:............................................................................................. 9916.3 Using graphic methods in Applet: .................................................................. 101

17. Solved University Question Papers: ................................................................ 104

17.1 May-June 2008: .............................................................................................. 10417.2 Dec-2008......................................................................................................... 114

Page 7: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 7

1. Introduction to JavaJava 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 InternetJava 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).

Page 8: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 8

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

Page 9: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 9

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

Page 10: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 10

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:

Running a Java Program:

Source Code

Java Compiler

JavaByteCode

Java ByteCode

Computer RunningVirtual Machine

JavaByteCode

Page 11: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 11

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

Page 12: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 12

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.

Page 13: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 13

3. Java Language BasicsThe 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.

Page 14: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 14

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.

Page 15: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 15

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 =35a-b =15

Page 16: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 16

a*b =250a/b =2a%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

Page 17: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 17

>= 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 =25b =10c =67a < b =falsea > b =truea==c =falsea<=c =truea>=b =truea+b!=c =truea+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 =5b =5a>b && a==b = false

Page 18: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 18

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.javaC:\Java\jdk1.5.0_17\bin>java bit70*/

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.javaC:\Java\jdk1.5.0_17\bin>java shift24

Page 19: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 19

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 = 10b = 15c = 25Maxm of 3 nos : 25*/

Page 20: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 20

4. Control StructuresA 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.javaC:\Java\jdk1.5.0_17\bin>java area 6113.03999999999999C:\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)

Page 21: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 21

{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

Page 22: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 22

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=68C:\Java\jdk1.5.0_04\bin>java Switch 23 45 -23-45=-22C:\Java\jdk1.5.0_04\bin>java Switch 23 45 /23/45=0C:\Java\jdk1.5.0_04\bin>java Switch 23 45 %23%45=23*/

Page 23: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 23

5. LoopsJava‘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;

Page 24: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 24

}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.javaC:\Java\jdk1.5.0_04\bin>java GCDGCD is 5*/

Page 25: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 25

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.javaC:\Java\jdk1.5.0_04\bin>java Reverse 9867The 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)

Page 26: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 26

break;System.out.print(i +" ");

}}

}/*C:\Java\jdk1.5.0_04\bin>javac Break.javaC:\Java\jdk1.5.0_04\bin>java Break1 2 3 4 5 6 7 8 9 */

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.javaC:\Java\jdk1.5.0_04\bin>java Continue0 12 34 56 78 9*/

Page 27: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 27

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!

Page 28: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 28

6. FunctionsFunctions 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.javaC:\Java\jdk1.5.0_17\bin>java method2Total 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.

Page 29: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 29

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

elsereturn(n*fact(n-1));

}}/*C:\Java\jdk1.5.0_17\bin>javac Recursive.javaC:\Java\jdk1.5.0_17\bin>java RecursiveFactorial 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);

elsereturn(fib(n-1)+fib(n-2));

}}C:\Java\jdk1.5.0_17\bin>javac Fibonacci.javaC:\Java\jdk1.5.0_17\bin>java FibonacciThe fibonacci series is :1 1 2 3 5 8 13 21

Page 30: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 30

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.javaC:\Java\jdk1.5.0_17\bin>java ParameterThe reverse of number is :4 3 2 1Sum of Digits is = 10*/

3. Write a program to print G.C.D of two number using recursive functionsclass 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;

Page 31: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 31

if(a<b)System.out.println(gcd(b,a));

elseSystem.out.println(gcd(a,b));

}}/*C:\Java\jdk1.5.0_17\bin>javac GCD.javaC:\Java\jdk1.5.0_17\bin>java GCD27*/

Page 32: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 32

7. ArraysAn 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;

Page 33: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 33

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 71Sum =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.javaC:\Java\jdk1.6.0_05\bin>java ArrayCopyArray y after copying is : 11 22 33 44 55 */

Page 34: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 34

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 Item3Salesgirl#1 310 275 365Salesgirl#2 210 190 325Salesgirl#3 405 235 240Salesgirl#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;}

Page 35: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 35

} if(i==n)

System.out.println("Element not found"); }}/*C:\Java\jdk1.5.0_17\bin>javac search.javaC:\Java\jdk1.5.0_17\bin>java search 18List of elements : 23 55 14 18 67Element 18 found at 3 positionC:\Java\jdk1.5.0_17\bin>java search 17List of elements : 23 55 14 18 67Element 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

Page 36: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 36

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.javaC:\Java\jdk1.5.0_17\bin>java search 18List of elements : 23 55 18 18 67Element 18 found at 2 positionElement 18 found at 3 positionElement found 2 timesC:\Java\jdk1.5.0_17\bin>java search 17List of elements : 23 55 18 18 67Element not found

7.5.4 Matrix Addition:class matadd{

public static void main(String args[]){

Page 37: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 37

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

Page 38: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 38

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.javaC:\Java\jdk1.5.0_17\bin>java mataddThe X array is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16The Y array is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16The Z array is : 2 4 6 8 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++)

Page 39: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 39

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

}}

Page 40: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 40

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

Page 41: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 41

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

Page 42: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 42

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.javaC:\Java\jdk1.5.0_17\bin>java TDetailHour = 2Minute = 25Second = 56Total 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;

Page 43: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 43

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.javaC:\Java\jdk1.5.0_17\bin>java TDetails6 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()

Page 44: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 44

{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.javaC:\Java\jdk1.5.0_17\bin>java TMDetail3 54 452 44 236 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);}

Page 45: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 45

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

Page 46: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 46

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.javaE:\Java\jdk1.5.0_16\bin>java EmpDetailEnter Rollno :1Enter Name :shaliniEnter Salary :5000Enter Rollno :2Enter Name :ajayEnter Salary :60001 shalini 5000.02 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

Page 47: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 47

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.javaC:\Java\jdk1.6.0_05\bin>java MathApplicationb =7*/

Page 48: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 48

9. Wrapper ClassesWhen 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.javaC:\Java\jdk1.5.0_17\bin>java IntWrapperValue 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);

Page 49: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 49

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.javaC:\Java\jdk1.5.0_17\bin>java float1f1 =2.5f2 =2.6f3 =2.7Max Value = 3.4028235E38Min 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.javaC:\Java\jdk1.5.0_17\bin>java DWrapperValue 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);

}}

Page 50: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 50

/*C:\Java\jdk1.5.0_17\bin>javac BWrapper.javaC:\Java\jdk1.5.0_17\bin>java BWrapperValue 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.javaC:\Program Files\Java\jdk1.5.0_17\bin>java CWrapperValue of Character object is =D*/

Page 51: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 51

10. StringsStrings 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.

Page 52: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 52

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 = ShaliniLength = 7Lower Case of Name = shaliniUpper Case of Name = SHALINIUpper Case of Name = ShalbnbName equals N1 = falseName equals N1 = trueName compares N1 = -32N1 compares Name = 32Concatenate Name with string = ShaliniPuriSubstring of Name = liniSubstring of Name = aliIndex of i in Name = 4*/

Page 53: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 53

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.javaC:\Program Files\Java\jdk1.5.0_17\bin>java SortNames before sorting :raj ajay amar sita nitinNames 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.

Page 54: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 54

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)

Page 55: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 55

{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.javaC:\Java\jdk1.6.0_05\bin>java LanguageVector Ada Basic C++ FORTRAN JavaList of languages :AdaBasicCOBOLC++FORTRANJavaC:\Java\jdk1.6.0_05\bin>*/

Page 56: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 56

11. Simple Input/OutputModern 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

Page 57: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 57

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.javaC:\Program Files\Java\jdk1.5.0_17\bin>java ReadCharEnter Q to exitShaliniQShaliniQ*/

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

Page 58: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 58

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.javaC:\Program Files\Java\jdk1.5.0_17\bin>java ReadCharEnter some text, Q to quitWelcome to the World of JavaQText entered by is :Welcome to the World of Java*/

Page 59: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 59

12.InheritanceIn 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.

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.

A program that illustrates Single level Inheritance:

class Room{

int length,breadth;Room(int l,int b)

Class A(superclass)

Class B(subclass)

A

B

Page 60: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 60

{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 = 200Volume = 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.

A

B C D

Page 61: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 61

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.125Area 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:

Page 62: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 62

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:

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;

Two Wheeler

Vehicle

Four Wheeler

Page 63: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 63

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 HondaMilage of the Vehicle :70.0Clutch present :yName of the company :MarutiMilage of the Vehicle :17.0AC present :y*/

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

Inheritance.

A

B

C

Page 64: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 64

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[])

Page 65: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 65

{Result R = new Result(1,"Shalini",50,67);R.display();R.show();R.showRes();

}}/*Roll No = 1Name = ShaliniMarks 1 = 50.0Marks 2 = 67.0Result = 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)

Page 66: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 66

{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.javaC:\Program Files\Java\jdk1.5.0_17\bin>java MulTestRoll No = 1Name = ShaliniMarks 1 = 50.0Marks 2 = 67.0Result = 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

Page 67: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 67

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

Page 68: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 68

}}/*C:\Java\jdk1.6.0_05\bin>javac InterfaceTest.javaC:\Java\jdk1.6.0_05\bin>java InterfaceTestArea of Rectangle :200.0Area 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);

Page 69: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 69

}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.javaC:\Java\jdk1.6.0_05\bin>java HybridRoll No :234Marks obtained :Part 1 =27.5Part 2 =33.05Total Score =66.55*/

Page 70: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 70

13. PackagesThe 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;

Page 71: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 71

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)

Page 72: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 72

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

}}

Page 73: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 73

/*C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Student.javaC:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Test.javaC:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Result.javaC:\Program Files\Java\jdk1.6.0_05\bin>javac SReport/Sports.javaC:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Demo.javaC:\Program Files\Java\jdk1.6.0_05\bin>java Report/DemoDisplay called from Student :Roll No :1Name :ShaliniDate of Birth :01/01/1975Address :VashiDisplay called from Test :Name :ShaliniDate of Birth :01/01/1975Address :VashiMarks 1 :65Marks 2 :75Display called from Result :Name :ShaliniAddress :VashiMarks 1 :65Marks 2 :75Total Marks :140Display called from Student :Roll No :2Name :AmarDate of Birth :01/01/1972Address :NaviMumbaiDisplay called from Sports :Date of Birth :01/01/1972Address :NaviMumbaiSports 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.

Page 74: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 74

abs(long)

abs(float)

abs(double)

Returns the absolute long value of a.

Returns the absolute float value of a.

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

uble)

Converts rectangular coordinates (a, b) to polar (r, theta).

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)

max(long, long)

max(float, float)

max(double,

double)

Takes two int values, a and b,& returns the greater number of the two.

Takes two long values, a & b & returns the greater number of the two.

Takes two float values, a & b& returns the greater number of the two.

Takes two double values, a & b, & returns the greater number of the

two.

min(int, int)

min(long, long)

min(float, float)

min(double,

double)

Takes 2 int values, a & b, & returns the smallest number of the two.

Takes 2 long values, a & b, and returns the smallest number of the two

Takes 2 float values, a &b, and returns the smallest number of the two.

Takes two double values, a and b, and returns the smallest number of

the two.

pow(double,

double)

Returns the number a raised to the power of b.

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.

Page 75: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 75

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

round(float)

round(double)

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

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

Page 76: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 76

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

Page 77: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 77

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

Page 78: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 78

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

Page 79: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 79

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

packageYes Yes Yes No

Other classes in

same packageYes No Yes No

Subclass in another

packageYes Yes No No

Non-subclass in

other packagesYes No No No

Page 80: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 80

14. Exception HandlingThe 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.javaC:\Java\jdk1.5.0_04\bin>java ErrorException 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

Page 81: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 81

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

Page 82: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 82

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:

Page 83: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 83

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 zeroy = 1*/

14.2.2 Catching Invalid Command line arguments:class ClineInput{

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

Page 84: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 84

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.javaC:\Java\jdk1.5.0_04\bin>java ClineInput Java 10 17.5 18 youInvalid arguments :JavaInvalid arguments :17.5Invalid arguments :youValid arguments :2InValid 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)

Page 85: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 85

{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.javaC:\Java\jdk1.5.0_04\bin>java ErrorArray Index Errory= 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

Page 86: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 86

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

Page 87: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 87

15. MultithreadingMultithreading 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

Page 88: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 88

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:

Page 89: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 89

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

}}

Page 90: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 90

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.javaC:\Java\jdk1.6.0_05\bin>java ThreadTestFrom Thread A : i =1From Thread A : i =2From Thread A : i =3From Thread A : i =4From Thread A : i =5Exit from AFrom Thread B : j =1From Thread B : j =2From Thread B : j =3From Thread B : j =4From Thread B : j =5Exit from BFrom Thread C : k =1From Thread C : k =2From Thread C : k =3From Thread C : k =4From Thread C : k =5Exit 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

Page 91: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 91

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.javaC:\Java\jdk1.5.0_04\bin>java RunnableTest

Page 92: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 92

Main ThreadMain ThreadMain ThreadMain ThreadMain ThreadMain ThreadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadGreetings from Child threadEnd of Child threadMain ThreadMain ThreadMain ThreadMain ThreadEnd 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.

Page 93: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 93

New Thread

start()

stop()

Active Thread stop()

yield

yield() resume()

wait ( ) notify () stop( )

sleep()

suspend( )

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:

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.

New Born

NewBorn

Runnable State

Dead State

Running Runnable

Blocked

Dead

Page 94: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 94

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:

Page 95: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 95

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)

{……………..

……………….}

Page 96: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 96

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( ){

…………………………………………..

}}

Page 97: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 97

16. Graphics and Java AppletsJava 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.

Page 98: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 98

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>

Page 99: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 99

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

Initialization

start()

stop() stopped paint()

destroy()

Destroyed End

Exit of BrowserInitialization 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

Born

Idle

Running

Dead

Page 100: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 100

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( ){……………….

Page 101: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 101

……………….}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

Page 102: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 102

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

Page 103: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 103

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.

Page 104: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 104

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(){

Page 105: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 105

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.javaE:\Java\jdk1.5.0_16\bin>java GCD35 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[]) {

Page 106: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 106

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/2009Enter the starting date in MM/DD/YYYY:1 19 20094 30 2009No.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);

Page 107: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 107

System.out.print(S0);t=t+5;

}}

}/*C:\Java\jdk1.5.0_17\bin>javac Distance.javaC:\Java\jdk1.5.0_17\bin>java Distance 7 5 6S0: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++)

Page 108: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 108

{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 StudDetailEnter Rollno :1Enter Name :shalini

Page 109: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 109

Enter Physics :45Enter Chemistry :46Enter Maths :33Enter Rollno :2Enter Name :ajayEnter Physics :46Enter Chemistry :45Enter Maths :44Enter Rollno :3Enter Name :abhiEnter Physics :45Enter Chemistry :49Enter Maths :49Student Details:1 shalini 124.02 ajay 135.03 abhi 143.0Student Details in the descending order of marks:3 abhi 143.02 ajay 135.01 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

Page 110: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 110

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:

Page 111: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 111

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++){

Page 112: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 112

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]+ " ");

Page 113: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 113

}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.javaE:\Java\jdk1.5.0_16\bin>java abc1Displaying Matrix :1 2 34 5 67 8 9Displaying Transposed Matrix :1 4 72 5 83 6 9Displaying Addition Matrix :2 4 68 10 1214 16 18Displaying Multiplicated Matrix :18 21 2427 30 3336 39 42*/

Page 114: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 114

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

elsereturn(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.javaC:\Java\jdk1.5.0_17\bin>java PComb 7 5P =2520C =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

Page 115: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 115

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.javaC:\Java\jdk1.5.0_17\bin>java series 7Series =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.

Page 116: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 116

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

Page 117: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 117

if(palindrome.equals(reversePalindrome))System.out.println("palindrome");

elseSystem.out.println("not a palindrome");

}}/*C:\Java\jdk1.5.0_17\bin>javac StringDemo.javaC:\Java\jdk1.5.0_17\bin>java StringDemo MADAMpalindromeC:\Program Files\Java\jdk1.5.0_17\bin>java StringDemo MADAMAnot 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 circleclass 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: '{' expectedclass Import Class ^Import Class.java:9: '}' expected^2 errorsC:\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 errorsii) int m = 10; int n = 7; while(m%n>=0) {

Page 118: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 118

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

Page 119: 48210796 CP 2 Notes Java Mumbai University

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

Prof. Shalini Puri 119

i = 8 sum = 2.7178574 i = 9 sum = 2.8289685i = 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.