oops manual

38
CPE122 manual CPE122 LAB MANUAL

Upload: mufasir-in

Post on 28-Oct-2014

90 views

Category:

Documents


5 download

DESCRIPTION

Java

TRANSCRIPT

CPE122 manual

CPE122LAB MANUAL

CPE122 manual

Introduction to Object Oriented ProgrammingJava is an object-oriented programming language. Object-oriented programming uses objects to mimic real life. Our world is filled with objects that interact with one another. For example, let's consider a class of objects called Car. If I tell you that I just bought a new car, you would have a basic idea of what I purchased. A Car has both characteristics such as make, model, and color, and behaviors such as the ability to start, accelerate and stop. In object-oriented terminology we say, a class describes the characteristics and behaviors that objects of this type have. The class is not the same as the object. Rather, the class is a template from which objects can be created. Therefore, we say an object is an instance of a class. My car is an object that is a specific instance of the class Car. It is a new Car whose make is Mercedes, model is E740 and color is red. I can send messages to my car to invoke its behaviors. For example, inserting a key into the ignition and turning it clockwise sends a message to my car to start. When I want to send a message to my car to accelerate, I step on the gas pedal. Stepping on the brake, sends the message to stop.Let's list some other examples of a class and objects that are created from the class. I'll listthree, and then you can list three.Class ObjectCartoonCharacter Mickey Mouse, Bugs Bunny, Tweedy BirdMovie Star Wars, Gone With the Wind, E.T.

The steps required to develop programs using the Java language.

As a first step, create the programmer using a program called an editor or a utility program or a part of anintegrated software development package. Once the program has been typed, it is saved as a filewith a .java extension in mass storage. This version of the program is known as the source program because it is the initial, or source, version of the program. It is this version to which you will return when corrections or alterations to the program are required.

A program in its source form cannot be executed by the computer. Traditionally, the program source code must first be translated into the machine's low-level language by a program known as a translator or compiler. However, the Java compiler translates the program source into a universal language called Java bytecode. To run a Java program, your computer must have a Java interpreter to interpret each bytecode statement into machine language. To run applets, most browsers contain a Java interpreter, or Java Virtual Machine. To run an application, the computer must have a Java interpreter available elsewhere. Your instructor will explain the details of how to type, save, compile, and finally execute programs using your computer system.

We shall use jcreater an integrated java development environment.Steps1: create source file using Jcreator.Step2: Compile the program using Build File option. Correct errors if any.Step3: Execute the program using Run File option.

Requirements to execute all programs:Computer System with operating system such as windows XP.Java virtual machine, JCreator.

CPE122 manual

Experiment:1 A simple java program.

Aim: To create a simple java program and execute it. Correct errors if any. Investigate use of println() and print method().

Experiment:1.1Create the following java program and execute.

Program 1.1// This is our first Java program.class First{public static void main(String[] args){System.out.println("WELCOME TO ABHA.");System.out.println("WELCOME TO KKU.");}}

Experiment 1.2.Correcting errors.This experiment introduces the compiling process and the manner in which your compiler reports the errors that it finds. Java compilers pinpoint the line where the error has occurred and also display a short error message. It is then up to you to play the part of detective, going back into the source program and searching for the error yourself. Often, one small error can spawn several misleading messages pointing to false errors.A common procedure when looking for errors (or "debugging") is to compile the program againafter correcting the first real error that you find. It often happens that one correction will causeother misleading error messages to disappear.

Step 1. The following document is a simple program in the Java programming language. Usingthe editor in your particular software development environment, type the program as it appears here and save it, for future reference, in a file called First.java . Be careful to include all of the punctuation marks and the braces.// This is our first Java program.class First{public static void main(String[] args){System.out.println("WELCOME TO ABHA.");System.out.println("WELCOME TO KKU.");

}}

CPE122 manual

Step 2. Retrieve the program from Step 1 and compile it. If the compiler finds errors (whichwould be typing errors), correct them and try again. Execute the final, correct program. Whathappens?____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 4. In case you didn't have any typing errors on your first attempt, we'll introduce somenow. Change the word System in the source program to system and try to compile thealtered version. How does your compiler inform you of this error?______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 4. Correct the error introduced in Step 3, and then remove the semicolon from the end ofthe lineSystem.out.println("WELCOME TO ABHA.");Try to compile this altered version. How does your compiler respond?____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 5. Correct the error introduced in Step 4, and then remove the closing brace } at the end ofthe program. Try to compile this altered version. How does your compiler respond?__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 6. Correct the error introduced in Step 5, and then change the spelling of main to maine.Compile and execute the program. What run-time error message did you get?________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

CPE122 manual

__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Experiment 1.3Investigate use print() method.Step1. Modify the original program in Experiment 1.2 to use the method print() instead ofprintln(). Compile and execute the program. How does this output differ from the outputof the original program?System.out.print("WELCOME TO ABHA.");System.out.print("WELCOME TO KKU.");

Step 2. Make a conclusion: What is the difference between println and print?________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Step 3. (Modify the existing program by adding \n inside and at the end of each string. Compileand execute the program. How does the output differ from the output above? How does itdiffer from the output in the original Experiment 1.2?System.out.print("WELCOME TO ABHA.\n");System.out.print("WELCOME TO KKU.\n");

__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Step 4. Add the following lines to the end of the main method. Compile and execute theprogram. How does the output produced by each of these statements differ from the others?System.out.println("1:Chocolate,\nstrawberry, vanilla?");System.out.println("2:Chocolate,\nstrawberry,\nvanilla?");System.out.println("3:Chocolate,\n\nstrawberry,\n\nvanilla?");______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

CPE122 manual

________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 5. What does the \n character combination mean?______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Experiment 1.4Step 1. Replace the statements in the main method of Experiment 1.3 with the singlestatement below. Compile the new program. Record what happens.System.out.println("Oh, I love to "program" in Java");__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Step 2. Correct the statement in Step 1 so that it looks like the first statement below and addthe second statement. Compile and execute the program. Record the results.System.out.println("Oh, I love to \"program\" in Java.");System.out.println("Oh, I love \to \"program\" i\n Java.");____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Step 3. Draw a conclusion: What is the meaning of the backslash mark? What are the meaningsof \" and \t ?__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Experiment 1.5Step1. Replace the statements in the main method in Experiment 1.4 with the statementsbelow. Compile and execute. Record the results.

CPE122 manual

System.out.println("1:Send money quick!"); // To Mom!System.out.println("2:Send money quick!// To Mom!");// To Mom! System.out.println("3:Send money quick!");________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Step 2. Add the following lines to the end of the main method. Compile and record the results.What rule can you derive about the placement of comments?System.out.println("4:Send money quick!" // To Mom!);__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Exercise1.1 Write a program that prints the messageMy name is Hector, I ama vector.I am the subject of many aphysics lecture!

a. all on one lineb. on two linesc. on eight linesd. inside a box drawn with asterisks

1.2 Find the errors in the following program.Class Second{public static main()

CPE122 manual

{System.out println("I like to write before I've read it./n");System.out.println(Then with my pen, I always edit.);System.out.println("But, with computer\s, now I type);System.out.println("And never, ever get it right"\n)}

1.3. What would be the output of the following program?class Empty{public static void main(String[] args){}}

CPE122 manual

Experiment 2. Basic data types.

Aim: to demonstrate use of basic data types and use of variables.

This program declares variables of basic data types such as integer, floating point numbers and character. String is a not a basic data type, it is a class type. Here it is used just to show the data types.

Q) Write a Program to use basic data types.

class Variables

{

public static void main(String[] args)

{

int answer;

int number = 2;

char chr='x';

double fvalue=5.6;

String name="MyName";

answer = number + 3;

System.out.println("charcter is "+chr);

System.out.println("floating point number is"+fvalue);

System.out.println("integer number is is "+number);

System.out.println("charcter is "+name);

}

CPE122 manual

}

Exercise2.1: what is the output of this program

class DataTypes

{

public static void main(String[] args)

{

int num = 2;

Scanner sc=new Scanner(System.in);

double price = 1.89;

String flavor = "chocolate";

System.out.println(num + " scoops of " + flavor + " ice cream");

System.out.println("enter");

}

}

Exercise 2.2: change the values of variables in experiment 2 and assign your own name to the string data type.

Exercise2.3: Create two variables for each of the data types used in the program experiment 2 and display them.

CPE122 manual

Experiment 3: Simple if statement

Aim: To show use of simple if statement and relational operators.

This program find the maximum of two numbers using simple if statement

Program:

class maxtwo{

public static void main(String arg[]){

int a,b;

a=33;

b=23;

if (a<b)

System.out.println("maximum is b");

if (b<a)

System.out.println("maximum is a");

}

}

Exercise3.1: write a program to find minimum of two numbers using simple if statement.

CPE122 manual

Experiment 4: If – else statement

Aim: To show use of if-else statement and relational operators.

This program find the maximum of two numbers using simple if statement

Program:

class maxtwo{

public static void main(String arg[]){

int a,b;

a=33;

b=23;

if (a<b)

System.out.println("maximum is b");

else

System.out.println("maximum is a");

}

}

Exercise4.1: write a program to find minimum of two numbers using if-else statement.

CPE122 manual

Experiment :4.1 Use of Scanner class

Aim: To read the data from key board

This program demonstrate the use of Scanner class to read the data from key board.

Program:

import java.util.Scanner;

class scan

{

public static void main(String args[]){

Scanner sc= new Scanner(System.in) ;

int num1,num2,num3;

System.out.println("enter 1st number");

num1=sc.nextInt();

System.out.println("enter 2nd number");

num2= sc.nextInt();

System.out.println("3rd number");

num3=sc.nextInt();

System.out.println("the numbers are="+num1+", "+num2+","+num3);

}

}

Exercise 4.1: write the program to read only two numbers from key board.

CPE122 manual

Exercise4.2: write the program to read four numbers from key board.

Experiment 5: Maximum of three numbers

Aim: this program demonstrate use of nested If-else stamen and logical operator &.

This program read three numbers from keyboard and finds the maximum of these numbers and display the same.

//program maximum of three numbers.

import java.util.Scanner;

class Max{

public static void main(String arg[])

{

Scanner sc=new Scanner(System.in);

int n1,n2,n3;

System.out.println("enter 1st number");

n1=sc.nextInt();

System.out.println("enter 2nd number");

n2=sc.nextInt();

System.out.println("enter 3rd number");

n3=sc.nextInt();

System.out.println

("the numbers are"+n1+","+n2+","+n3);

if (n1>n2&n1>n3)

System.out.println("max is"+n1);

else if (n2>n3)

System.out.println("max is"+n2);

else System.out.println("max is "+n3);

}

CPE122 manual

}

Exercise5.1: Write a program to find minimum of three numbers.

Experiment 6: For Loop

LOOPS

The purpose of loop statements is to repeat Java statements many times. There are several kinds of loop statements in Java. A loop needs three parts (1)initialization of a variable, (2) testing a condition, and (3) updating a value before the next iteration. The for loop groups these three common parts together into one statement.

Aim: to demonstrate how to use a for loop in a program.

This program find sum of first 5 natural numbers

Program:

class forLoop{

public static void main(String arg[]){

int sum2=10,sum=0, i;

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

sum=sum+sum2;

System.out.println(sum);

sum2=sum;

}

}

}

CPE122 manual

Exercise 6.1 write a program to find sum of first 10 natural numbers using for loop.

Experiment7: While loop

The while statement is used to repeat a block of statements while some condition is true. The condition must become false somewhere in the loop, otherwise it will never terminate.

Aim: to demonstrate the use of While loop in a program

This program find the sum of first 10 natural numbers using While loop. The variable I is first set to zero and it is iteratively increased by one. When I becomes greater than 10 the test condition will become false and loop terminates.

//program sum of first 10 numbers using while loop

class whileloop{

public static void main(String args[]){

int i=0, sum=0;

while (i<=10){

sum=sum+i;

i=i+1;

}

System.out.println(sum);

}

}

Exercise 7.1 write a program to find sum of first 15 natural numbers using while loop.

CPE122 manual

Experiment 8: Do Loop

When you want to test at the end to see whether something should be repeated, the do..while statement is the natural choice. In this loop the condition is tested at the bottom of the body of the statement. At least once the body of the loop is executed even if the test condition is false.

Aim: To demonstrate the use of Do loop in a program.

// program sum of first N numbers using Do loop

import java.util.Scanner;

class DoLoop{

public static void main(String args[]){

Scanner sc= new Scanner(System.in);

int i=0, sum=0,n;

System.out.println("enter value for n");

n=sc.nextInt();

do{

sum=sum+i;

i=i+1;

}while (i<=n);

System.out.println(sum);

}

}

Exercise 8.1 write a program to find sum of first 15 natural numbers using do loop.

CPE122 manual

Experiment 9: Fibonacci series

Aim: to demonstrate the use of for loop for several purposes such as generating a fibbonacci series.

This program generates first five numbers of Fibonacci series.

//program to print first 5 elements of fibbonacci series.

class fibbonacci{

public static void main(String arg[]){

int i, fib1=1, fib2=1, fib;

System.out.println("the fibbonacci series is");

System.out.println(fib1);

System.out.println(fib2);

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

fib=fib1+fib2;

System.out.println(fib);

fib1=fib2;

fib2=fib;

}

}

}

Exercise9.1: write a program to generate first 10 numbers of Fibonacci series.

Exercise9.2: write a program to generate first N numbers of Fibonacci series.

CPE122 manual

Experiment 10 : Nested loops

Aim : To demonstrate use of Nested loops

This program to print numbers in the following pattern

0

1 0

2 1 0

3 2 1 0

4 3 2 1 0

class numbers{

public static void main(String args[]){

int i,j;

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

for(j=i;j>=0;j--)

System.out.print("\t"+j);

System.out.print("\n");

}

}

}

CPE122 manual

Experiment :10.1 Nested loops continued

Aim : To demonstrate use of Nested loops

This program to print the numbers in the following pattern

4

3 4

2 3 4

1 2 3 4

0 1 2 3 4

*/

class nloop2{

public static void main(String args[])

{

int i,j;

for(i=5;i>=0;i--)

{

for (j=i;j<5;j++)

System.out.print("\t"+j);

System.out.print("\n");

}

CPE122 manual

}

}

Experiment 10.2 Nested loops continued

Aim : To demonstrate use of Nested loops

/* Program to print the numbers in the following pattern

0 1 2 3 4

1 2 3 4

2 3 4

3 4

4

class numbers{

public static void main(String args[]){

int i,j,k;

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

for(j=i;j<5;j++)

System.out.print("\t"+j);

System.out.print("\n");

for(k=0;k<=i;k++)

System.out.print("\t");

}

CPE122 manual

}

}

Experiment 10.3 Nested loops continued

Aim : to demonstrate use of Nested loops

This program to print numbers in the following pattern

0 1 2 3 4

1 2 3 4

2 3 4

3 4

4

class numbers{

public static void main(String args[]){

int i,j,k;

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

for(j=i;j<5;j++)

System.out.print("\t"+j);

System.out.print("\n");

for(k=0;k<=i/2;k++)

System.out.print("\t");

}

}

CPE122 manual

}

Experiment 11: CREATING CLASSES AND OBJECTS

Aim: to create objects of a class.

This program creates two objects of class rectangle and compute area of each rectangle and display the same.

// program create class objects,

// create rectagles and compute area

class Rectangle{

int length, width;

Rectangle(int x, int y)

{

length=x;

width=y;

}

int rectArea()

{

return(length*width);

}

}

class rectangleArea{

public static void main(String args[])

{

Rectangle rect1=new Rectangle(15,10);

Rectangle rect2=new Rectangle(10,6);

CPE122 manual

int area1=rect1.rectArea();

int area2=rect2.rectArea();

System.out.println("Area1="+area1+"\t area2="+area2);

}

Experiment 12: Inheritance

Aim: To demonstrate inheritance

This program demonstrate use of inheritance. Program declares a base class Room and a method area(). This program also declares a class BedRoom and a method Volum().which will be child class of Class Room. Then program creates objects of type BedRoom and compute its area and volum.

// program inheritance

class Room{

int length;

int breadth;

Room(int x, int y)

{

length=x;

breadth=y;}

int area()

{ return(length*breadth);

}

}

class BedRoom extends Room

{

int height;

BedRoom(int x, int y, int z)

CPE122 manual

{

super(x,y);

height=z;

}

int volume()

{

return(length*breadth*height);

}

}

class Inhertest

{

public static void main(String arg[])

{

BedRoom room1= new BedRoom(14, 12, 10);

int area1=room1.area();

int volume1=room1.volume();

System.out.println("Area="+area1);

System.out.println("volum="+ volume1);

}

}

Exercise 12.1 write a program to create 2 objects of type BedRoom and find their araeas and volumes for each one.

CPE122 manual

Experiment 13: Method overloading

Aim: this program demonstrate use of method overloading.

This program declares a class with 2 constructors one with one parameter and second with only one parameter.

// program method overloading

class Room{

float length;

float breadth;

Room(float x, float y)

{

length=x;

breadth=y;

}

Room(float x)

{

length=breadth=x;

}

float area()

{

return(length*breadth);

}

CPE122 manual

}

class TestOverload{

public static void main(String arg[]){

Room room1= new Room(25, 15);

Room room2= new Room(20);

float area1=room1.area();

float area2=room2.area();

System.out.println("Area1 = "+area1);

System.out.println("Area2 = "+area2);

}

}

Exercise 13.1 add statements in the above program to create two more objects one object with one parameter and second object with 2 parameters.

CPE122 manual

Experiment 14: Single dimensional array

Aim: To create a single dimensional array

This program creates a single dimensional array of 10 integers.

// Program array of integers

import java.util.Scanner;

class arr{

public static void main(String srgs[])

{

int i;

Scanner sc=new Scanner(System.in);

int a[]=new int[50];

System.out.println("enter 10 numbers");

for(i=0;i<10;i++)

a[i]=sc.nextInt();

System.out.println("the array is");

for (i=0;i<10;i++)

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

}

}

Exercise14.1: write a program to create an array of 5 integers.

Exercise14.2: write a program to create an array of N integers.

CPE122 manual

Experiment: 15 Two dimensional array

Aim: To create a two dimensional array, A matrix.

This program reads nine elements from key board and stores then in a two dimensional array display them in a matrix form.

//program matrix

import java.util.Scanner;

class matrix{

public static void main(String arg[]){

Scanner sc= new Scanner(System.in);

int a[][]= new int[3][3];

int i,j;

System.out.println("enter elements of the matrix");

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

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

a[i][j]=sc.nextInt();

System.out.println("the elements of the array are");

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

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

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

System.out.println("\n");

}

}

CPE122 manual

}

Exercise15.1: write a program to create an 2X2 matrix.

Exercise15.2: write a program to create an MXN matrix.