chapter 1: - welcome to publishererperp.techmaxbooks.com/uploadedfiles/samplechapter/m... · web...

164
Data Structure & Algorithms (M) 1-1 Revisiting Java Programming Construct Revisiting Java Programming Construct Syllabus : Classes types and objects Methods Expressions Control flow Arrays Input and output Packages Utilities in the java.lang package 1.1 Classes and Objects : Java is a true Object-Oriented Language and therefore the underlying structure of all Java programs is classes. 1

Upload: vantruc

Post on 05-May-2018

216 views

Category:

Documents


1 download

TRANSCRIPT

Data Structure & Algorithms (M) 1-1 Revisiting Java Programming Construct

Revisiting Java ProgrammingConstruct

Syllabus :

Classes types and objects

Methods

Expressions

Control flow

Arrays

Input and output

Packages

Utilities in the java.lang package 

1.1 Classes and Objects :

Java is a true Object-Oriented Language and therefore the underlying structure of all Java programs is classes.

Class defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is template for an object, and an object is an instance of a class.

1.1.1 The General Form of a Class :

1

Data Structure & Algorithms (M) 1-2 Revisiting Java Programming Construct

A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. The general form of a class definition is shown here :

class classname{

type instance-variable1;type instance-variable2;

. . type instance-variableN;

type methodname1(parameter-list){

// body of method}type methodname2(parameter-list){

// body of method}

type methodnameN(parameter-list){

// body of method}

} The data, or variables, defined within a class are called instance variables. The code is

contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

Variables defined within a class are called instance variables because each instance of the class contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.

Note : The general form of a class does not specify main( ) method. Java classes do not need to

have a main( ) method. You only specify one if that class is the starting point for your program. Further, applets don’t require a main( ) method at all.

C++ programmer may note that there is no semicolon after closing brace.

1.1.2 Declaration of Instance Variables :

Let’s begin our study of the class with a simple example. Here is a class called Rectangle that defines two instance variables: length, and width. class Rectangle{

int length;

Data Structure & Algorithms (M) 1-3 Revisiting Java Programming Construct

int width;}

These variables are only declared and therefore no storage space has been created in the memory.

1.1.3 Declaring Objects :

Obtaining objects of a class is a two-step process :Step 1 : You must declare a variable of the class type. This variable does not define an

object. Instead, it is simply a variable that can refer to an object. Step 2 : You must acquire an actual, physical copy of the object. And assign it to that

variable. You can do this using the new operator. The new operator dynamically allocates (i.e., allocates at run time) memory for an object and returns a reference to it. This reference is more or less, the address in memory of the object allocated by new. This reference is then stores in the variable. Thus, in Java, all objects must be dynamically allocated.

Example :

Here is an example of creating object type Rectangle.

Rectangle rect; // declare reference to object rect = new Rectangle( ); // allocate a Rectangle object

Step 1 : The first line declares rect as a reference to an object of type Rectangle. After this line executes, rect contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use rect at this point will result in a compile time error.

Step 2 : The second line allocates an actual object and assigns a reference to it to rect. After the second line executes, you can use rect as if it were a Rectangle object. But, in reality rect simply holds the memory address of the actual Rectangle object.

The effect of these two lines of code is depicted in Table 1.1.

Table 1.1

Step Statement Effect

1 Rectangle rect;

2 rect = new Rectangle( );

Data Structure & Algorithms (M) 1-4 Revisiting Java Programming Construct

Both statements can be combined into one as shown below :

Rectangle rect = new Rectangle( );

The method Rectangle( ) is the default constructor of the class. We can create any number of objects of Rectangle. Example :

Rectangle rect1 = new Rectangle( );Rectangle rect2 = new Rectangle( );

Note : The new allocates memory for an object during run time. The advantage of this approach is that your program can create as many or as few objects as it needs during the execution of your program. However, since memory is finite, it is possible that new will not be able to allocate memory for an object because insufficient memory exists. If this happens, a run-time exception will occur.

1.1.4 Accessing Instance Variables :

Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Rectangle object will contain its own copies of the instance variables length, and width. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. The syntax is given below :

objectname.variablename = value;

Example :

To assign the length variable of rect the value 20, you would use the following statement :

rect.length = 20;

This statement tells the compiler to assign the copy of length that is contained within the rect object the value of 20. In general you use dot operator to access both the instance variables and the methods within an object.

A Simple Program : P. 1.1 : Program which uses the Rectangle class to compute area of the rectangle. /* Program to demonstrate the use of class.Call this file RectangleDemo1.java */class Rectangle{

int length;

Data Structure & Algorithms (M) 1-5 Revisiting Java Programming Construct

int width;}// This class declares an object of type Rectangle.class RectangleDemo1{

public static void main(String args[]){

Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();int area;

//assign values to rect1's instance variablesrect1.length= 20;rect1.width=15;

//assign different values to rect2's instance variablesrect2.length= 25;rect2.width=17;

// compute area of first rectanglearea= rect1.length* rect1.width;

System.out.println("Area of Rectangle (length :"+rect1.length+", width :"+rect1.width+") is :+area);

// compute area of second rectanglearea= rect2.length* rect2.width;

System.out.println("Area of Rectangle (length : "+rect2.length+", width :"+rect2.width+") is :+area);

}}Execution :C:\javac RectangleDemo1.javaC:\java RectangleDemo1

Output :

Area of Rectangle (length : 20 , width : 15) is : 300 Area of Rectangle (length : 25 , width : 17) is : 425 Refer Demo1.java file on CD

Data Structure & Algorithms (M) 1-6 Revisiting Java Programming Construct

Explanation of RectangleDemo1.java :

You should call the file that contains this program RectangleDemo1.java, because the main( ) method is in the class RectangleDemo1, not the class called Rectangle. When you compile this program, you will find that two .class files have been created, one for Rectangle and one for RectangleDemo1. The Java compiler automatically puts each class into its own .class file. It is not necessary for both the Rectangle and the RectangleDemo1 class to actually be in the same source file. You could put each class in its own file, called Rectangle.java and RectangleDemo1.java, respectively.

Each object has its own copies of the instance variables. In above program we have declared two Rectangle objects; each has its own copy of length, and width. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.

1.1.5 Assigning Object Reference Variables :

Let’s see following fragment carefully,

Rectangle rect1 = new Rectangle();

Rectangle rect2 = rect1;

After this fragment executes, rect1 and rect2 will both refer to the same object. The assignment of rect1 to rect2 did not allocate any memory or copy any part of the original object. It simply makes rect2 refer to the same object as does rect1. Thus, any changes made to the object through rect2 will affect the object to which rect1 is referring, since they are the same object. This situation is given in Fig. 1.1.

Fig. 1.1 : Assigning object reference variables

Although rect1 and rect2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to rect1 will simply unhook rect1 from the original object without affecting the object or affecting rect2. For example :

Rectangle rect1 = new Rectangle();Rectangle rect2 = rect1;

.

.rect1 = null;

Data Structure & Algorithms (M) 1-7 Revisiting Java Programming Construct

Here, rect1 has been set to null, but rect2 still points to the original object.

Note : When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.

1.2 Class Methods :

As mentioned in the previous section, classes usually consist of two things: instance variables and methods. The general form of a method is given below :

return-type method-name(parameter-list){

// body of method}

Method declarations have four basic parts : The name of the method (method-name) The type of the value the method returns (return-type) A list of parameters (parameter-list) The body of the method

Here, return-type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by method-name. This can be any legal identifier. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameters list will be empty.

Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:

return value;

Here, value is the value returned.

A simple program to illustrate method :

Let us consider Rectangle class again and add a method area() to it. P. 1.2 : Program to demonstrate method./* Program to demonstrate method */class Rectangle{

Data Structure & Algorithms (M) 1-8 Revisiting Java Programming Construct

int length;int width;// display Area of a Rectanglevoid area(){

System.out.println(" Area is "+(length*width));}

}class RectangleDemo2{

public static void main(String args[]){

Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();

//assign values to rect1's instance variablesrect1.length= 20;rect1.width=15;

//assign different values to rect2's instance variablesrect2.length= 25;rect2.width=17;

System.out.print("First Rectangle (length : "+rect1.length+", width : "+rect1.width+") --->");

rect1.area(); // display area of first rectangle

System.out.print("Second Rectangle (length : "+rect2.length+", width : "+rect2.width+") --->");

rect2.area(); // display area of second rectangle}

}

Execution :C:\javac RectangleDemo2.javaC:\java RectangleDemo2

Output :

First Rectangle (length : 20 , width : 15) ---> Area is 300

Data Structure & Algorithms (M) 1-9 Revisiting Java Programming Construct

Second Rectangle (length : 25 , width : 17) ---> Area is 425 Refer RectangleDemo2.java file on CD

Explanation of RectangleDemo2.java :

Invoking method :

The following line,

rect1.area( );

invokes the area( ) method on rect1. That is, it calls area( ) relative to the rect1 object, using object’s name followed by the dot operator. Thus, the call to rect1.area( ) displays the area of the rectangle defined by rect1. And call to,

rect2.area( );

displays the area of the rectangle defined by rect2. Each time area() is invoked, it displays the area for the specified rectangle.

What is exactly invoking a method ?

When rect1.area() is executed, the Java run-time system transfers control to the code defined inside area(). After the statements inside area() have executed, control is returned to the calling routine, and execution resumes with the line of code following the call.

Note : A method is always invoked relative to some objects of its class. Once this invocation has occurred, the object is known. Thus, within a method, there is no need to specify the object a second time. This means that length, and width inside area( ) implicitly refer to the copies of those variables found in the object that invokes area( ).

1.2.1 Returning a Value :

Let us add some more properties to the method. Assume that we want to compute the area of the rectangle and return that result to the caller. The following example, an improved version of the preceding program, does just that :

P. 1.3 : Program to demonstrate returning a value.

/* Program to demonstrate returning a value */class Rectangle{

int length;int width;// compute and return Area of a Rectangleint area()

Data Structure & Algorithms (M) 1-10 Revisiting Java Programming Construct

{return length*width;

}}class RectangleDemo3{

public static void main(String args[]){

Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();int a;

//assign values to rect1's instance variablesrect1.length= 20;rect1.width=15;

//assign different values to rect2's instance variablesrect2.length= 25;rect2.width=17;

System.out.print(" First Recangle (length : "+rect1.length+" , width : "+rect1.width+") --->");

a = rect1.area(); // get area of first rectangleSystem.out.println(" Area is : "+a);

System.out.print("Second Recangle (length : "+rect2.length+", width : "+rect2.width+") --->");

a= rect2.area(); // get area of second rectangleSystem.out.println(" Area is : "+a);

}}Execution :C:\javac RectangleDemo3.javaC:\java RectangleDemo3

Output :

First Rectangle (length : 20 , width : 15) ---> Area is 300 Second Rectangle (length : 25 , width : 17) ---> Area is 425

Data Structure & Algorithms (M) 1-11 Revisiting Java Programming Construct

Refer RectangleDemo3.java file on CD

Data Structure & Algorithms (M) 1-12 Revisiting Java Programming Construct

Explanation of RectangleDemo3.java :As you can see, when area( ) is called, it put on the right side of an assignment

statement. On the left is a variable, in this case a, that will receive the value returned by area( ).

Thus, after

a = rect1.area( );

executes, the value of rect1.area() is 300 and this value then is stored in a.

Note : The type of data returned by a method must be compatible with the return type specified

by the method.

The variable receiving the value returned by a method must also be compatible with the return type specified for the method.

1.2.2 Method that Takes Parameters :Parameterized method can operate on a variety of data. You can use parameterized

method to improve the Rectangle class. This concept is implemented by the following program : P. 1.4 : Program to demonstrate method that takes parameters./* Program to demonstrate method that takes parameters */class Rectangle{

int length;int width;

// compute and return Area of a Rectangleint area(){

return length*width;}// sets values of rectanglevoid setdata(int l,int w){

length = l;width = w;

}}class RectangleDemo4{

Data Structure & Algorithms (M) 1-13 Revisiting Java Programming Construct

public static void main(String args[ ]){

Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();int a;// initialize each rectanglerect1.setdata(20,15);rect2.setdata(25,17);

// get area of first rectanglea = rect1.area(); System.out.println(" Area of First Rectangle is : "+a);

// get area of second rectanglea= rect2.area(); System.out.println(" Area of Second Rectangle is : "+a);

}}Execution :C:\javac RectangleDemo4.javaC:\java RectangleDemo4

Output :

Area of First Rectangle is : 300Area of Second Rectangle is : 425 Refer RectangleDemo4.java file on CD

Explanation of RectangleDemo4.java :

As you can see, the setdata() method is used to set the value (i.e. length and width) of each rectangle. For example, when

rect1.setdata(20,15);

is executed, 20 is copied into parameters l, and 15 is copied into w. inside setdata() the values of l, and w are then assigned to length, and width respectively.

1.3 Expressions :

An expression is a combination of operators, constants and variables arranged as per the rules of the language. It may also include function calls which return values. An expression

Data Structure & Algorithms (M) 1-14 Revisiting Java Programming Construct

may consist of one or more operands, and zero or more operators to produce a value. Expression may be of the following seven types :

Constant Expressions

Integral Expressions

Float Expressions

Relational Expressions

Logical Expressions

Bitwise Expressions

An expression may also use combinations of the above expressions. Such expressions are known as compound expressions.

Expressions involve the use of literals, variables and operators.

Literals :

A literal is any constant value that can be used in an assignment or other expression. Java allows, Boolean (true and false), integer literal, floating point literals, character literals, string literals, the null obj reference (this is the only object literal and it is defined to be from the general object class).

Operators :

Java expressions involve composing literals and variables with operators. Java supports following operators.

1. Assignment operator :

The standard assignment operator in Java is ‘=’. Its syntax is as follows :

<variable> = <expression>

2. The dot operator :

One of the primary uses of an object reference ce variable is to access the members of the class for this object, an instance of its class. This access is performed with the (“ .”) operator. We call a method associated with an obj by using the following syntax :

<object reference> · <method_name> *[<param>, <param>, ….]);

<object reference> · <variable_name>

3. Arithmetic operators :

Arithmetic operators are given below :

+ addition

– subtraction

Data Structure & Algorithms (M) 1-15 Revisiting Java Programming Construct

multiplication

/ division

% modulo

4. Increment and decrement operatorLike C & C++, Java also provides increment and decrement operators. Increment and decrement operators are,

+ + increment

– – decrement

5. Logical operators

Java allows for the standard relational operators between numbers; they are given below :

< less than<= less than or equal to> = greater than or greater than > greater than= = equal to ! = not equal to

Logical operators are given below :

! not (prefix)

&& condition and

| | conditional or

6. Bitwise operators :

Java provides the bitwise operators for integers and Booleans; they are given below :~ bitwise complement& bitwise and| bitwise or^ bitwise exclusive-or< < shift bits left, filling in with zero> > shift bits right, filling in with sign bit> > > shift bits right filling in with zero

7. Operational assignment operators :

Operational assignment operators are of the following form :

<variable> <op> = <expression>;

Data Structure & Algorithms (M) 1-16 Revisiting Java Programming Construct

This is equivalent to

<variable> = <variable> (op) <expression>

8. String Concatenation :

String can be composed using the concatenation operator (+).

Example :

String str1 = “Abdul” ;

String str2 = “Kalam”;

String str3 = str1 + str2;

Above code will assign str3 equal to “Abdulkalam”.

Casting in expression :

This is explained in chapter 2.

1.4 Control Flow :

A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s program control statements can be put into the following categories: selection, iteration and jump.

Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable.

Iteration statements enable program execution to repeat one or more statements.

Jump statements allow your program to execute in a nonlinear fashion.

1.4.1 Selection Control Statements :

1.4.1.1 The if statement :

The if statement allows conditional execution. Its syntax isif(condition) { Statement1; Statement2; . . Statmentn;

Data Structure & Algorithms (M) 1-17 Revisiting Java Programming Construct

}The keyword if tells the compiler that what follows, is a decision control instruction.

The condition following the keyword if is always enclosed within a pair of parenthesis. If the condition is true, then the statements are executed. If the condition is not true then the statements are not executed, instead the program skips past it. We express a condition using relational operators. P. 1.5 : Program to demonstrate Multiple statements within if

class IfDemo{

public static void main(String args[ ]){

int marks;marks = 35;

if(marks<40){

int lessmarks=40-marks;System.out.println("\nSorry!!!!!you are failed");System.out.println("\nYou should have got "+lessmarks+" more

marks");}

}}

Execution :C:\javac IfDemo.javaC:\java IfDemo

Output :

Sorry!!!!!you are failedYou should have got 5 more marks Refer IfDemo.java file on CDExplanation of IfDemo.java :

Observe that the 3 statements to be executed on satisfaction of the condition have been enclosed within a pair of braces. If a pair of braces is not used then the Java compiler assumes that the programmer wants only the immediately next statement after the if to be executed on

Data Structure & Algorithms (M) 1-18 Revisiting Java Programming Construct

satisfaction of the condition. In other words we can say that default scope of the if statement is the immediately next statement after it.

1.4.1.2 The if–else statement :

The if-else statement is an extension of the simple if statement. The general form is :if(condition){

True-block statement(s);}else{

False-block statement(s);}

If the condition is true, then the true-block statement(s) immediately following the if statement, are executed; otherwise, the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both.

P. 1.6 : Program to find given number is even or odd.

/* program to check whether number is even or odd */class EvenOdd{

public static void main(String args[ ]){

int no , temp ;no = 35;

temp = no % 2 ;if (temp == 0)

System.out.println("The number "+no+" is Even.");else

System.out.println("The number "+no+" is Odd.");}

}Execution :C:\javac EvenOdd.javaC:\java EvenOdd

Data Structure & Algorithms (M) 1-19 Revisiting Java Programming Construct

Output :

The number 35 is odd. Refer EvenOdd.java file on CD

Explanation of EvenOdd.java :

The expression in the if-else statement is (temp = = 0). If this expression evaluates to be TRUE, the message ‘The number is Even’ is displayed on screen. If the expression evaluates to be FALSE, then the message ‘The number is Odd’ is displayed on screen.

1.4.1.3 The Switch 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 thisbreak;

case value2:do this;break;

. .

case valuen:do this;break;

default: do this;}

The expression must be type byte, shot, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case vale must be a unique literal. Duplicate case vales 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 the 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.

Data Structure & Algorithms (M) 1-20 Revisiting Java Programming Construct

The break statement is used inside the switch to terminate a statement sequence. When a break 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. P. 1.7 : Program to performed arithmetic operations using switch case. /*Program to performed arithmetic operations using switch case*/class SwitchDemo{ public static void main(String args[ ]) {

int x , y ;char choice;x = 10;y = 2;

System.out.println("\t\tMenu\n");System.out.println("\t1. Addition --> Enter A \n");System.out.println("\t2. Subtraction --> Enter S \n");System.out.println("\t3. Division --> Enter D \n");System.out.println("\t4. Multiplication --> Enter M \n");

try{

System.out.println("Enter your choice :"); choice= (char)System.in.read( );

switch (choice){

case 'A' :System.out.println("Addition of "+x+" and "+y+" : "+(x+y));break ;case 'S' :System.out.println("Subtraction of "+x+" and "+y+" : "+(x-y));break ;case 'D' :

System.out.println("Division of "+x+" and "+y+" : "+((float)x/(float)y));

break ;case 'M' :System.out.println("Multiplication of "+x+" and "+y+" : "+(x*y));break ;default :System.out.println("Wrong choice !!");

} // End of switch statement} // End of try statement

Data Structure & Algorithms (M) 1-21 Revisiting Java Programming Construct

catch(Exception e) {

System.out.println("I/O Error"); }

} // End of main method} // End of class SwitchDemo

Execution :C:\javac SwitchDemo.javaC:\java SwitchDemo

Output :

Menu

1. Addition --> Enter A

2. Subtraction --> Enter S

3. Division --> Enter D

4. Multiplication --> Enter M

Enter your choice :AAddition of 10 and 2 : 12 Refer SwitchDemo.java file on CD

Explanation of SwitchDemo.java :

System.in is an object of type InputStream, used to read characters from the console. In above program the read( ) method reads the input from the keyboard as a string which is then converted to the char data type using casting operator. Note that we have used the keywords try and catch to handle any errors that might occur during the reading process.

1.4.2 Iteration Statements :

Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops.

1.4.2.1 The While Statement :

The while loop repeats a statement or block while its controlling expression is true. The syntax for the while statement is :

while(condition)

Data Structure & Algorithms (M) 1-22 Revisiting Java Programming Construct

{// body of 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. P. 1.8 : Program of finding out the Greatest Common Division (GCD) of the given

two numbers, using while loop. /* Program of finding out the Greatest Common Division (GCD) of the given two numbers, using while loop*/

class GCD{

public static void main(String args[ ]){

int num_1 , num_2 ; num_1 = 25;num_2 = 15;

System.out.print("The GCD of "+num_1+" and "+num_2);

while ((num_1!=0) && (num_2!=0)) {

if (num_1 > num_2)num_1 = num_1 - num_2 ;

elsenum_2 = num_2 - num_1 ;

}System.out.print(" is "+num_1);

}}Execution :

C:\javac GCD.javaC:\java GCD

Output :The GCD of 25 and 15 is 5 Refer GCD.java file on CD

1.4.2.2 The 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.

Data Structure & Algorithms (M) 1-23 Revisiting Java Programming Construct

We can say that the do-while loop is a modified version of the while loop, with the condition placed at the loop end. This loop is also known, simply as the do-statement. Its general form is :

do{ // body of loop} while(condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression.

Note : Remember that the do-while loop is executed at least once.

P. 1.9 : Let us consider program to reverse the digits of any integer number. For example, the number 12345 should be written 54321.

/* Program to reverse the digits of any integer number*/class ReverseDigits{

public static void main(String args[ ]){

int num , temp ; num = 1234;System.out.println(" The Number is : "+num);

System.out.print(" The Reverse Number is : ");do{

temp = num % 10 ;System.out.print(temp);num = num / 10 ;

} while (num != 0) ;}

}Execution :

C:\javac ReverseDigits.javaC:\java ReverseDigits

Output : The Number is : 1234 The Reverse Number is : 4321 Refer ReverseDigits.java file on CD

Explanation of ReverseDigits.java:

Data Structure & Algorithms (M) 1-24 Revisiting Java Programming Construct

The number is stored in the variable num. Then we have the do-while loop. This loop is first executed once and then the loop condition is checked. The loop condition is (num ! = 0). If this condition evaluates to be TRUE, the loop is executed again, otherwise the loop is terminated.

1.4.2.3 The for Loop :

The for statement allows us to specify three things about a loop in a single line :

Setting a loop counter to an initial value.

Testing the loop counter to determine whether its value has reached the number of repetitions desired.

Increasing the value of loop counter each time the program segment within the loop has been executed.

The syntax for the for statement is :for (initialisation; condition; update){

// body of loop}

The initialization expression is used to declare and/or initialize control variables for the loop; it is evaluated first before any iteration occurs. 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. We can have more than one condition separated by comma.

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. P. 1.10 : 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./* program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7 */

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

Data Structure & Algorithms (M) 1-25 Revisiting Java Programming Construct

int no,count=0,sum=0;

for(no=101;no>100&&no<200;no++)if(no%7==0){

System.out.println(" "+no+" is divisible by 7");sum=sum+no;count=count+1;

}System.out.println("\n Total no. of integer between 100 to 200 that are divisible

by 7 : "+count);System.out.println(" Sum of all integer between 100 to 200 that are divisible by

7 : "+sum);}

}Execution :

C:\javac ForDemo.javaC:\java ForDemo

Output :

105 is divisible by 7112 is divisible by 7119 is divisible by 7126 is divisible by 7133 is divisible by 7140 is divisible by 7147 is divisible by 7154 is divisible by 7161 is divisible by 7168 is divisible by 7175 is divisible by 7182 is divisible by 7189 is divisible by 7196 is divisible by 7

Total no. of integer between 100 to 200 that are divisible by 7 : 14Sum of all integer between 100 to 200 that are divisible by 7 : 2107 Refer ForDemo.java file on CD

Data Structure & Algorithms (M) 1-26 Revisiting Java Programming Construct

1.4.3 Jump Statements :

Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.

Note : In addition to the jump statements discussed here, Java supports one other way that you can change your program’s flow of execution: through Exception Handling mechanism. Exception handling is discussed in chapter 3.

1.4.3.1 The break Statement :

In Java, the break statement has three uses :

1. It terminates a statement sequence in a switch statement.

2. It can be used to exit a loop.

3. It can be used as a civilized form of goto.

We have already seen the first purpose of break in switch statement. Hence last two purposes are explained in this section.

Using break to exit a loop :

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here are some simple examples. P. 1.11 : Program that uses break in for loop./* Using break to exit a for loop*/

class BreakDemo1{

public static void main(String args[ ]){

for(int i =0;i<100;i++){

if(i==10) break; //terminate loop if i is 10System.out.println("i ="+i);

}System.out.println("End of Loop");

}}

Data Structure & Algorithms (M) 1-27 Revisiting Java Programming Construct

Execution :C:\javac BreakDemo1.javaC:\java BreakDemo1

Output :

i = 0i = 1i = 2i = 3i = 4i = 5i = 6i = 7i = 8i = 9End of Loop Refer BreakDemo1.java file on CD

Explanation of BreakDemo1.java :

As you can see, although the for loop is designed to run from 0 to 99, the break statement cause it to terminate early, when i equals 10.

Note : The break statement can be used with any of Java’s loops. We can rewrite above program by using while loop.

Using break as a form of goto :

Java does not have a goto statement, because it provides a way to branch in an arbitrary and unstructured manner.

Java defines expanded form of the break statement. By using this form of break, you can break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block. Further, you can specify precisely where execution will resume, because this form of break works with a label. As you will see, break gives you the benefits of a goto.

The general form of the labeled break statement is shown here:

break label;

Data Structure & Algorithms (M) 1-28 Revisiting Java Programming Construct

Here, label is the name of a label that identifies a block of code. When this form of break executes, control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block. This means that you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control to a block of code that does not enclose the break statement.

To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once you have labeled a block, you can then use this label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block.

P. 1.12 : Following program using break as civilized form of goto./* Program that uses break as a civilized form of goto*/class BreakDemo2{

public static void main(String args[ ]){

boolean b = true;FIRST: {

SECOND :{

THRID : {

System.out.println("Before break....");if(b) break SECOND ; //break out of second blockSystem.out.println("This won't execute....");

}System.out.println("This won't execute....");

} System.out.println("This is after SECOND block....");

}}

}

Execution :C:\javac BreakDemo2.javaC:\java BreakDemo2

Output :

Data Structure & Algorithms (M) 1-29 Revisiting Java Programming Construct

Before break.... This is after SECOND block.... Refer BreakDemo2.java file on CDExplanation of BreakDemo2.java :

Above program shows three nested blocks, each with its own label. The break statement causes execution to jump forward, past the end of the block labeled SECOND, skipping the two println( ) statements.

Data Structure & Algorithms (M) 1-30 Revisiting Java Programming Construct

1.4.3.2 The Continue Statement :

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end.

The continue statement performs such an action. In 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 which enclosing loop to continue.

P. 1.13 : Program that uses continue with a label, to print a triangular multiplication table for 0 through 9.

/* Program to demonstrate continue statement with a label*/class ContinueDemo{

public static void main(String args[ ]){

OUTER: for(int i =0;i<10;i++){

for(int j =0;j<10;j++){

if(j>i) {

System.out.println();continue OUTER;

}System.out.print(" "+(i*j));

}}System.out.println( );

}}Execution :

C:\javac ContinueDemo.javaC:\java ContinueDemo

Data Structure & Algorithms (M) 1-31 Revisiting Java Programming Construct

Output :

0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81 Refer ContinueDemo.java file on CD

Explanation of ContinueDemo.java:

The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop counting i.

1.4.3.3 The Return Statement :

The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. A full discussion of return must wait until methods are discussed later.

At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed.

P. 1.14 : Program to demonstrate return statement. /* Program to demonstrate return statement*/class ReturnDemo{

public static void main(String args[ ]){

boolean t = true;System.out.println("Before the return");if(t) return; // return to callerSystem.out.println("This won't execute");

}}

Data Structure & Algorithms (M) 1-32 Revisiting Java Programming Construct

Execution :C:\javac ReturnDemo.javaC:\java ReturnDemo

Output :

Before the return Refer ReturnDemo.java file on CD

Explanation of ReturnDemo.java :

Here return causes execution to return to the Java-runtime system, since it is the run-time system that calls main( ).

The final println( ) statement is not executed. As soon as return is executed, control passes back to the caller (i.e. Java-runtime system).

1.5 Arrays :

An Array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.

1.5.1 One-Dimensional Arrays :

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array.

Like any other variables, arrays must be declared and created in the computer memory before they are used. Creation of an array involves three steps:

1. Declaring the array.

2. Creating memory locations.

3. Initializing Arrays.

1.5.1.1 Declaring Arrays :

To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is :

type variable-name[ ];

Here, type declares the base type of the array. The base type for the array determines what type of data the array will hold. For example, the following declares an array named number with the type array of int :

int number[ ];

Data Structure & Algorithms (M) 1-33 Revisiting Java Programming Construct

Although this declaration establishes the fact that number is an array variable, no array actually exists. In fact, the value of number is set to null, which represents an array with no value.

Alternative array declaration syntax :

There is a second form that may be used to declare an array :

type[ ] variable-name;

Here, the square brackets follow the type specifier, and not the name of the array variable. For example, the following two declarations are equivalent :

int number[ ];

int [ ] number;

Note : Remember, we do not enter the size of the arrays in the declaration.

1.5.1.2 Creating Arrays :

After declaring an array, we need to create it in the memory. Java allows us to create arrays using new operator. new is a special operator that allocates memory.

The general form of new as it applies to one-dimensional arrays appears as follows :

array-variable = new type[size];

Here, type : specifies the type of data being allocated.

size : specifies the number of elements in the array.

array-variable : is the array variable that is linked to the array.

The elements in the array allocated by new will automatically be initialized to zero.

Example :

number = new int[4];

This example allocates a 4-element array of integers and links them to number. After this statement executes, number will refer to an array of 4 integers. Further, all elements in the array will be initialized to zero.

It is possible to combine the two steps- declaration and creation-into one as shown below :

int number[ ] = new int[4];

Fig. 1.2 illustrates creation of an array in memory.

Data Structure & Algorithms (M) 1-34 Revisiting Java Programming Construct

Statement Representation

int number[ ];

number = new int[4];

Fig. 1.2 : Creation of an Array in memory

1.5.1.3 Initializing Arrays :

The final step is to put values into the array created. This process is known as initialization. This is done using the array subscripts as shown below:

array-variable[subscript] = value;

Example :

number[0] = 5;

number[1] = 10;

number[2] = 15;

number[3] = 20;

Note :

Java creates arrays starting with the subscript of zero and ends with a value one less than size specified.

Unlike C, Java protects arrays from overruns and underruns. Trying to access an array bound its boundaries will generates an error message.

We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below:

type array-variable[ ] = { list of values };

Data Structure & Algorithms (M) 1-35 Revisiting Java Programming Construct

The array initializer is a list of values separated by commas and surrounded by curly braces. The compiler allocates enough space for all the elements specified in the list. There is no need to use new.

Example :

int number[ ] = {5,10,15,20};

It is possible to assign an array object to another.

Example :

int number1[ ] = { 5,10,15,20 };

int number2[ ];

number2 = number1;

are valid in Java. Both the arrays will have the same values.

1.5.1.4 A Simple Program on One-Dimensional Array :

Putting together all above information, here is a program that creates an array of the number to find average of 5 numbers. P. 1.15 : Program to calculate average of 5 numbers using array./* Program to calculate average of 5 numbers using Array*/class ArrayDemo1{

public static void main(String args[ ]){

int number[ ] = new int[5];int sum=0;number[0]=5;

number[1]=10;number[2]=15;number[3]=20;number[4]=25;for(int i=0;i<5;i++)

sum=sum+number[i];System.out.println("Average is : "+sum/5);

}}Execution :C:\ javac ArrayDemo1.javaC:\ java ArrayDemo1

Data Structure & Algorithms (M) 1-36 Revisiting Java Programming Construct

Output :

Average is : 15 Refer ArrayDemo1.java file on CD

1.5.1.5 Array Length :

In Java, all arrays store the allocated size in a variable named length. We can obtain the length of the array number using number.length.

Example :

int size = number.length;

This information will be useful in the manipulation of arrays when their sizes are not known. Following program illustrates the use of an array for sorting a list of numbers. P. 1.16 : Program to perform sorting on given numbers using Array./* Program to perform sorting on given numbers using Array*/class ArrayDemo2{

public static void main(String args[]){

int number[] = {100,-34,78,23,10};int size= number.length;

System.out.println("Given List is : ");for(int i =0;i<size;i++)

System.out.print(" "+number[i]);System.out.println("\n");// Code for ascending sorting

for(int i =0;i<size;i++){

for(int j = i+1;j<size;j++){

if(number[i]>number[j]){

int temp=number[i];number[i]=number[j];number[j]=temp;

}}

Data Structure & Algorithms (M) 1-37 Revisiting Java Programming Construct

}System.out.println("Sorted List is : ");for(int i =0;i<size;i++)

System.out.print(" "+number[i]);}

}Execution :C:\ javac ArrayDemo2.javaC:\ java ArrayDemo2

Output :

Given List is : 100 -34 78 23 10

Sorted List is : -34 10 23 78 100 Refer ArrayDemo2.java file on CD

1.5.2 Multidimensional Arrays :

In Java, Multidimensional Arrays are actually arrays of arrays. To declare Multidimensional Array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called TwoDimensional.

int TwoDimensional[ ] [ ] = new int[4][3];

This allocates a 4 by 3 array and assigns it to TwoDimensional. Internally this matrix is implemented as an array of arrays of int. Conceptually, this array will look like one shown in Fig. 1.3.

Fig. 1.3 : A conceptual view of a 4 by 3, two-dimensional array

Note : Left index determines row and Right index determines column.

Data Structure & Algorithms (M) 1-38 Revisiting Java Programming Construct

1.5.2.1 A Simple Program on Multidimensional Array :

The following program numbers each element in the array from left to right, top to bottom, and then displays these values: P. 1.17 : Program to demonstrate a two-dimensional array./* Program to demonstrate a two-dimensional array*/class ArrayDemo3{

public static void main(String args[ ]){

int TwoDimensional [ ][ ]= new int[4][3];int i,j,count=0;

for(i=0;i<4;i++) for(j=0;j<3;j++) {

TwoDimensional[i][j]=count; count++;

}for(i=0;i<4;i++){ for(j=0;j<3;j++) System.out.print(TwoDimensional[i][j]+" "); System.out.println( );}

}}Execution :C:\ javac ArrayDemo3.javaC:\ java ArrayDemo3

Output :

0 1 23 4 56 7 89 10 11

Refer ArrayDemo3.java file on CD

Data Structure & Algorithms (M) 1-39 Revisiting Java Programming Construct

1.5.2.2 Uneven (or Irregular) Multidimensional Arrays :

When, you allocate dimensions manually, you do not need to allocate the same number of elements for each dimension.

When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately.

For example, this following code allocates memory for the first dimension of TwoDimensional when it is declared. It allocates the second dimension manually.

int TwoDimensional [ ] [ ] = new int[3][ ];

TwoDimensional [0] = new int[2];

TwoDimensional [1] = new int[5];

TwoDimensional [2] = new int[3];

These statements create a two-dimensional array as having different lengths for each row as shown in Fig. 1.4.

Fig. 1.4 : Variable size Arrays

Note : The use of uneven (or, irregular) multidimensional arrays is not recommended for most applications, because it runs contrary to what people expect to find when a multidimensional array is encountered. However, it can be used effectively in some situations. For example, if you need a very large two-dimensional array that is sparsely populated (i.e., one in which not all of the elements will be used), then an irregular array might be a perfect solution.

1.5.2.3 Programs on Array :

P. 1.18 : Given a list of marks ranging from 0 to 100, write a program to compute and print the number of students who have obtained marks.(a) in the range 81 to 100,(b) in the range 61 to 80,(c) in the range 41 to 60,(d) in the range 0 to 40.

Data Structure & Algorithms (M) 1-40 Revisiting Java Programming Construct

Solution :/* Program to compute and print the number of students who have obtained marks in specific

range */import java.io.DataInputStream; // to load DataInputStream classclass OneDArray1{ public static void main(String args[]) {

int student_marks[]= new int[25];int i,n=0,count1=0,count2=0,count3=0,count4=0;DataInputStream in = new DataInputStream(System.in);

try{

System.out.print("Enter no. of student : "); n= Integer.parseInt(in.readLine());for(i=0;i<n;i++){

System.out.print("Enter marks of student ["+(i+1)+"] : ");student_marks[i]= Integer.parseInt(in.readLine());

}}catch(Exception e) { System.out.println("I/O Error"); }

System.out.println();for(i=0;i<n;i++){

if(student_marks[i]>=81&&student_marks[i]<=100){ System.out.println("Student["+(i+1)+"] obtained marks between 81

to 100");count1++;

}if(student_marks[i]>=61&&student_marks[i]<=80){

System.out.println("Student["+(i+1)+"] obtained marks between 61 to 80");

count2++;}

Data Structure & Algorithms (M) 1-41 Revisiting Java Programming Construct

if(student_marks[i]>=41&&student_marks[i]<=60){

System.out.println("Student["+(i+1)+"] obtained marks between 41 to 60");

count3++;}if(student_marks[i]>=0&&student_marks[i]<=40)

{ System.out.println("Student["+(i+1)+"] obtained marks between 0 to

40"); count4++;

}}

System.out.println("\nTotal no. of students who obtained marks between 81 to 100 :"+count1);

System.out.println("Total no. of students who obtained marks between 61 to 80 :"+count2);

System.out.println("Total no. of students who obtained marks between 41 to 60 :"+count3);

System.out.println("Total no. of students who obtained marks between 0 to 40 :"+count4); }}Execution :C:\ javac OneDArray1.javaC:\ java OneDArray1Output :

Enter no. of student : 5Enter marks of student [1] : 99Enter marks of student [2] : 89Enter marks of student [3] : 65Enter marks of student [4] : 45Enter marks of student [5] : 35

Student[1] obtained marks between 81 to 100Student[2] obtained marks between 81 to 100Student[3] obtained marks between 61 to 80Student[4] obtained marks between 41 to 60

Data Structure & Algorithms (M) 1-42 Revisiting Java Programming Construct

Student[5] obtained marks between 0 to 40

Total no. of students who obtained marks between 81 to 100 :2Total no. of students who obtained marks between 61 to 80 :1Total no. of students who obtained marks between 41 to 60 :1Total no. of students who obtained marks between 0 to 40 :1 Refer OneDArray1.java file on CD

Data Structure & Algorithms (M) 1-43 Revisiting Java Programming Construct

P. 1.19 : Write a Program that adds up the individual elements of 2 D Array.

Solution :/* Program that adds up the individual elements of 2 D Array*/class TwoDArray1{

public static void main(String args[ ]){ int i , j , sum ; int elements[ ][ ] = { {0,2,4,6,8,10,12},

{14,16,18,20,22,24,26}, {28,30,32,34,36,38,40} } ;

for ( i = 0,sum = 0 ; i < 3 ; i++) { for (j=0 ; j<7 ; j++) sum = sum + elements[i][j] ; } System.out.println("The result of addition : "+ sum) ; }

}Execution :C:\ javac TwoDArray1.javaC:\ java TwoDArray1Output : The result of addition : 420 Refer TwoDArray1.java file on CD P. 1.20 : Write a Program that displays the marks of 5 subjects of 3 students and

the average of marks for each subject.

Solution :/* Program that display average of marks for each subject*/class TwoDArray2{

public static void main(String args[ ]){

int i , j ;int marks[][] ={ {65,68,75,59,77},

{62,85,57,66,80}, {71,77,66,63,86} } ;

float avg ;

Data Structure & Algorithms (M) 1-44 Revisiting Java Programming Construct

System.out.print("\t\t");for (i = 0 ; i < 5 ; i++)

System.out.print("subj"+(i+1)+"\t");

System.out.println("\n");for (i=0 ; i<3 ; i++){

System.out.print(" student"+(i+1)+"\t");for(j=0 ; j<5 ; j++)

System.out.print(marks[i][j]+"\t");System.out.print("\n");

}System.out.print("\n\nThe Average of each subject is : \n") ;

for (j=0 ; j<5 ; j++){

System.out.print("Subject"+(j+1)+" : ") ;for (i=0,avg=0 ; i<3 ; i++)

avg = avg + (float)marks[i][j] ;avg = avg / 3 ;System.out.print(avg+"\n");

}}

}Execution :C:\ javac TwoDArray2.javaC:\ java TwoDArray2Output :

subj1 subj2 subj3 subj4 subj5 student1 65 68 75 59 77 student2 62 85 57 66 80 student3 71 77 66 63 86

The Average of each subject is :Subject1 : 66.0Subject2 : 76.666664Subject3 : 66.0Subject4 : 62.666668Subject5 : 81.0 Refer TwoDArray2.java file on CD

Data Structure & Algorithms (M) 1-45 Revisiting Java Programming Construct

P. 1.21 : Write a program for matrix Addition.Solution :/* Program for Matrix Addition */class TwoDArray3{

public static void main(String args[ ]){

int i , j;int add[][]= new int[3][3];

int set1[ ][ ] = { {1,3,5},{7,9,11},{13,15,17} } ; int set2[ ][ ] = { {2,4,6},{8,10,12},{14,16,18} } ; System.out.print("The first 3X3 matrix is :\n"); for (i=0 ; i<3 ; i++) { for (j=0 ; j<3 ; j++)

System.out.print(set1[i][j]+"\t");System.out.println(" ");

}System.out.println(" ");System.out.println("The second 3X3 matrix is : ");for (i=0 ; i<3 ; i++)

{ for (j=0 ; j<3 ; j++)

System.out.print(set2[i][j]+"\t"); System.out.println(" "); } System.out.println(" "); for (i=0 ; i<3 ; i++) { for (j=0 ; j<3 ; j++)

add[i][j] = set1[i][j] + set2[i][j] ; } System.out.println("The resultant addition 3X3 matrix is :") ; for (i=0 ; i<3 ; i++) { for (j=0 ; j<3 ; j++)

System.out.print(add[i][j]+"\t"); System.out.println(" "); } }

}Execution :C:\ javac TwoDArray3.javaC:\ java TwoDArray3

Data Structure & Algorithms (M) 1-46 Revisiting Java Programming Construct

Output :

The first 3X3 matrix is :1 3 57 9 1113 15 17

The second 3X3 matrix is :2 4 68 10 1214 16 18

The resultant addition 3X3 matrix is :3 7 1115 19 2327 31 35 Refer TwoDArray3.java file on CD P. 1.22 : Write a program for matrix Multiplication. Solution :/* Program for Matrix Multiplication */class TwoDArray4{

public static void main(String args[ ]){

int i,j,k;int multi[][]= new int[3][4];

int set1[ ][ ] = { {3,5 }, {4,2}, {4,1} } ; int set2[ ][ ] = { {1,2,4,3}, {1,5,3,2}} ; System.out.print("The first 3X2 matrix is :\n"); for (i=0 ; i<3 ; i++) { for (j=0 ; j<2 ; j++)

System.out.print(set1[i][j]+"\t"); System.out.println(" "); } System.out.println(" ");

System.out.println("The second 2X4 matrix is : "); for (i=0 ; i<2 ; i++) { for (j=0 ; j<4 ; j++)

System.out.print(set2[i][j]+"\t");

Data Structure & Algorithms (M) 1-47 Revisiting Java Programming Construct

System.out.println(" "); } System.out.println(" ");

for (i=0 ; i<3 ; i++) {

for (j=0 ; j<2 ; j++) { for (k=0 ; k<4 ; k++)

multi[i][k] += set1[i][j]*set2[j][k] ; } }

System.out.println("The resultant addition 3X4 matrix is :") ; for (i=0 ; i<3 ; i++) { for (j=0 ; j<4 ; j++)

System.out.print(multi[i][j]+"\t"); System.out.println(" "); } }

}Execution :C:\ javac TwoDArray4.javaC:\ java TwoDArray4

Output :

The first 3X2 matrix is :3 54 24 1

The second 2X4 matrix is :1 2 4 31 5 3 2

The resultant addition 3X4 matrix is :8 31 27 196 18 22 165 13 19 14 Refer TwoDArray4.java file on CD

Data Structure & Algorithms (M) 1-48 Revisiting Java Programming Construct

P. 1.23 : Write a program to print a two-dimensional Square Root Table as ahown below, to provide the square root of any number from 0 to 9.9. For example, the value x will give the square root of 3.2 and y the square root of 3.9.

Square Root Table

Number 0.0 0.1 0.2 . . 0.9

0.0

1.0

2.0

3.0 x y

.

.

9.0

Solution :/* Program to print two-dimensional Square Root Table */

import java.text.*; // to include DecimalFormat class

class TwoDArray5{

public static void main(String args[]){

double a[][]= new double[10][10];int i,j;double x,y;DecimalFormat df = new DecimalFormat("0.00"); // formatting

System.out.println("--------Square Root Table--------\n");

for(i=0,x=0.0;i<10;i++,x=x+1.0) for(j=0,y=0.0;j<10;j++,y=y+0.1)

a[i][j] = Math.sqrt(x+y);

for(j=0,y=0.0;j<10;j++,y=y+0.1) System.out.print(" "+df.format(y));

Data Structure & Algorithms (M) 1-49 Revisiting Java Programming Construct

for(j=0;j<10;j++) System.out.print("============");

System.out.println();for(i=0,x=0.0;i<10;i++,x=x+1.0){ System.out.print(x+" | "); for(j=0;j<10;j++)

System.out.print(" "+df.format(a[i][j])); System.out.println();}

}}Execution :C:\ javac TwoDArray5.javaC:\ java TwoDArray5

Output :

--------Square Root Table--------

0.00 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90=================================================================0.0 | 0.00 0.32 0.45 0.55 0.63 0.71 0.77 0.84 0.89 0.951.0 | 1.00 1.05 1.10 1.14 1.18 1.22 1.26 1.30 1.34 1.382.0 | 1.41 1.45 1.48 1.52 1.55 1.58 1.61 1.64 1.67 1.703.0 | 1.73 1.76 1.79 1.82 1.84 1.87 1.90 1.92 1.95 1.974.0 | 2.00 2.02 2.05 2.07 2.10 2.12 2.14 2.17 2.19 2.215.0 | 2.24 2.26 2.28 2.30 2.32 2.35 2.37 2.39 2.41 2.436.0 | 2.45 2.47 2.49 2.51 2.53 2.55 2.57 2.59 2.61 2.637.0 | 2.65 2.66 2.68 2.70 2.72 2.74 2.76 2.77 2.79 2.818.0 | 2.83 2.85 2.86 2.88 2.90 2.92 2.93 2.95 2.97 2.989.0 | 3.00 3.02 3.03 3.05 3.07 3.08 3.10 3.11 3.13 3.15 Refer TwoDArray5.java file on CD

Explanation of TwoDArray5.java :

Data Structure & Algorithms (M) 1-50 Revisiting Java Programming Construct

This program uses the class DecimalFormat, which is used for formatting output. DecimalFormat class is declared in java.text package; hence we need to import this pacakge before using DecimalFormat. P. 1.24 : Write a program, which counts the number of zeros in a Three-

Dimensional array.

Solution :/* Program for Matrix Multiplication */class ThreeDArray{

public static void main(String args[ ]){

int a[][][]={ { {5,0,2}, {0,0,9}, {4,1,0}, {7,7,7}}, { {3,0,0}, {8,5,0}, {0,0,0}, {2,0,9}} };

int count = 0;

for (int i = 0; i < 2; i++) for (int j= 0; j < 4; j++) for (int k = 0; k < 3; k++) if (a[i][j][k]==0) ++count;

System.out.println("This Array has "+count+" zeros.");}

}Execution :C:\ javac ThreeDArray.javaC:\ java ThreeDArray

Output :

This Array has 11 zeros. Refer ThreeDArray.java file on CD

1.6 Input and Output :

1.6.1 Streams :

Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O

Data Structure & Algorithms (M) 1-51 Revisiting Java Programming Construct

system. The same I/O classes and methods can be applied to any type of device. This mean that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams are clean way to deal with input/output without having every part of your code understand the difference between a keyboard and a network, for example. Java implements streams within class hierarchies defined in the java.io package.

Java 2 defines two types of streams :

Byte Streams

Character Streams

Fig. 1.5 : Types of stream

Byte streams :

Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. These classes define several key methods that the other stream classes implement. Two of most important are read( ) and write( ), which, respectively, read and write bytes of data. The input and output stream classes are as shown in Fig. 1.6 and Fig. 1.7.

Fig. 1.6 : InputStream classes

Data Structure & Algorithms (M) 1-52 Revisiting Java Programming Construct

Fig. 1.7 : OutputStream Classes

Character Stream :

Character Streams provides a convenient means for handling input and output of characters. They use Unicode and, therefore, can be 52nternationalised. Also, in some cases, character streams are more efficient than byte steam. Character Streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. These classes define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which read and write character of data, respectively. Character streams were added by Java 1.1. The Reader class hierarchy is given in Fig. 1.8. The Writer class hierarchy is given in Fig. 1.9.

Fig. 1.8 : Reader class hierarchy

Fig. 1.9 : Writer class hierarchy

1.6.2 Predefined Streams :

All Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. System contains three predefined stream variables, in, out, and err. These fields are declared as public and static within System. This means that they can be used by any other part of your program and without reference to a specific System object.

Data Structure & Algorithms (M) 1-53 Revisiting Java Programming Construct

System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. The preceding programs have been using System.out. use of Syatem.in is a little bit more complicated.

1.6.3 Reading Input from Console :

As you have noticed while reading the preceding sections, not much use has been made of I/O in the example programs. Java provides strong, flexible support for I/O as it relates to files and networks. Java I/O system is cohesive and consistent.

In Java whatever value enter from keyword its in String format, hence we need to convert that value as per our requirement.

We may give values to variables interactively through the keyboard using the readLine( ) method as illustrated in following program.

P. 1.25 : Program to illustrate reading input from console. /* Program to illustrate reading input from console */import java.io.DataInputStream; // load class for reading purposeclass ReadDemo{

public static void main(String args[ ]){

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in); int intNumber =0;

float floatNumber = 0.0F;try{

System.out.print("Enter an integer Number :");intNumber = Integer.parseInt(in.readLine());System.out.print("Enter a float Number :");floatNumber = Float.valueOf(in.readLine()).floatValue();

}catch(Exception e) {

System.out.println("I/O Error"); }System.out.println("Integer Number is : "+intNumber);

Data Structure & Algorithms (M) 1-54 Revisiting Java Programming Construct

System.out.println("Float Number is : "+floatNumber);}

}Execution :C:\javac ReadDemo.javaC:\java ReadDemo

Output :

Enter an integer Number : 5Enter a float Number : 25.456Integer Number is : 5Float Number is : 25.456 Refer ReadDemo.java file on CD

Explanation of ReadDemo.java :

Stream :

Java Programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system.

DataInputStream :

An input stream that contains methods for reading the Java standard data types.

import statement :

import statement is similar to #include statement in C. This statement instructs the interpreter to load the DataInputStream class contained in the java.io package. Using import statement, we can have access to classes that are part of other named packages.

Note : You can replace above import statement (i.e. import java.io.DataInputStream) by import java.io.*;. This import statement will load all classes belongs to java.io package.

System.in :

In Java, console input is accomplished by reading from System.in. To obtain a stream that is attached to the console, you wrap System.in in a DataInputStream object.

readLine( ) :

Data Structure & Algorithms (M) 1-55 Revisiting Java Programming Construct

The readLine( ) method (which is invoked using an object of the class DataInputStream) reads the input from the keyboard as a string.

Data Structure & Algorithms (M) 1-56 Revisiting Java Programming Construct

Conversion from String to Number :

String to Integer :

Input entered by keyboard is in the form of String that is converted to primitive integer by using Integer.parseInt( ).

String to Float :

Float.valueOf( ), converts string to float object. And floatValue() converts object to primitive float.

Attention !

We have used the keywords try and catch to handle any errors that might occur during the reading process. Java requires this.

Note : Java does not have a generalized console input method that parallels the standard C function scanf() or C++ input operators.

1.7 Packages :

[ University Exam : May 09 !!! ]

Packages are containers for classes that are used to keep the class name space compartmentalized. Packages are Java’s way of grouping a variety of classes and / or interfaces together. The grouping is usually done according to functionality.

Benefits of Packages :

1. Packages allow you to organize your classes into smaller units ( such as folders ) and make it easy to locate and use the appropriate class file.

2. It helps to avoid naming conflicts. When you are working with a number of classes, it becomes difficult to decide on names of the classes & methods. At times you would want to use the same name, which belongs to another class. Two classes, in two different packages can have the same name. They may be referred by their fully qualified name comprising the package name and the class name.

3. Package, basically hides the classes thus preventing other programs or packages from accessing classes that are meant for internal use only.

4. Packages allow you to protect your classes, data and methods in a larger way than on a class-to-class basis.

1.7.1 Creating a Package :

Creating a package is quite easy: simply include a package command as the first statement in a java source file. Any classes declared within that file will belong to the specified

Data Structure & Algorithms (M) 1-57 Revisiting Java Programming Construct

package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name.

General form for package statement is

package pkg;here pkg is the name of the package. This must be the first statement in a java source

file(except for comments and white spaces). For example:package FirstPackage //package declarationpublic class A{ //class definition

//body}

Here the package name is FirstPackage. The class A is now considered a part of this package. This file would be saved as a file called A.java and located in a directory named FirstPackage. When the source file is compiled, java will create A.class file and store it in the same directory.

Remember that .class file must be located in a directory that has the same name as the package and this directory should be a subdirectory of the directory where classes that will import the package are located. Remember also that the case is significant and therefore the subdirectory name must match the package name exactly.

Java also supports the concept of package hierarchy; this is done by specifying multiple names in a package statement, separated by dots. The general form of a multilevel package statement is

package pkg1[.pkg2[.pkg3]];A package hierarchy must be reflected in the file system of your java development

system. For example: a package is declared as

package java.awt.image;Needs to be stored in java/awt/image, java\awt\image or java:awt:image on your UNIX,

Windows or Machintosh file system, respectively. Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored.

1.7.2 CLASSPATH Environmental Variable :

Assume that you create a class called ‘A’ in a package called ‘FirstPackage’. Since your directory structure must match your packages, you create a directory called FirstPackage and put A.java inside that directory. This results in A.class being stored in the FirstPackage directory. When you try to run A though, the java interpreter reports an error message similar to “cannot find class A”. This is because the class A is stored in FirstPackage package. You cannot refer to it simply as A. You must refer to the class by enumerating its package

Data Structure & Algorithms (M) 1-58 Revisiting Java Programming Construct

hierarchy, separating the packages with dots. This class must now be called as FirstPackage.A. However if you try to use FirstPackage.A, you still receive an error message similar to “can’t find class FirstPackage/A.

The reason is hidden in your CLASSPATH environmental variable. CLASSPATH sets the top of the class hierarchy. The problem is that there is no FirstPackage directory in the current working directory, because you are in FirstPackage directory itself. You have two choices: change directories up one level and try java FirstPackage.A, or add the top of your development class hierarchy to the CLASSPATH environmental variable. Then you will be able to use java FirstPackage.A from any directory, and java will find right .class file.

Let’s see a very simple package example. P. 1.26 : Program to demonstrate how to run a program to stored in Package.package MyPackage;class CD{

String title;int length;boolean avail;

CD(String t, int l,boolean a){

title=t;length=l;avail=a;

}

public void show(){

System.out.println("\nTitle : "+title + "\nLength : " + length + "\nAvail : "+avail );

}}class CDStore{

public static void main(String args[]){

CD cd1=new CD("Jaws", 120, true);CD cd2=new CD("Titanic", 120, true);cd1.show();cd2.show();

}} Refer CDStore.java file on CD

Data Structure & Algorithms (M) 1-59 Revisiting Java Programming Construct

Call this file CDStore.java, and put it in a directory called MyPackage. Next, compile the file. Make sure the resulting .class file is also in the MyPackage. Then try executing the CDStore class , using the following line:

java MyPackage.CDStoreRemember, you will need to be in the directory above MyPackage when you execute the

command, or you have to set CLASSPATH environmental variable correctly. CDStore is now part of the package MYPakage. This means that it cannot be executed by itself. That is, you cannot use this command line:

java CDStoreCDStore must be qualified with its package name.

Output of the above program would be :Title : JawsLength : 120Avail : true

Title : TitanicLength : 120Avail : true

1.7.3 Access Protection :

Java has different types of access specifies namely private, public, protected and no access specifier as discussed in previous chapters. Packages act as containers for clases and class is java’s smallest unit of abstraction. Because of this, java addresses four categories of visibility for class members. As shown in following table.

private No modifier protected public

Same classs Yes Yes Yes Yes

Same packageSubclass

No Yes Yes Yes

Same packageNon-Subclass

No Yes Yes Yes

Different packageSubclass

No No Yes Yes

Different packageNon -Subclass

No No No Yes

Data Structure & Algorithms (M) 1-60 Revisiting Java Programming Construct

Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside its class. When member does not have explicit access specification, it is visible to sub classes as well as to other classes in the same package. This is the default access. If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.

1.7.4 Programs on Packages :

Let’s see an example based on this.The following example shows all combinations of the access control modifiers. This

example has two packages and five classes. The first package called “package1” defines three classes: Protection1, Derived and

Samepackage. The first class defines four int variables in each of the legal protection modes. The variable n is declared with the default protection, n_pri is private, n_pro is protected, and n_pub is public.

Each class in this example will try to access the variables in an instance of this class. The lines that will not compile due to access restrictions are commended out.

The Derived class is a subclass of Protection1 in the same package ,p1. this grants Derived access to every variable in Protection exceptfor n_pri, the private one. The Samepackage class is not a subclass of protection, but is in the same package and also has access to all but n_pri. P. 1.27 : Program to demonstrate access protection.package package1;public class Protection1{

int n=1;private int n_pri=2;protected int n_pro=3;public int n_pub=4;

public Protection1(){

System.out.println("base constructor");System.out.println("n :"+n);System.out.println("n pri :"+n_pri);System.out.println("n pro :"+n_pro);System.out.println("n pub :"+n_pub);

}} Refer Protection1.java file on CD

Data Structure & Algorithms (M) 1-61 Revisiting Java Programming Construct

package package1;

public class Derived extends Protection1{

public Derived(){

System.out.println("derived constructor");

System.out.println("n :"+n);//System.out.println("n pri :"+n_pri);System.out.println("n pro :"+n_pro);System.out.println("n pub :"+n_pub);

}} Refer Derived.Java file on CDpackage package1;

class Samepackage{

Samepackage(){

Protection1 p=new Protection1();System.out.println("same package constructor");

System.out.println("n :"+p.n);//System.out.println("n pri :"+n_pri);System.out.println("n pro :"+p.n_pro);System.out.println("n pub :"+p.n_pub);

}} Refer Samepackage.Java file on CDpackage package1;public class Demo{

public static void main(String args[]){

Protection1 p=new Protection1();Derived d=new Derived();Samepackage s =new Samepackage();

}} Refer Demo.Java file on CD

Data Structure & Algorithms (M) 1-62 Revisiting Java Programming Construct

Execution :

D:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Protection1.javaD:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Derived.javaD:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Samepackage.javaD:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Demo.javaD:\Books\Java\Chap 5\Chap 5 Programs>java package1.Demobase constructorn :1n pri :2n pro :3n pub :4base constructorn :1n pri :2n pro :3n pub :4derived constructorn :1n pro :3n pub :4base constructorn :1n pri :2n pro :3n pub :4same package constructorn :1n pro :3n pub :4 Refer Demo.Java file on CD

Following is the source code for the other package “package2”, the two classess defined in “package2” cover the other two conditions which are affected by access control. The first class, Protection2 , is a subclass of package1.Protection1. This grants access to all of package1. Protection1’s variables except for n_pri (private) and n, the variable declared with the default protection. Finally, the lass OtherPackage has access to only one variable n_pub, which was declared public.

Data Structure & Algorithms (M) 1-63 Revisiting Java Programming Construct

P. 1.28 : Program to demonstrate access protation.package package2;import package1.*;

class Protection2 extends package1.Protection1{

Protection2(){

System.out.println("derived other package constructor");//System.out.println("n :"+n);//System.out.println("n pri :"+n_pri);System.out.println("n pro :"+n_pro);System.out.println("n pub :"+n_pub);

}} Refer Protection2.java file on CDpackage package2;import package1.*;class Otherpackage{

Otherpackage(){

Protection1 p=new Protection1();System.out.println("other package constructor");//System.out.println("n :"+n);//System.out.println("n pri :"+n_pri);//System.out.println("n pro :"+n_pro);System.out.println("n pub :"+p.n_pub);

}} Refer Otherpackage.java file on CDpackage package2;public class Demo{

public static void main(String args[]){

Protection2 p=new Protection2();Otherpackage o =new Otherpackage();

}} Refer Demo.Java file on CD

Data Structure & Algorithms (M) 1-64 Revisiting Java Programming Construct

Execution :

D:\Books\Java\Chap 5\Chap 5 Programs\package2>cd..D:\Books\Java\Chap 5\Chap 5 Programs>javac package2\Protection2.javaD:\Books\Java\Chap 5\Chap 5 Programs>javac package2\Otherpackage.javaD:\Books\Java\Chap 5\Chap 5 Programs>javac package2\Demo.javaD:\Books\Java\Chap 5\Chap 5 Programs>java package2.Demobase constructorn :1n pri :2n pro :3n pub :4derived other package constructorn pro :3n pub :4base constructorn :1n pri :2n pro :3n pub :4other package constructorn pub :4 Refer Demo.Java file on CD

1.7.5 Importing Packages :

Since classes within packages must be fully qualified with their package name or names, it could become tedious to type in the long dot separated package path name for every class you want to use. For this reason, java includes the import statement to bring certain classes, or entire packages into visibility. Once imported, a class can be referred to directly using only its name. If you are going to refer to a few dozen classes in your application, then the import statement will save a lot of typing.

In a java source file, import statements occur immediately following the package statement and before any class definitions. The general form of import statement is :

import pkg1.[pkg2].(classname|*);

here, pkg1 is the name of a top level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot. There is no limit on the depth of a package hierarchy. Finally you specify either an explicit class name or a star(*), which indicates that the java compiler should import the entire package.

Data Structure & Algorithms (M) 1-65 Revisiting Java Programming Construct

Suppose you wish to use a class say My_Class whose location is as follows :

This class can be imported as follows :import My_Package . MySub_Package . My_Class ;

If we wish to use all classes defined in MySub_Package , then we should writeimport My_Package . MySub_Package . * ;

Let us now see some simple programs that will use classes from other packages. package package1;public class ClassA{

public void displayA(){

System.out.println("ClassA");}

} Refer ClassA.java file on CDCompilation :

D:\Books\Java\Chap 5\Chap 5 Programs>javac package1\ClassA.javaThis file should be saved in directory package1. Now compile this file. The resultant

.class file will be stored in the same directory.

Now consider the following file: P. 1.29 : Program to demonstrate importing packages.import package1.ClassA;class PackageTest1{

public static void main(String args[]){

ClassA A=new ClassA();A.displayA();

}} Refer PackageTest1.java file on CD

My_Package

MySub_Package

My_Class

Data Structure & Algorithms (M) 1-66 Revisiting Java Programming Construct

This is a simple program that imports the class ClassA from the package package1. The file should be saved in directory of which package1 is a subdirectory. Now we can run the program and obtain the result.

Execution :

D:\Books\Java\Chap 5\Chap 5 Programs>javac PackageTest1.javaD:\Books\Java\Chap 5\Chap 5 Programs>java PackageTest1ClassA

During the compilation of PackageTest1.java the compiler checks for the file ClassA.class in package1 directory for information it needs, but it doesn’t actually include the code from ClassA.class in the file PackageTest1.class. When the PackageTest1 program is run, java looks for the file PackageTest1.class and loads it using something called class loader. Now the interpreter knows that it also needs the code in the file ClassA.class and loads it as well.

Now let us consider one more program,package package2;public class ClassB{

protected int m=10;public void displayB(){

System.out.println("ClassB");System.out.println("m: "+m);

}}

Compilation :

D:\Books\Java\Chap 5\Chap 5 Programs>javac package2\ClassB.java Refer ClassB.java file on CD

The source file and the compiled file are located in package2 directory.

Program shown below uses classes contained in both the packages and therefore it imports package1 and package2. Note that we have used star instead of explicit class name in importing package2. P 1.30 : Program to explain how to import all classes in a package using ‘*’.import package1.ClassA;import package2.*;

class PackageTest2

Data Structure & Algorithms (M) 1-67 Revisiting Java Programming Construct

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

ClassA A=new ClassA();ClassB B=new ClassB();A.displayA();B.displayB();

}}

Execution :

D:\Books\Java\Chap 5\Chap 5 Programs>javac PackageTest2.java

D:\Books\Java\Chap 5\Chap 5 Programs>java PackageTest2

Output :

ClassAClassBm: 10 Refer PackageTest2.java file on CD

When we import multiple packages it is likely that two or more packages contain classes with identical names. Example :package package1public class Teacher{ ……….}public class Student{ ……….}package package2public class Courses{ ……….}public class Student{ ……….}

Data Structure & Algorithms (M) 1-68 Revisiting Java Programming Construct

We may import and use these packages like :import package1.*;import package2.*;Student s; //create a student object

Since both the packages contain the class Student, compiler cannot understand which one to use and therefore generates an error. In this case, we have to be more explicit about which one we intend to use.import package1.*;import package2.*;package1.Student s1;package2.Student s2;Teacher t;Courses c;

It is also possible to subclass a class that has been imported from another package. This is shown in following program. P 1.31 : Program to explain how a class can be subclassed that has been imported

from another package.import package2.ClassB;class ClassC extends ClassB{

int n=20;void displayC(){

System.out.println("ClassC");System.out.println("m :"+m);System.out.println("n: "+n);

}}class PackageTest3{

public static void main(String args[]){

ClassC C=new ClassC();C.displayB();C.displayC();

}}

Data Structure & Algorithms (M) 1-69 Revisiting Java Programming Construct

Execution :

D:\Books\Java\Chap 5\Chap 5 Programs>javac PackageTest3.java

D:\Books\Java\Chap 5\Chap 5 Programs>java PackageTest3

Output :

ClassBm :10ClassCm :10n : 20 Refer PackageTest3.java file on CD

Note that the variable m has been declared as protected. A subclass in another package can inherit a protected member. It would not have been possible if it has been as either private or default.

1.7.6 Hiding Classes :

When we import a package using asterisk (*), all public classes are imported. However, we may prefer not to import certain classes. That is, we may like to hide these classes from accessing from outside of the package. Such classes should not be declared ‘public’; For example :package package1;public class X{

//body}Class Y{

//body}

Here the class Y is not declared public. It is hidden form outside of the package package1. This class can be seen and used by other classes in the same package. Note that a java source file should contain only one public class and may include any number of non public classes.

Now consider the following code , which imports the package package1 that contains classes X and Y.import package1.*;X obx; //Ok, class X is publicY oby; //not ok class Y is non public

Data Structure & Algorithms (M) 1-70 Revisiting Java Programming Construct

Java compiler would generate an error message for this code because the class Y, which has not been declared public, is not imported and therefore not available for creating its objects.

1.7.7 Java Application Programming Interface Packages :

Java API provides a large number of classes grouped into different packages according to functionality. Following Fig. 1.10 shows the frequently used API packages. Table 1.2 shows the classes that belong to each package.

Fig. 1.10 : Few Java API packages

Table 1.2 : Java’s System packages

Package Name Contents

java.lang These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, string, math functions, threads and exceptions. Basically these are language support classes.

java.util Language utility classes such as vectors, hash tables, random numbers, date etc.

java.io These classes supports input/output. They provide facilities for the input and output of data.

java.awt It contains set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on.

java.net It contains classes for networking. They include classes for communicating with local computers as well as with internet servers.

java.applet It contains classes for creating and implementing applets.

1.7.8 The java.lang Package :

By default, each Java application/applet has access to the java.lang package. Inside java.lang are classes that represent primitive data types (such as int & char), as well as more complex classes. It contains classes pertaining to strings, string buffers, threads, and even the System class from which we obtain out input and output streams. Java.lang is quite extensive,

Data Structure & Algorithms (M) 1-71 Revisiting Java Programming Construct

and some aspects (such as threads) can be confusing for those new to the Java language. Let see frequently used interfaces and classes provided by java.lang package.

Table 1.3 : java.lang package

Interfaces

Cloneable Interface indicating that an object may be copied or cloned.

Runnable Methods for classes that want to run as threads

Classes

Boolean Object wrapper for Boolean values

Byte Object wrapper for byte values

Character Object wrapper for char values

Class Run-time representations of classes

ClassLoader Abstract behaviour for handling loading of classes.

Compiler System class that gives access to the Java compiler

Double Object wrapper for double values

Float Object wrapper for float values

Integer Object wrapper for int values

Long Object wrapper for long values

Math Utility class for math operations

Number Abstract superclass of all number classes (Integer, Float, and so on)

Object Generic object class, at top of inheritance hierarchy

Process Abstract behaviour for processes such as those spawned using methods in the System class

Runtime Access to the Java runtime

SecurityManager Abstract behaviour for implementing security policies

String Character strings

StingBuffer Mutable strings

System Access to Java’s system level behaviour, provided in a platform independent way

Thread Methods for managing threads and classes that run in threads

ThreadDeath Class of object thrown when a thread is asynchronously terminated

ThreadGroup A group of threads

Throwable Generic exception class; all objects thrown must be Throwable.

Data Structure & Algorithms (M) 1-72 Revisiting Java Programming Construct

1.8 True/False Questions :

Q. 1 A variable declared inside the for loop control cannot be referenced outside the loop.

Ans. : True

Q. 2 In a do-while loop, the loop is not executed if the condition is false.

Ans. : False

Q. 3 A class is a template for multiple objects with similar features.

Ans. : True

Q. 4 There cannot be multiple objects with similar features.

Ans. : False

Q. 5 Java always provide default constructor to class.

Ans. : False

Q. 6 The this keyword can be used to return the object a method is operating on.

Ans. : True

Q. 7 Method declared with the keyword static cannot use this.Ans. : True

Q. 8 Arguments can be passed to Java programs by appending them to the command line while running the program.

Ans. : True

Q. 9 Constructors cannot be overloaded like regular methods.

Ans. : False

Q. 10 Objects are passed to a method by use of call-by reference.

Ans. : True

Q. 11 It is perfectly legal to refer to any instance variable inside of a static method.

Ans. : False

Q. 12 We can overload methods with differences only in their return type.

Ans. : False

Q. 13 Members of a class specified as a private are accessible only to the methods of the class.

Ans. : True

Data Structure & Algorithms (M) 1-73 Revisiting Java Programming Construct

Q. 14 A method declared as static cannot access non-static class members.

Ans. : True

Q. 15 A static class method can be invoked outside the class by simply using the name of the method alone.

Ans. : False

Q. 16 Members of the inner class can be used by the outer class.

Ans. : False

Q. 17 Garbage collection only occurs sporadically during the execution of the program. Ans. : True

Q. 18 Any class may inherited by another class in the same package.

Ans. : False

Q. 19 By, default all programs import the java.lang package.

Ans. : True

Q. 20 Java compiler store the .class files in the path specified in CLASSPATH environmental variable.

Ans. : True

Q. 21 User defined packages can also be imported just like the standard packages.

Ans. : True

Q. 22 All the classes in a package can be simultaneously imported using ‘*’.

Ans. : True

Q. 23 All standard clases of java are included within a package called java.lang.Ans. : True

1.9 Multiple Choice Questions :

Q. 1 Which of the following are illegal loop constructs ?

A.

while(int i>0){

i--; other statements;}

Data Structure & Algorithms (M) 1-74 Revisiting Java Programming Construct

B.for( int i = 10,int j=0;i+j>5;i=i-2,j++){ //Body }

C.int i = 10;while(i){ //Body}

D.

int i = 1, sum=0;do { loop statements} while(sum<10||i<5);

Ans. : A and C

Q. 2 Consider the following code :

if(number>=0)

if(number>0)

System.out.println(“Number is positive”);

else

System.out.println(“Number is negative”);

What will be the output if number is equal to 0?

A. Number is negative

B. Number is positive

C. Both A and B

D. None of the aboveAns. : A

Q. 3 Which of the following control expressions are valid for an if statement?

A. An integer expression

B. A Boolean expression

C. Either A or B

D. Neither A nor B

Ans. : B

Data Structure & Algorithms (M) 1-75 Revisiting Java Programming Construct

Q. 4 In the following code snippet, which lines of code contain error?

Line Code

1. int j =0;

2. while(j<10) {

3. j++;

4. if(j==5) continue loop;

5. System.out.println(“j is “+j); }

A. Line 2

B. Line 3

C. Line 4

D. Line 5

E. None of the above

Ans. : A

Q. 5 Consider the following code :

char c = ‘a’;switch(c){

case ‘a’ :System.out.println(“A”);

case ‘b’ :System.out.println(“B”);

default :System.out.println(“C”);

}

For this code, which of the following statements is true?

A. Output will be A

B. Output will be A followed by B

C. Output will be A, followed by B, and then followed by C

D. Code is illegal and therefore will not compile

Ans. : B

Q. 6 Which of the following are overloading the method

int sum (in x,int y) { }

A. int sum(int x, int y, int z)B. float sum(int x, int y)C. int sum(float x, float y)

Data Structure & Algorithms (M) 1-76 Revisiting Java Programming Construct

D. int sum(int a, int b)E. float sum(int x, int y, float z)

Ans. : A, C and E

Q. 7 Which keyword can protect a class in a package from accessibility by the classes outside the package ?

A. private B. protected

C. final D. don’t use any keyword at all (make it default)

Ans. : D

Q. 8 Which of the following are keywords?

A. switch B. integer

C. default D. boolean

E. object

Ans. : A and C

Q. 9 Which of the following keywords are used to control access to a class member?

A) default

B) protected

C) private

D) public

E) interface

Ans. : B, C and D

Q. 10 Which keyword can protect a class in a package from accessibility by the classes outside the package?A. private B. protected

C. final D. don’t use any keyword

Ans. : D

Q. 11 We would like to make a member of a class visible in all sub classes regardless of what package they are in. which one of the following keywords would achieve this?A. private B. protected

C. public D. private protected

Ans. : D

Q. 12 The use of protected keyword to a member in a class will restrict its visibility as follows:A. Visible only in the class and its subclass in the same package

B. Visible only inside the same package

C. Visible in all classes in the same package and subclasses in other packages

D. Visible only in the class where it is declared

Ans. : C

Data Structure & Algorithms (M) 1-77 Revisiting Java Programming Construct

Q. 13 A package is a collection of

A. Classes

B. Interfaces

C. Editing tools

D. Classes and interfaces

Ans. : D

Q. 14 Package p1 contains the following code :package p1public class Student {

//Body of student}class Test{

//Body of test}

Now consider the following code:import p1.*;class result{

Student s1;Test t1;

}

This code will not compile because

A. Class result should be declared public.

B. Student class is not available

C. Test class is not available

D. Result body is not fully defined.

Ans. : C

1.10 Debugging Exercises :

Q. 1 Following code should compare the value of a variable with the expected value and print appropriate message. What should you modify in the code to obtain the expected message ?

class CheckValue{

public static void main(String args[ ])

Data Structure & Algorithms (M) 1-78 Revisiting Java Programming Construct

{int i =2;if(i=2){

System.out.println("Correct Value");}else{

System.out.println("Incorrect Value");}

}}

Ans. : Condition for if is comparison statement not assignment statement. Following program shows the corrected version :class CheckValue{

public static void main(String args[]){

int i =2;if(i==2) {

System.out.println("Correct Value");}else{

System.out.println("Incorrect Value");}

}}

Output :

Correct ValueQ. 2 What is wrong with the following code ?

switch(x){

case 1:n1=10;n2=20;

Data Structure & Algorithms (M) 1-79 Revisiting Java Programming Construct

case 2 :n3=30;break;n4=40;

}

Ans. : n = 40; is unreachable.Q. 3 What is problem with the following snippet ?class Q3{

public static void main(String args[ ]){

int i=5, j = 10;if ((i<j) || (i=10))

System.out.println(“OK”);System.out.println(“NOT OK”);

}}

Ans. : Problem with the statement (i = 10), that is not comparison statement, its assignment statement. Q. 4 What will be the output of the following code snippet ?

int x = 10;int y = 20;if((x<y)||(x=5)>10) System.out.println(x);else System.out.println(x);

Ans. : Output is : 10Q. 5 Show the output of the following code :int a, b;a = 5;b = 10;if(a>5) if(b>5) { System.out.println(“b is “+b); }

else System.out.println(“a is “+a);

Ans. : Output is : a is 5.

Data Structure & Algorithms (M) 1-80 Revisiting Java Programming Construct

Q. 6 State the output of the following code :

int a = 10;int b = 5;if(a>b){ if(b>5) System.out.println(“b is “+b);}else System.out.println(“a is “+a); Ans. : No output

Q. 7 What will be the output of the following code ?

int m = 100;int n = 300;while(++m < --n);

System.out.println(m);

Ans. : Output is : 200.

Q. 8 Give the output of the following code :

int m = 100;while(true){ if(m<10) break; m = m – 10;}System.out.println(“ m is “+m); Ans. : Output is : m is 0.

Q. 9 Give the output of the following code :int m = 100;while(true){ if(m<10) continue; m = m – 10;}System.out.println(“ m is “+m);

Ans. : No output, infinite loop.

Data Structure & Algorithms (M) 1-81 Revisiting Java Programming Construct

Q. 10 Show the exact output that would be produced by the following main( ) routine :

public static void main(String args[ ]){

int N;N = 1;while (N <= 32){

N = 2 * N;System.out.println(N);

}}

Ans. : The exact output printed by this program is :248163264

(The hard part to get right is the 64 at the end. The value of N doubles each time through the loop. For the final execution of the loop, N starts out with the value 32, but N is doubled to 64 before it is printed.)

Q. 11 Show the exact output produced by the following main() routine :

public static void main(String args[ ]) { int x,y; x = 5; y = 1; while (x > 0) { x = x - 1; y = y * x; System.out.println(y); } }

Ans. : The way to answer this question is to trace exactly what the program does, step-by-step. The output is shown below on the right. On the left is a table that shows the values of the variables x and y as the program is being executed.

Data Structure & Algorithms (M) 1-82 Revisiting Java Programming Construct

value of x value of y Output

5 1 [ before loop] -

4 4 [ = 1*4 ] 4

3 12 [ = 4*3 ] 12

2 24 [ = 12*2 ] 24

1 24 [ = 24*1 ] 24

0 0 [ = 24*0 ] 0

Q. 12 Debug the given code for displaying the numbers 1 to 10 using do-while loop.

class DoWhile{

public static void main(String args[]){

int num=1;do{

System.out.println(num);num++;

}while(num>=10);}

}

Ans. : Following Program will display the numbers 1 to 10 :

class DoWhile{

public static void main(String args[]){

int num=1;do{

System.out.println(num);num++;

}while(num<=10); }

}

Data Structure & Algorithms (M) 1-83 Revisiting Java Programming Construct

Output :

12345678910

Q. 13 Correct the code to rectify the compile time error thrown.

class ForLoop{

public static void main(String args[ ]){

int num=10;for(num>=1){

num=num-1;System.out.println(num);

}}

}

Ans. : Above program will give compile time error, so corrected version of above program is given below :

class ForLoop{

public static void main(String args[ ]){

int num=10;for( ;num>=1; ){

num=num-1;System.out.println(num);

}}

}

Data Structure & Algorithms (M) 1-84 Revisiting Java Programming Construct

Q. 14 Program for calculating factorial of a number has been written using for loop. Correct the code.

class Factorial{

public static void main(String args[ ]){

int num=0,fact=1;for(int num=5;num>=1;num--){

fact*=num;}System.out.println("Factorial of 5 is :"+fact);

}}

Ans. : Above program will give following compile time error :Factorial.java:6: num is already defined in main(java.lang.String[ ]) for(int num=5;num>=1;num--) ^

Corrected version is given below :

class Factorial{

public static void main(String args[ ]){

int fact=1;for(int num=5;num>=1;num--){

fact*=num;}System.out.println("Factorial of 5 is :"+fact);

}}

Q. 15 Using a single line of code, complete the following class so that it returns x+y if the value of x is equal to y, otherwise returns 0 :

public class Q15{ public return int function(int a, int b)

Data Structure & Algorithms (M) 1-85 Revisiting Java Programming Construct

{ ………….(one line code her) }}

Ans. :

public class Q15{ public return int function(int a, int b) { return(x==y)?x+y:0; // added code }}

Q. 16 State the output of the following program :

class Q16{

public static void main(String args[ ]){

int x =10;int y =15;System.out.println((x>y)?3.14:3);

}}Ans. : Output is : 3.0

Q. 17 What will be the following program produce ?

class Q17{

public static void main(String args[ ]){

short s1=3; //0000 0011short s2=13; //0000 1101

s1=(short) (s1^s2);System.out.println("Result is "+s1);

}}

Ans. : Output is : Result is 14.

Data Structure & Algorithms (M) 1-86 Revisiting Java Programming Construct

Q. 18 Consider the class definition :

class Default{

public static void main(String args[ ]){

int m;System.out.println("m is = "+m);

}}

Will this code compile ? YES or NO. Give reason, if NO.

Ans. : No.

Above program will give compile time error that is given below :Default.java:6: variable m might not have been initialized System.out.println("m is = "+m); ^

Q. 19 Consider the following class definition :

class Square{

private square() { }int area (int side){

return(side*side);}

}class Constructor{

public static void main(String args[ ]){

Square S1=new Square();int area = S1.area(10);System.out.println(area);

}}

Will the code above compile and run successfully. YES or NO. Give reason, if NO.

Ans. : No, because constructor of the class is not declared property, constructor name should be same as class Name.

Data Structure & Algorithms (M) 1-87 Revisiting Java Programming Construct

Above program will give compile time error that is given below :Square.java:3: invalid method declaration; return type required private square() { } ^

Q. 20 Consider the following program :

class Number{

int x;void store(Number num){

num.x++;}

}class MainNumber{

public static void main(String args[]){

Number n = new Number();n.x=10;n.store(n);System.out.println(n.x);

}}

What is the output ?

Ans. : Output is : 11.

Q. 21 Given the code :

class Continue{

public static void main(String args[ ]){

int m = 0;loop1: for(int i=0;i<10;i++) loop2: for(int j=0;j<10;j++) loop3: for(int k=0;k<10;k++)

{ System.out.println(++m);

Data Structure & Algorithms (M) 1-88 Revisiting Java Programming Construct

if(k%10)==0)continue loop2;

}}

}

What is the last value printed ?

Ans. : Output is : 100

Q. 22 The following code results in compile time error. Identify the error.

public static void display(x){

int y;if(x>10){

y=x;}System.out.println(" value of y= "+y);

}

Ans. : Above program will give following compile time error : <identifier> expected public static void display(x) ^

Hence we can modified above program as :public static void display(int x){

int y = 0;if(x>10){

y=x;}System.out.println(" value of y= "+y);

}

Q. 23 What will be the output of the following program when it is executed with the command line – java Command Have a Good Day!

class Command{

public static void main(String args[ ])

Data Structure & Algorithms (M) 1-89 Revisiting Java Programming Construct

{for(int i =1;i<args.length;i++){

System.out.print(args[i]); if(i!=args.length) System.out.print(" ");

}System.out.print(" ");

}}

Ans. : Output is : a Good Day !

Q. 24 Consider following application :

class Max{

public static void main(String args[ ]){

int max=10;max(max,20,30);System.out.println(max);

}static void max(int max,int x1,int x2){

if(x1>x2)max=x1;

elsemax=x2;

}}

Ans. : Output is : 10.

Q. 25 State the output of the following program :

class Recur{

public static void main(String args[ ]){

int Result=result(10);System.out.println("Result = "+Result);

}

Data Structure & Algorithms (M) 1-90 Revisiting Java Programming Construct

static int result(int m){

if(m<=2)return m;

elsereturn m+result(m-2);

}}

Ans. : Output is : 30.

Q. 26 Consider the following code :

class Q10{

public static void main(String args[]){

int x = 10,y=20;System.out.rintln(multi(x,y));

}

int multi(int a,int b){

return(a*b);}

}

Will it compile ? YES or NO. Give reason, if NO.

Ans. : No.

Reason : The static method trying to invoke a non-static method.

Q. 27 What will the output of the following program ?

class Static{

static int m=0;static int n=0;public static void main(String args[ ]){

int m = 10;int x = 20;{

int n = 30;

Data Structure & Algorithms (M) 1-91 Revisiting Java Programming Construct

System.out.println("m + n = "+(m+n));}x = m+n;System.out.println("x = "+x);

}}

Ans. : Output is : m + n = 40

x = 10

Q. 28 What is problem with the following Program ?

class Outer{

int outer_x =500;void show(){

Inner i = new Inner();i.display();

}// this is an inner classclass Inner{

int y = 100;void display(){

System.out.println(" Display variable 'x' of outer class = "+outer_x);}

}void showy(){

System.out.println(y);}

}class Q28{

public static void main(String args[ ]){

Outer o=new Outer();o.show();

}}

Data Structure & Algorithms (M) 1-92 Revisiting Java Programming Construct

Ans. :

This Program will give Compile time error, because y is declared as an instance variable of Inner. That means y is local to Inner class. Thus it is not known outside of that class and it cannot be used by showy().

Q. 29 Will this program compile? If no, give reason.

import java.awt.*;import java.io.*;package studentBase;class Test{

void display(){

System.out.println("results");}

}

Ans. : No, the package definition must come first.

Q. 30 The class given below has been saved in the folder “circle”. Will the program run?

package Circle;class NewCircle{

public void draw( ){}public void getRadius( ){}public static void main(String args[]){

System.out.println("Package creation done");}

}

Ans. : This program will not run because it has been saved in folder “circle” which is wrong. Java is case sensitive language. Package name should exactly match with the directory name. So the program should be saved in folder “Circle”.

Data Structure & Algorithms (M) 1-93 Revisiting Java Programming Construct

Q. 31 The code uses the class defined abive. Class ImportClass is not defined in Circle folder. Will the code run without giving any errors ?

import Circle.NewCircle;class ImportClass{

public static void main(String args[]){

Circle.NewCircle nc=new Circle.NewCircle();System.out.println("Hi.......");

}}

Ans. : Yes, the program will run.

Q. 32 The method draw() in NewCircle has been set as private.Class SamePackage is in the same package as NewCircle. Will the class be able to use this method ?

package Circle;import Circle.NewCircle;class samePackage{

public static void main(String args[]){

NewCircle nc=new NewCircle();nc.draw( );

}}

Ans. : The class samePackage will not be able to use draw() method because it has been declared private in class Circle.

Q. 33 Importing a complete package with all its classes has been demonstrated in the program. Will the class compile ?

import Circle;class ImportClass{

public static void main(String args[]){

Circle.NewCircle nc=new Circle.NewCircle();System.out.println("Hi.......");

}}

Data Structure & Algorithms (M) 1-94 Revisiting Java Programming Construct

Ans. : This program will not compile because import statement is wrong. It should be written like this :

import Circle.*;

1.11 Programs :

Program 1 : Write a program for Fibonacci series. The Fibonacci series is given as,0, 1, 1, 2, 3, 5, 8, 13, 21, . . . . . .(Hint : We will see how this series is developed. Observe the first two elements in the series. They are 0 and 1. The third element is 1 which is the addition of the first two elements (0 + 1). The fourth element is the addition of the second and the third numbers (3 = 2 + 1). Thus, in general a n th element is the sum of the previous two elements in the series i.e. (n – 1) and (n – 2). )

Solution : /* Program to implement Fibonacci series*/class P1{

public static void main(String args[ ]){

int x , y , z = 0 ;System.out.println("The Fibonacci Series :\n");System.out.println("====================\n");System.out.println("0\n1");

for (x=0,y=1 ; y<1000 ; x=z){

z = y ;y = x + y ;System.out.println(y);

}}

}Execution :C:\javac P1.javaC:\java P1

Data Structure & Algorithms (M) 1-95 Revisiting Java Programming Construct

Output :

The Fibonacci Series :====================

011235813213455891442333776109871597 Refer P1.java file on CD

Program 2 : The factorial of an integer m is the product of consecutive integers from 1 to m. That is factorial m = m! = m*(m-1)*…*1. Write a program to calculate factorial of given number.

Solution : /*Program to calculate factorial of given number*/

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

int i , number , factorial ; number = 7;

Data Structure & Algorithms (M) 1-96 Revisiting Java Programming Construct

for (i=1,factorial=1 ; i<=number ; i++)factorial = factorial * i ;

System.out.println("The factorial of "+number+" : "+factorial); }}Execution :C:\javac P2.javaC:\java P2

Output :

The factorial of 7 : 5040 Refer P2.java file on CD

Program 3 : Program to display first 10 even numbers and their squares.

Solution : /*Program to display first 10 even numbers and their squares*/

class P3{

public static void main(String args[ ]){

int n ,count=1;System.out.println("First 10 even numbers and their squares:\n");System.out.println("\nNumber\tSquare\n");for (n=2 ;count<=10; n=n+2){

System.out.println(n+"\t"+(n*n));count++;

}}

}

Execution :

C:\javac P3.javaC:\java P3

Data Structure & Algorithms (M) 1-97 Revisiting Java Programming Construct

Output :

Number Square2 44 166 368 6410 10012 14414 19616 25618 32420 400 Refer P3.java file on CD

Program 4 : Program to calculate nPr and nCr (i.e. Permutation and Combination)

(Hint : The value of nPr and nCr is given as,nPr =

and nCr =

So, first we will have to calculate the three factorial values : n !, r ! and (n – r) ! )

Solution : /*Program to compute Permutation and Combination */class P4{

public static void main(String args[ ]){

int i , n , r , P , C ;int factorial , temp , result ;

n = 6; r=3;

for (i=1,factorial=1 ; i<=n ; i++) /* Calculate n! */factorial = factorial * i ;

for (i=1,temp=1 ; i<=r ; i++) /* Calculate r! */temp = temp * i ;

Data Structure & Algorithms (M) 1-98 Revisiting Java Programming Construct

for (i=1,result=1 ; i<=(n-r) ; i++) /* Calculate (n-r)!*/result = result * i ;

P = factorial / temp ;C = P / result ;

System.out.println(" Permutation : "+P);System.out.println(" Combination : "+C);

}}Execution :C:\javac P4.javaC:\java P4

Output :

Permutation : 120Combination : 20 Refer P4.java file on CD

Program 5 : Program to find roots of quadratic equation.

Solution : /* Program to compute roots of quadratic equation */class P5{

public static void main(String args[]){

double a , b , c , d , e ;double temp , r1 , r2 ;int select ;

a=2;b=3;c=6;temp = (b * b) - (4 * a * c) ;

if (temp > 0)select = 0 ;

elseif (temp == 0)

select = 1 ;

Data Structure & Algorithms (M) 1-99 Revisiting Java Programming Construct

elseselect = 2 ;

switch (select){case 0 :

temp = Math.sqrt (temp) ;r1 = (-b + temp) / (2 * a) ;r2 = (-b - temp) / (2 * a) ;System.out.println("The roots are Real and Unequal.\n");System.out.println("The roots are : "+r1+" "+r2);break ;

case 1 :r1 = -b / (2 * a) ;r2 = r1 ;System.out.println("The roots are Real and Equal.\n");System.out.println("The roots are : "+r1+" "+r2);break ;

case 2 :temp = -temp ;temp = Math.sqrt (temp) ;temp = temp / (2 * a) ;r1 = -b / (2 * a) ;System.out.println("The roots are Real and Imaginary.\n");System.out.println("The roots are : "+r1+"+ j"+temp+" , "+r1+"-

j"+temp);break ;

}

}}Execution :C:\javac P5.javaC:\java P5

Output :

The roots are : -0.75+ j1.5612494995995996 , -0.75- j1.5612494995995996 Refer P5.java file on CD

Data Structure & Algorithms (M) 1-100 Revisiting Java Programming Construct

Explanation of P5.java :

Let the quadratic equation be,

(ax2 + bx + c)

So, the coefficients of the quadratic equation are a, b and c.

The roots of any quadratic equation are given as,

x1, x2 =

Here, x1 and x2 are the two roots and a, b and c are the coefficients.

First the value is calculated. Then, the Math.sqrt ( ) function gives the square root of the parameter inside the paranthesis ‘( )’.

(i) If > 0 roots are real and unequal.

(ii) If = 0, roots are real and equal.

(iii) If < 0 , roots are real and imaginary.

For case (i),

x1 , x2 =

For case (ii),

x1 = x2 =

For case (iii),

x1 , x2 = j

Here the if-else statement and the switch statement is utilized.

Program 6 : The triangle of numbers is defined as,1

1 21 2 3

1 2 3 4...

The value of triangular number, corresponds to the value of addition of that row. So, the row number is accepted from user.

The general formula to calculate the triangular number is,

triangular number = where, n is the row number.

Write a program to calculate the value of triangular number.

Data Structure & Algorithms (M) 1-101 Revisiting Java Programming Construct

Solution :/* Program to calculate the value of triangular number*/

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

int n , tri_num ;

n = 6;tri_num = n * (n+1) / 2 ;

System.out.println("The value of the triangular number "+n+" is "+tri_num); }}Execution :C:\javac P6.javaC:\java P6

Output :

The value of the triangular number 6 is 21 Refer P6.java file on CD

Program 7 : To calculate the value of xn without using pow ( ) function. (Read value of x and n from user)

Solution : /* Program to illustrate pow () function and read operation */

import java.io.DataInputStream; // load class for reading purpose

class P7{

public static void main(String args[ ]){

int num , power , result ;

// creating object of class DataInputStream.

Data Structure & Algorithms (M) 1-102 Revisiting Java Programming Construct

DataInputStream in = new DataInputStream(System.in); try{

System.out.print("Enter the base Number :");num = Integer.parseInt(in.readLine());System.out.print("Enter the power :");power = Integer.parseInt(in.readLine());

result= num;for(int i=0;i<power-1;i++){

result =result*num;} System.out.println(" Result is : "+result);

}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P7.javaC:\java P7

Output :

Enter the base Number : 4Enter the power : 3Result is : 64

Note : This program might give some Note at compile time , ignore it and execute your program.

Refer P7.java file on CD

Program 8 : Write a program to check whether entered character is lower case, upper case, numeric or symbol using if-else only.

(Hint : The character is,

(i) Lower case if it lies between ‘a’ to ‘z’,

(ii) Upper case if it lies between ‘A’ to ‘Z’,

(iii) Numeric if it lies between ‘0’ to ‘9’

If the character does not lie in any of the three ranges, then it is a symbol. )

Data Structure & Algorithms (M) 1-103 Revisiting Java Programming Construct

Solution : /*To check whether entered character is lower case, upper case, numeric or symbol using if-else only*/

class P8{

public static void main(String args[ ]){

char c ;

try{

System.out.print("Enter any character :");c = (char)System.in.read( );

if ((c >= 'a') && (c <= 'z'))System.out.print("The character is lower case.\n");

else if ((c >= 'A') && (c <= 'Z'))System.out.print("The character is upper case.\n");

else if ((c >= '0') && (c <= '9'))System.out.print("The character is numeric.\n");

else System.out.print("The character is a symbol.\n");

}catch(Exception e) {

System.out.println("I/O Error"); }

}}Execution :C:\javac P8.javaC:\java P8

Output :

Enter any character : AThe character is upper case.

Data Structure & Algorithms (M) 1-104 Revisiting Java Programming Construct

Enter any character : aThe character is lower case.

Enter any character : 5The character is numeric.

Enter any character : *The character is a symbol. Refer P8.java file on CD

Program 9 : Write a program to check whether entered character is lower case, upper case, numeric or symbol using switch case only.

Solution :/*To check whether entered character is lower case, upper case, numeric or symbol using if-else only*/

class P9{

public static void main(String args[ ]){

char c ;

try{

System.out.print("Enter any character :");c = (char)System.in.read( );

switch (c){case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '9': System.out.println("The character is numeric.");

break ;

Data Structure & Algorithms (M) 1-105 Revisiting Java Programming Construct

case 'a':case 'b':case 'c':case 'd':case 'e':case 'f':case 'g':case 'h':case 'i':case 'j':case 'k':case 'l':case 'm':case 'n':case 'o':case 'p':case 'q':case 'r':case 's':case 't':case 'u':case 'v':case 'w':case 'x':case 'y':case 'z': System.out.println("The character is lower case."); break ;case 'A':case 'B':case 'C':case 'D':case 'E':case 'F':case 'G':case 'H':case 'I':case 'J':case 'K':

Data Structure & Algorithms (M) 1-106 Revisiting Java Programming Construct

case 'L':case 'M':case 'N':case 'O':case 'P':case 'Q':case 'R':case 'S':case 'T':case 'U':case 'V':case 'W':case 'X':case 'Y':case 'Z': System.out.println("The character is upper case.");

break ;default :System.out.println("The character is a symbol");}

}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P9.javaC:\java P9

Output :

Enter any character : BThe character is upper case.

Enter any character : bThe character is lower case.

Enter any character : 14The character is numeric.

Enter any character : &The character is a special character Refer P9.java file on CD

Data Structure & Algorithms (M) 1-107 Revisiting Java Programming Construct

Program 10 : Write a program to compute sum of the digits of a given integer number.Solution :/*Program to compute sum of the digits of a given integer number.*/

import java.io.DataInputStream; // to load DataInputStream class.class P10{

public static void main(String args[ ]){

int num , temp , sum = 0 ;

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

System.out.print("Enter the Number :");num = Integer.parseInt(in.readLine());

do{

temp = num % 10 ;sum = sum + temp ;num = num / 10 ;

}while (num != 0) ;

}catch(Exception e) { System.out.println("I/O Error"); }System.out.println("The sum of individual digits is : "+sum);

}}Execution :C:\javac P10.javaC:\java P10

Output :

Enter the Number : 1234The sum of individual digits is : 10

Note : This program might give some Note at compile time, ignore it and go ahead.

Refer P10.java file on CD

Data Structure & Algorithms (M) 1-108 Revisiting Java Programming Construct

Program 11 : Write a program to find the largest number of the given five numbers.

Solution :/*Program to find the largest number of the given five numbers*/

import java.io.DataInputStream; // to load DataInputStream class class P11{

public static void main(String args[]){

int n1 , n2 , n3 , n4 , n5 , max ;

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

System.out.print("Enter the First Number : ");n1 = Integer.parseInt(in.readLine());System.out.print("Enter the Second Number : ");n2 = Integer.parseInt(in.readLine());System.out.print("Enter the Third Number : ");n3 = Integer.parseInt(in.readLine());System.out.print("Enter the Fourth Number : ");n4 = Integer.parseInt(in.readLine());System.out.print("Enter the Fifth Number : ");n5 = Integer.parseInt(in.readLine());

if (n1 > n2)max = n1 ;

elsemax = n2 ;

if (n3 > max)max = n3 ;

if (n4 > max)max = n4 ;

if (n5 > max)

Data Structure & Algorithms (M) 1-109 Revisiting Java Programming Construct

max = n5 ; System.out.println("The maximum number of the given five numbers is

"+max);}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P11.javaC:\java P11

Output :

Enter the First Number : 25Enter the Second Number : -7Enter the Third Number : 5Enter the Fourth Number : 0Enter the Fifth Number : 1234The maximum number of the given five numbers is 1234

Note : This program might give some Note at compile time, ignore it and go ahead.

Refer P11.java file on CD

Program 12 : Write a program to print.

A B C D C B AA B C B A

A B AA

Solution :/* Program to print A B C D C B A

A B C B AA B A

A */class P12{

public static void main(String args[ ]){

Data Structure & Algorithms (M) 1-110 Revisiting Java Programming Construct

int i=0,j=6,k=0;char x='A';

while((j/2)>=0){

for(i=0;i<=(j/2);i++)System.out.print(" "+((char)(x+i)));

i=i-2;for(;i>=0;i--)

System.out.print(" "+((char)(x+i)));j=j-2;k=k+1;System.out.print("\n");for(i=0;i<=k;i++)

System.out.print(" ");}

}}Execution :C:\javac P12.javaC:\java P12

Output :

A B C D C B AA B C B A

A B AA

Refer P12.java file on CD

Program 13 : Write a program to display months in word. (month number is the input).

/*Program to display months in word*/

import java.io.DataInputStream; // to load DataInputStream class class P13{

public static void main(String args[ ]){ int n=0;

Data Structure & Algorithms (M) 1-111 Revisiting Java Programming Construct

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try {

System.out.print("Enter the Month Number(1-12) : ");n = Integer.parseInt(in.readLine());switch(n)

{case 1:

System.out.println("Month is Jan");break;

case 2:System.out.println(" Month is Feb");break;

case 3:System.out.println("Month is March");break;

case 4:System.out.println("Month is April");break;

case 5:System.out.println("Month is May");break;

case 6:System.out.println("Month is June");break;

case 7:System.out.println("Month is July");break;

case 8:System.out.println("Month is Aug");break;

case 9:System.out.println(" Month is September");break;

case 10:System.out.println(" Month is Oct");

Data Structure & Algorithms (M) 1-112 Revisiting Java Programming Construct

break;case 11:

System.out.println("Month is November");break;

case 12:System.out.println(" month is Dec");break;

default:System.out.println(" Wrong input!!!"); }}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P13.javaC:\java P13

Output :

Enter the Month Number(1-12) : 3Month is March Refer P13.java file on CD

Program 14 : The following set of numbers is called Pascal’s Triangle.

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

If we denote rows by i and columns by j, then any element in the triangle is given by : Pij = Pi-1,j-1 + Pi-1,j.

Solution :/* Program to display Pascal’s Triangle */

class P14{

Data Structure & Algorithms (M) 1-113 Revisiting Java Programming Construct

public static void main(String args[ ]){

int m=0,x,b;do{

x=0;b=1;while(x<=m){

if(m==0||x==0)System.out.print(" "+b);

else{

b=b*(m-x+1)/x; System.out.print(" "+b);

}x=x+1;

}System.out.println("\n");m=m+1;

}while(m<=5);

}}Execution :C:\javac P14.javaC:\java P14

Output :

11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 1

Refer P14.java file on CD

Data Structure & Algorithms (M) 1-114 Revisiting Java Programming Construct

Program 15 : Write a program to display the following pattern

** * *

* * * * ** * *

*Solution :/* Program to display the following pattern *

* * * * * * * *

* * **

*/ class P15{

public static void main(String args[ ]){

int ch,i,j,in=1;

for(i=1;i<=5;i++){

for(j=1;j<=5-i&&i<=3;j++) System.out.print("\t"); //to leave space before stars for upper

triangle

for(j=1;j<=i-1&&i>3;j++) //to leave space before stars for lower triangle System.out.print("\t");

for(j=1;j<=in;j++) //to display stars System.out.print("*\t");

if(i+1<=3)in=in+2; //to decide no of stars in each row

elsein=in-2;

System.out.print("\n");}

Data Structure & Algorithms (M) 1-115 Revisiting Java Programming Construct

}}Execution :C:\javac P15.javaC:\java P15Output :

** * *

* * * * ** * *

* Refer P15.java file on CD

Program 16 : Write a program to check whether the number is an Armstrong number.(Hint : An Armstrong number is one, for which the sum of the cubes of each digit of the number is equal to the number itself.For instance, 153 = (1)3 + (5)3 + (3)3)

Solution :/* Program to check whether the number is an Armstrong number*/

class P16{

public static void main(String args[ ]){ int sum=0,ch,i,j,num,no; no= 153; num=no; do {

sum=sum+(no%10)*(no%10)*(no%10);no=no/10;

} while(no!=0);

if(sum==num) System.out.println("The number "+num+" is an Armstrong number ");

else System.out.println("The number "+num+" is not an Armstrong number

");

Data Structure & Algorithms (M) 1-116 Revisiting Java Programming Construct

}}Execution :C:\javac P16.javaC:\java P16

Output :

The number 153 is an Armstrong number Refer P16.java file on CD

Program 17 : Write a program to display whether a number is prime or not. A prime number is one which is divisible only by 1 itself.

Solution :/* Program to display whether a number is prime or not*/

class P17{

public static void main(String args[ ]){

int i,num;

num = 23;System.out.print(" The Number "+num+" is ");i=2;while(i<=num-1){

if(num%i==0){

System.out.print("Not a prime Number.");break;

}i++;

}if(i==num)

System.out.print("Prime Number.");}

}

Data Structure & Algorithms (M) 1-117 Revisiting Java Programming Construct

Execution :C:\javac P17.javaC:\java P17

Output :

The Number is Prime Number. Refer P17.java file on CD

Program 18 : Write a program to generate all combinations of 1,2 and 3 using for loop.Solution :/* Program to generate all combinations of 1,2 and 3 using for loop */

class P18{

public static void main(String args[ ]){

int i,j,k;

for(i=1;i<=3;i++) for(j=1;j<=3;j++)

for(k=1;k<=3;k++) System.out.println(" "+i+" "+j+" "+k);

}}Execution :C:\javac P18.javaC:\java P18

Output :

1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1

Data Structure & Algorithms (M) 1-118 Revisiting Java Programming Construct

2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3 Refer P18.java file on CD

Program 19 : According to a study, the approximate level of intelligence of a person can be calculated using the following formula :

i = 2 + (y + 0.5x)

write a program, which will produce a table of values of i,y and x , where y varies from 1 to 2 , and , for each value of y, x varies from 5.5 to 12.5 in steps of 0.5.

Solution :/* Program to illustrate the study of approximate level of intelligence of a person */

class P19{

public static void main(String args[ ]){

int y;double i,x;

System.out.println(" i \ty \tx");System.out.println("----------------------");for(y=1;y<=2;y++)

for(x=5.5;x<=12.5;x=x+0.5){

Data Structure & Algorithms (M) 1-119 Revisiting Java Programming Construct

i=2+(y+0.5*x);System.out.println(" "+i+"\t"+y+"\t"+x);

}}

}Execution :C:\javac P19.javaC:\java P19

Output :

i y x

5.75 1 5.5 6.0 1 6.0 6.25 1 6.5 6.5 1 7.0 6.75 1 7.5 7.0 1 8.0 7.25 1 8.5 7.5 1 9.0 7.75 1 9.5 8.0 1 10.0 8.25 1 10.5 8.5 1 11.0 8.75 1 11.5 9.0 1 12.0 9.25 1 12.5 6.75 2 5.5 7.0 2 6.0 7.25 2 6.5 7.5 2 7.0 7.75 2 7.5 8.0 2 8.0 8.25 2 8.5 8.5 2 9.0 8.75 2 9.5 9.0 2 10.0 9.25 2 10.5 9.5 2 11.0

Data Structure & Algorithms (M) 1-120 Revisiting Java Programming Construct

9.75 2 11.5 10.0 2 12.0 10.25 2 12.5 Refer P19.java file on CD

Program 20 : A famous conjecture holds that all positive integers converges to 1 (one) when treated in the following fashion.

Step :

1. If the number is odd, it is multiplied by three and one is added.

2. If the number is even, it is divided by two.

3. Continuously apply above operations to the intermediate results until the number converges to one.

Write a program to read an integer number from keyboard and implement the above mentioned algorithm and display all the intermediate values until the number converges to 1. Also count and display the number of iterations require for the convergence.

Solution :/* Program to display Intermediate values until number converges to 1*/

import java.io.DataInputStream; // to load DataInputStream class

class P20{

public static void main(String args[]){ int x, p = 0, count = 0; boolean exp=true;

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try {

System.out.print("Enter a number : ");x = Integer.parseInt(in.readLine());

while(exp){

Data Structure & Algorithms (M) 1-121 Revisiting Java Programming Construct

if (x%2==0)x=x/2;

elsex=x*3+1;

p=x;count=count+1;System.out.println(" Number After "+count+" iteration is : "+x);if(p!=1)

exp=true;else if (p==1)

exp=false;}

}System.out.println("\nTotal Number of iterations : "+count);

}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P20.javaC:\java P20

Output :

Enter a number : 34 Number After 1 iteration is : 17 Number After 2 iteration is : 52 Number After 3 iteration is : 26 Number After 4 iteration is : 13 Number After 5 iteration is : 40 Number After 6 iteration is : 20 Number After 7 iteration is : 10 Number After 8 iteration is : 5 Number After 9 iteration is : 16 Number After 10 iteration is : 8 Number After 11 iteration is : 4 Number After 12 iteration is : 2 Number After 13 iteration is : 1

Total Number of iterations : 13

Data Structure & Algorithms (M) 1-122 Revisiting Java Programming Construct

Note : This program might give some Note at compile time, ignore it and go ahead.

Refer P20.java file on CD

Data Structure & Algorithms (M) 1-123 Revisiting Java Programming Construct

Program 21 : Write a program to determine the sum of the following harmonic series for a given value of n :

1 + 1/2 + 1/3 + ......+ 1/n

Solution :/*Program to illustrate Harmonic series : 1 + 1/2 + 1/3 + ......+ 1/n */import java.io.DataInputStream; // to load DataInputStream class class P21{

public static void main(String args[ ]){

int n;float temp,sum=0.0F;

// creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

System.out.println("Harmonic series : 1 + 1/2 + 1/3 + ......+ 1/n \n ");try{

System.out.print(" Enter a number : ");n = Integer.parseInt(in.readLine());

for(int i=0;i<n;i++)sum= sum + (float)1/(i+1);

System.out.println("\nHarmonic series for "+n+" is : "+sum);}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P21.javaC:\java P21Output :Harmonic series : 1 + 1/2 + 1/3 + ......+ 1/nEnter a number : 3Harmonic series for 3 is : 1.8333334

Note : This program might give some Note at compile time, ignore it and go ahead.

Refer P21.java file on CD

Data Structure & Algorithms (M) 1-124 Revisiting Java Programming Construct

Program 22 : Write a program that will read the value of x and evaluate the following function,

{ 1 for x > 0y = { 0 for x = 0

{ – 1 for x < 0Using(A) nested if statements(B) else if statements(C) Conditional operator.

Solution :

(A)import java.io.DataInputStream; // to load DataInputStream class

class P22A{

public static void main(String args[ ]){

int x,y;// creating object of class DataInputStream.

DataInputStream in = new DataInputStream(System.in); try{

System.out.print(" Enter a number : ");x = Integer.parseInt(in.readLine());

if(x>=0){

y=1; if(x==0) // nested if y=0;}else

y=-1;System.out.println(" x = "+x+" y = "+y);

}catch(Exception e) { System.out.println("I/O Error"); }

}}

Data Structure & Algorithms (M) 1-125 Revisiting Java Programming Construct

Execution :C:\javac P22A.javaC:\java P22A

Output :

Enter a number : 5 x = 5 y = 1 Refer P22A.java file on CD

(B)

/* Using Conditional Operator */

import java.io.DataInputStream; // to load DataInputStream class class P22B{

public static void main(String args[]){

int x,y;// creating object of class DataInputStream.

DataInputStream in = new DataInputStream(System.in); try{

System.out.print(" Enter a number : ");x = Integer.parseInt(in.readLine());

if(x>0)y=1;

else if(x<0) // else-if laddery=-1;elsey=0;

System.out.println(" x = "+x+" y = "+y);}catch(Exception e) { System.out.println("I/O Error"); }

}}

Data Structure & Algorithms (M) 1-126 Revisiting Java Programming Construct

Execution :C:\javac P22B.javaC:\java P22B

Output :

Enter a number : -5 x = -5 y = -1 Refer P22B.java file on CD

(C)

/* Using Conditional Operator */

import java.io.DataInputStream; // to load DataInputStream class class P22C{

public static void main(String args[ ]){

int x,y;// creating object of class DataInputStream.

DataInputStream in = new DataInputStream(System.in);

try{

System.out.print(" Enter a number : ");x = Integer.parseInt(in.readLine());

y = (x>0)? 1: ( (x<0) ? -1 : 0 ); // conditional operator

System.out.println(" x = "+x+" y = "+y);}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P22C.javaC:\java P22C

Data Structure & Algorithms (M) 1-127 Revisiting Java Programming Construct

Output :

Enter a number : 0 x = 0 y = 0

Note : These programs (P22A.java, P22B.java, P22C.java) might give some Note at compile time, ignore it and go ahead.

Refer P22C.java file on CD

Program 23 : Write a program using class complex to calculate addition of two complex numbers.

Solution :class complex{ float x,y;

complex (){

x=0.0F;y=0.0F;

}complex(float a) {

x=y=a;}complex(float real,float imag){

x=real;y=imag;

}void show(){

System.out.println(x+" + j"+y);}void sum(complex c1,complex c2){

x = c1.x + c2.x;y = c1.y + c2.y;

}}

Data Structure & Algorithms (M) 1-128 Revisiting Java Programming Construct

class P23{

public static void main(String args[ ]){

complex A = new complex(8.7F,2.5F);complex B= new complex(2.6F);complex C= new complex();C.sum(A,B);C.show();

}}Execution :C:\javac P23.javaC:\java P23

Output :

11.299999 + j5.1 Refer P23.java file on CD

Program 24 : Design a class to represent a bank account. Include the following members :

Data members : Name of the depositor Account number Type of account Balance amount in the accountMethods : To assign initial values To deposit an amount To withdraw an amount after checking balance To display the name and balance

Solution :/* Program to represent Bank Account */

import java.io.DataInputStream; // to load DataInputStream class class Bank{

String name,type;

Data Structure & Algorithms (M) 1-129 Revisiting Java Programming Construct

int acno,bal,wit,dep;

// To assign initial valuesvoid getdata(){

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

System.out.print(" Enter Name of Account Holder : ");name=in.readLine();System.out.print(" Enter Type of Account : ");type=in.readLine();System.out.print(" Enter initial amount in Account : ");bal = Integer.parseInt(in.readLine());

}catch(Exception e) { System.out.println("I/O Error"); }

}// To deposit an amountvoid deposit(){

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

System.out.print(" Enter amt to deposit : ");dep = Integer.parseInt(in.readLine());

bal=bal+dep;show();

}catch(Exception e) { System.out.println("I/O Error"); }

}// To withdraw an amount after checking balancevoid withdraw(){

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

Data Structure & Algorithms (M) 1-130 Revisiting Java Programming Construct

try{

System.out.println("\nEnter amt to withdraw : ");wit = Integer.parseInt(in.readLine());if(bal-wit>=500)

bal=bal-wit;else

System.out.println("You cannot withdraw....");show();

}catch(Exception e) { System.out.println("I/O Error"); }

}// To display the name and balancevoid show(){

System.out.println("\nDepositor name :"+name);System.out.println("Type of Account :"+type);System.out.println("Balance :"+bal);

}}class P24{

public static void main(String args[ ]){

int choice;int ans;Bank b1=new Bank();b1.getdata();

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

do{

System.out.println("\n1. Deposit");System.out.println("2. Withdraw");System.out.print("Enter your choice (1/2) :");

Data Structure & Algorithms (M) 1-131 Revisiting Java Programming Construct

choice = Integer.parseInt(in.readLine());

if(choice ==1) b1.deposit();else b1.withdraw();System.out.println("\nDo you want to continue ?(1: yes /0 : No)");ans = Integer.parseInt(in.readLine());

}while(ans==1);}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P24.javaC:\java P24

Output :

Enter Name of Account Holder : KushEnter Type of Account : savingEnter initial amount in Account : 100001. Deposit2. WithdrawEnter your choice (1/2) :1Enter amt to deposit : 5000

Depositor name : KushType of Account :savingBalance :15000

Do you want to continue ?(1: yes /0 : No)11. Deposit2. WithdrawEnter your choice (1/2) :2

Enter amt to withdraw :10000

Data Structure & Algorithms (M) 1-132 Revisiting Java Programming Construct

Depositor name : KushType of Account :savingBalance :5000

Do you want to continue ?(1: yes /0 : No)0

Note : This program might give some Note at compile time, ignore it and run your program.

Refer P24.java file on CD

Program 25 : Modify the above program to incorporate a constructor to provide initial values.

Solution :/* Program to represent Bank Account- Using Constructor */

import java.io.DataInputStream; // to load DataInputStream class

class Bank{

String name,type;int acno,bal,wit,dep;

// To assign initial values by constructorBank(String n, String t,int b){

name=n;type=t;bal=b;

}

// To deposit an amountvoid deposit(){

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

Data Structure & Algorithms (M) 1-133 Revisiting Java Programming Construct

System.out.print(" Enter amt to deposit : ");dep = Integer.parseInt(in.readLine());

bal=bal+dep;show();

}catch(Exception e) { System.out.println("I/O Error"); }

}// To withdraw an amount after checking balancevoid withdraw(){

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try{

System.out.println("\nEnter amt to withdraw : ");wit = Integer.parseInt(in.readLine());if(bal-wit>=500)

bal=bal-wit;else

System.out.println("You cannot withdraw....");show();

}catch(Exception e) { System.out.println("I/O Error"); }

}// To display the name and balancevoid show(){

System.out.println("\nDepositor name : "+name);System.out.println("Type of Account : "+type);System.out.println("Balance : "+bal);

}}class P25{

public static void main(String args[ ]){

int choice;

Data Structure & Algorithms (M) 1-134 Revisiting Java Programming Construct

int ans;Bank b1=new Bank("Stavan","Saving",50000); //providing initial value by

constructor

b1.show();

//creating object of class DataInputStream. DataInputStream in = new DataInputStream(System.in);

try {

do{

System.out.println("\n1. Deposit");System.out.println("2. Withdraw");System.out.print("Enter your choice (1/2) :");choice = Integer.parseInt(in.readLine());

if(choice ==1) b1.deposit();if(choice ==2) b1.withdraw();System.out.println("\nDo you want to continue ?(1: yes /0 : No)");ans = Integer.parseInt(in.readLine());

}while(ans==1);}catch(Exception e) { System.out.println("I/O Error"); }

}}Execution :C:\javac P25.javaC:\java P25

Output :

Depositor name : StavanType of Account : SavingBalance : 50000

1. Deposit

Data Structure & Algorithms (M) 1-135 Revisiting Java Programming Construct

2. WithdrawEnter your choice (1/2) :1Enter amt to deposit : 5000

Depositor name :StavanType of Account :SavingBalance :55000

Do you want to continue ?(1: yes /0 : No)1

1. Deposit2. WithdrawEnter your choice (1/2) :2

Enter amt to withdraw :50000

Depositor name :StavanType of Account :SavingBalance :5000

Do you want to continue ?(1: yes /0 : No)0

Note : This program might give some Note at compile time, ignore it and run your program.

Refer P25.java file on CD

Program 26 : A set of two linear equations with two unknowns x1 and x2 is given below :

ax1 + bx2 = m cx1 + dx2 = n

The set has a unique solution

x1 = x2 =

provided the denominator ad-cb is not equal to zero.

Write a program that will read the values of constants a,b,c,d,m and n and compute the values of x1 and x2. An appropriate message should be printed if ad–cb =0.

Data Structure & Algorithms (M) 1-136 Revisiting Java Programming Construct

Solution :/* Program to compute value of x1 and x2 of linear equations */import java.io.DataInputStream; // to load DataInputStream class class P26{

public static void main(String args[]){

int a=0,b=0,c=0,d=0,m=0,n=0,deno=0;double x1=0.0,x2=0.0;DataInputStream in = new DataInputStream(System.in);

System.out.println(" Two Linear Equations are :");System.out.println("\t ax1 + bx2 = m ");System.out.println("\t cx1 + dx2 = n \n");

try{ System.out.print("Enter a : "); a= Integer.parseInt(in.readLine());

System.out.print("Enter b : ");b = Integer.parseInt(in.readLine()); System.out.print("Enter c : ");c = Integer.parseInt(in.readLine()); System.out.print("Enter d : ");d = Integer.parseInt(in.readLine()); System.out.print("Enter m : ");m = Integer.parseInt(in.readLine()); System.out.print("Enter n : ");n = Integer.parseInt(in.readLine());

}catch(Exception e) { System.out.println("I/O Error"); }

deno = (a*d)-(c*b);if(deno==0)

System.out.println(" Denominator is zero ");else{

x1 = (m*d - b*n)/deno;

Data Structure & Algorithms (M) 1-137 Revisiting Java Programming Construct

x2 = (n*a - m*c)/deno;System.out.println(" x1 = "+(double)x1);System.out.println(" x2 = "+(double)x2);

}}

}Execution : C:\javac P26.java C:\java P26

Output :

Two Linear Equations are : ax1 + bx2 = m cx1 + dx2 = nEnter a : 1Enter b : 2Enter c : 3Enter d : 4Enter m : 5Enter n : 5 x1 = -5.0 x2 = 5.0 Refer P26.java file on CD

Program 27 : Assume that the test results of a batch of students are stored in 4 different classes. Class student stores the roll_number, class test stores the marks obtained in two semesters, class sports stores the score obtained in sports and class result contains the total marks obtained in the test & sports. The class test can inherit roll_number from student and the class result can inherit the details of the marks and roll_number from test using multilevel inheritance. Since multiple inheritances is not possible, class result can implement sports to obtain sports marks.

Design package ‘package1’ to contain classes ‘Student’,’Test’and ‘Result’. Design package ‘package2’ to contain interface Sports. Class ‘Hybrid’ should have the ‘main’ function and it should invoke necessary methods to display result. Don’t put class ‘Hybrid’ in any of these two packages.

The relationship among these classes will be as shown in the following Fig. 1.11.

Data Structure & Algorithms (M) 1-138 Revisiting Java Programming Construct

Fig. 1.11

Solution : This file is stored in package ‘package1’.package package1;public class Student{

int roll_number;public void get_number(int a){ roll_number = a;}public void put_number(){

System.out.println("Roll No. : "+roll_number);}

} Refer Student.java file on CD

This file is stored in package ‘package1’.package package1;public class Test extends Student{

float sem1, sem2;public void get_marks (float s1, float s2){

sem1 = s1;sem2 = s2;

}public void put_marks(){

System.out.println("Marks obtained : ");System.out.println("Sem1 = "+sem1);System.out.println("Sem2 = "+sem2);

}} Refer Test.java file on CD

Data Structure & Algorithms (M) 1-139 Revisiting Java Programming Construct

This file is stored in package ‘package2’.package package2;public interface Sports{ float score=6.0F; void put_score( );} Refer Sports.java file on CD

This file is stored in package ‘package1’.package package1;import package2.Sports;public class Result extends Test implements Sports{

float total;public void display(){

total = sem1 + sem2 + score;put_number( );put_marks( );put_score( );System.out.println("Total Marks : "+total);

}public void put_score(){

System.out.println("Sports weight : "+score);}

} Refer Results.java file on CD

This file is stored in directory one level above the subdirectories ‘package1’ and ‘package2’.import package1.*;import package2.*;

class Hybrid{

public static void main(String args[])

Data Structure & Algorithms (M) 1-140 Revisiting Java Programming Construct

{Result R1=new Result();R1.get_number(123);R1.get_marks(1200,1000);R1.display( );

}}Execution :D:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Student.java

D:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Test.java

D:\Books\Java\Chap 5\Chap 5 Programs>javac package2\Sports.java

D:\Books\Java\Chap 5\Chap 5 Programs>javac package1\Result.java

D:\Books\Java\Chap 5\Chap 5 Programs>javac Hybrid.java

D:\Books\Java\Chap 5\Chap 5 Programs>java HybridRoll No. : 123Marks obtained :Sem1 = 1200.0Sem2 = 1000.0Sports weight : 6.0Total Marks : 2206.0 Refer Hybrid.java file on CD

Review Questions

Q. 1 Explain with suitable example : Declaration of object in Java. (Section 1.1.3)

Q. 2 Explain meaning of following statement :

Student S1 = new Student( );

Student S2 = S1; (Section 1.1.5)

Q. 3 What is a package ? (Section 1.7)

Q. 4 How do we tell java that we want to use a particular package in a file ? (Section 1.7)

Q. 5 How do we design a package? (Section 1.7)

Data Structure & Algorithms (M) 1-141 Revisiting Java Programming Construct

Q. 6 Discuss the various levels of access protection available for packages and their implications. (Section 1.7.3)

Q. 7 What are the benefits of packages ? (Section 1.7)

Q. 8 How do we hide classes using packages ? (Section 1.7.6)

Q. 9 Why is the use of ‘import’ statement? Explain with example. (Section 1.7.5)

Q 10 List all interfaces & classes in java.lang package ? (Section 1.7.8)