Object Oriented Programming Lab

I-Semester 2019-10

Lab-1

Q1. Write a C program to define structure of State with fields such as capital, area, population, precipitation, and unique id of a State. Perform the following tasks

a. Create an array of states with at least 10 names

b. Search details about state using capital.

c. Calculate population density of each state=(population/area) and print state name with maximum value of population density.

d. Display the state with minimum precipitation.

Q2. Write a program in Java to print quotient and remainder when user provides divisor and dividend at run time.

Q3. Write a program in Java to print simple interest.

Q4. Write a Java program to reverse a number using while loop.

Other Questions

Note: Pl try to answer as many questions as possible.

I. Find the error in the Java programs if any (assume that the code is not altered)

a.

public class Scope {

public static void main(String args[]) {

int x = 10;

if(x == 10) {

int y = 20;

System.out.println("x and y: " + x + " " + y);

x = y * 2;

}

System.out.println("x and y: " + x + " " + y);

}

}

Error (if any) with reason :______________________________

b. //FileName: OneB.java

public class OneB

{

public static void main(string[] args) {

system.out.println(args[0]);

}

}

Error (if any) with reason :______________________________

II. Find the output of the following program fragments

a.

public class prog3 {

public static void main(String[] args) {

int x = 10, z = 0;

for (;x!=0;) {

z += x;

x /= 2;

System.out.println(z);

}

} // of main

} // of class prog3

Output : ______________________________

b.

public class prog4 {

public static void main(String args[]) {

int x = 10, y = 10;

if(x < y) System.out.println("x is less than y");

x = x * 2;

if(x == y) System.out.println("x now equal to y");

x = x * 2;

if(x > y) System.out.println("x now greater than y");

if(x == y) System.out.println("you won't see this");

}

}

Output: ______________________________________

c.

public class prog2a {

public static void main(String[] args) {

int i = 5;

while (i >= 1) {

int num = 1;

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

System.out.print(num + "AAA");

num *= 2;

}

System.out.println();

i--;

}

}

III. Write Java Programs for the following

a. Write a program which reads a no from the keyboard and check if its divisible by 5, 6. (All possible combinations should be handled.eg. it could be not div by 5 & 6, div by 5 but not 6, or vice versa, or div by 5 & 6)

b. Write a complete Java program that generates the first ‘n’ Fibonacci numbers, where ‘n’ is read as user input.

Eg : Enter n: 6

Output: 1 1 2 3 5 11

c. Write a complete Java program that reads an integer no from the user that computes the sum and prints the value.

Eg no : 12345, output = 15

d. Write a program that reads 3 edges of a triangle and determines if it’s a valid triangle or not. Also classify them as Equilateral, Isosceles, or Scalene triangle.

e. Write a complete Java program to compute the func(x) using the formula

Both x (of type float) and m (of type int) are read as input from the keyboard, the result is to be displayed on the screen.

f. Write a program to read a list of integers from command line and print the no of positive, negative and zeros in the list.

Eg countProg 10 20 -3 4 0 0 -2

Output : positive nos = 3, negative nos = 2, zeros = 2

g. Write a complete Java program that read a series of numbers entered on the command line and displays the maximum, minimum and average of the nos.

Eg. MaxMinSum 1 4 0 -1 3

Output. Max = 4, Min = -1, Avg = 1.4

Lab -2

Q. 1 Write a program to create a class "Rectangle" which has the following:

Data fields : length, width, area, and parameter.(all in float)

constructor: to initialize the length and width of rectangle.

method : calculate_area() calculates area,

calculate_parameter() calculates parameter.

create another class "Main" which contains main method with following functionality

create 2 object of class rectangle

print details of object with greater area and parameter.

Q. 2 Define an “Account” class having

Data fields: Name holder name, Account no, balance.

Constructor: for setting the above fields

Methods: withdrawal, deposit and checkBalance

Define a tester class to test the above account class.

Other Programs

Q. 1 What is the output of the following code?

a)

class T

{

int t = 20;

}

class Main

{

public static void main(String args[])

{

T t1 = new T();

System.out.println(t1.t);

}

}

b)

class T

{

int t = 20;

T()

{

t = 40;

}

}

class Main

{

public static void main(String args[])

{

T t1 = new T();

System.out.println(t1.t);

}

}

Q. 2 Which of the following is/are true about constructors in Java?

1) Constructor name should be same as class name.

2) If you don't define a constructor for a class, a default parameter less constructor is automatically created by the compiler.

3) The default constructor calls super() and initializes all instance variables to default value like 0, null.

4) If we want to parent class constructor, it must be called in first line of constructor.

Q. 3 Is there any compiler error in the below Java program?

class Point {

int m_x, m_y;

public Point(int x, int y)

{

m_x = x;

m_y = y;

}

public static void main(String args[])

{

Point p = new Point();

}

}

Q. 4 What is the output of the following code?

a)

class Point

{

int m_x, m_y;

public Point(int x, int y)

{

m_x = x;

m_y = y;

}

public Point()

{

this(10, 10);

}

public int getX()

{

return m_x;

}

public int getY()

{

return m_y;

}

public static void main(String args[]) {

Point p = new Point();

System.out.println(p.getX());

}

}

b)

final class Complex

{

private double re, im;

public Complex(double re, double im)

{

this.re = re;

this.im = im;

}

Complex(Complex c)

{

System.out.println("Copy constructor called");

re = c.re;

im = c.im;

}

public String toString()

{

return "(" + re + " + " + im + "i)";

}

}

class Main

{

public static void main(String[] args)

{

Complex c1 = new Complex(10, 15);

Complex c2 = new Complex(c1);

Complex c3 = c1;

System.out.println(c2);

}

}

c)

class Test

{

static int a;

static

{

a = 4;

System.out.println ("inside static blockn");

System.out.println ("a = " + a);

}

Test()

{

System.out.println ("ninside constructorn");

a = 10;

}

public static void func()

{

a = a + 1;

System.out.println ("a = " + a);

}

public static void main(String[] args)

{

Test obj = new Test();

obj.func();

}

}

I. Write Java Programs for the following

  1. Define a class CreditCard which has String name, String cardNo, boolean enabled, int pin, String expiryMonth, int cardType, (Platinum, Gold, Silver), int currentCredit, int creditLimit. Provide the following methods. 1. appropriate constructor, 2. changePin(int newPin), 3 transact(int amt), 4 changeCardStatus(boolean status) 5. display()

Note: transact() should check if the card is enabled + pin + credit limit. Further based on the card type an discount is offered. 3% for platinum, 2% for Gold and 1% for Silver.

  1. Write a complete Java program to simulate dice game. The program asks the user to guess a no in the range 1..6. Then it generates a random no (1..6) compares with that guessed by user and displays appropriate messages.

Eg : Input: Please enter your guess: 3

Output: OOPS, Sorry you lost. !!

  1. Define a class Complex containing the real and imaginary parts of the complex no, and member functions add(), sub(), mul(), div(), which work in the normal human semantics.

The class Complex is to be invoked from the ComplexNoTester as follows

public class ComplexNoTester {

public static void main(String[] args) {

Complex c1 = new Complex(1, 3); //1=>real, 3=>imag

Complex c2 = new Complex(“2 + 3i”);

Complex c3 = new Complex(c1);

c1.add(c2); // c1 = c1 + c2;

c1.add(3, 6); // c1 = c1 + complex(3,6);

c4 = c1.add(c3); //c4 = c1 + c3

c1.display();

}

}

Lab-3

Area

Data:

-side1

-side2

Methods:

+calc_Area(int)

+calc_Area(float)

+calc_Area(float,float)

+display()

Note:

1. – indicates private access specifier, + indicates public access specifier

2. +calc_Area(int): a method to calculate area of square which takes one input of type int

Area of square: side * side

3. +calc_Area(float): a method to calculate area of circle which takes one input of type float

Area of circle: 3.14 * radius * radius

4. +calc_Area(float, float): a method to calculate area of rectangle which takes two inputs both of type float

Area of rectangle: side1 * side2

5. +display(): a method to print the calculated area.

Create a class AreaTester to include main method. Create objects of Area in this main method and work on method overloading with switch case:

case 1: calculating area of square.

case 2: calculating area of circle

case 3: calculating area of rectangle

1 $vi AreaTester.java

class Area {

}

public class AreaTester {

public static void main(String[] args) {

// Read Input from user. and test the Area class.

}

}

$javac AreaTester.java

$java AreaTester

Other Programs

I. Find the error(s) in the Java programs if any (assume that the code is not altered)

a.

public class Circle {

private double radius = 1.0;

/** Find the area of this circle */

public double getArea() {

return radius * radius * Math.PI;

}

public static void main(String[] args) {

Circle myCircle = new Circle();

System.out.println("Radius is "+ myCircle.radius);

}

}

Error(s) (if any) with reason :______________________________

II. Find the output of the following programs.

a.

class Count {

public int count;

public Count(int c) {

count = c;

}

public Count() {

count = 1;

}

}

public class Test {

public static void main(String[] args) {

Count myCount = new Count();

int times = 0;

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

increment(myCount, times);

System.out.println("count is " + myCount.count);

System.out.println("times is " + times);

}

public static void increment(Count c, int times) {

c.count++;

times++;

}

}

Output : ______________________________

Why is the increment method declared as static ?

III

Q.1 In a class, one method has two overloaded forms. One form is defined as static and another form is defined as non-static. Is that method properly overloaded?

Q.2 In the below class, is ‘method’ overloaded or duplicated?

public class MainClass

{

void method(int ... a)

{

System.out.println(1);

}

void method(int[] a)

{

System.out.println(2);

}

}

Q.3 Method signature consists of

a) Method Name, Return Type and Number Of Arguments

b) Access Modifier, Method Name and Types Of Arguments

c) Method Name, Number Of Arguments, Types Of Arguments and Order Of Arguments

d) Return Type, Access Modifier and Order Of Arguments

Q. 4 Give the output of the following

class DisplayOverloadingQ4

{

public void disp(char c, int num)

{

System.out.println("I’m the first definition of method disp");

}

public void disp(int num, char c)

{

System.out.println("I’m the second definition of method disp" );

}

}

class Sample

{

public static void main(String args[])

{

DisplayOverloadingQ4 obj = new DisplayOverloadingQ4();

obj.disp('x', 51 );

obj.disp(52, 'y');

}

}

Q. 5 Method Overloading shows dynamic polymorphism. True or false?

Q. 6 What is the output of the following code?


class Demo{

void disp(int a, double b){

System.out.println("Method A");

}

void disp(int a, double b, double c){

System.out.println("Method B");

}

public static void main(String args[]){

Demo obj = new Demo();

obj.disp(100, 20.67f);

}}

IV. Write Java Programs for the following ( Try as many as you can)

a. Create a class named LinearEquation for a system of linear equations:

The class contains:

· Private data fields a, b, c, d, e, and f.

· A constructor with the arguments for a, b, c, d, e, and f.

· get & set methods for a, b, c, d, e, and f.

· A method named isSolvable() that returns true if is not 0.

· Methods getX() and getY() that return the solution for the equation.

Create another class called Line which has

· private data fields x1, y1, x2, y2 (indicating the endpoints of the line)

· A constructor with the arguments for x1, y1, x2, y2.

· A method intersectingPoints(Line anotherLine) to calculate and display the intersecting point of this line with another line anotherLine. (Using class LinearEquation)

The main program used to drive the above classes is as follows

public class LineIntersectionTester {

public static void main(String[] args) {

Line l1 = new Line(x1, y1, x2, y2); //line (x1, y1) – (x2, y2)

Line l2 = new Line(x3, y3, x4, y4); //line (x3, y3) – (x4, y4)

l1.intersctingPoints(l2);

}

}

a. ISBN (International Standard Book Number) consists of 10 digits (d1d2d3d4d5d6d7d8d9d10). The last digit d10 is a checksum, computed from the digits d1..d9 as given below

If d10 is 10, then its treated as ‘X’. Write a complete Java program that reads the first 9 digit ISBN no as a string and generates and displays a new string containing all the 10 digits of the ISBN no.

Eg input : 013601267, output = 0136012671


Lab-4


Q.1 Write a program in Java to print Pascal’s triangle.

1

11

121

1331

14641

Q.2 Write a program in java to multiply two matrices.

Q.3 Write a java program implementing constructor overloading:

A class called Circle is defined as shown in the class diagram. It contains two private member variables: radius (of type double) and color (of type String); and three public member methods: getRadius(), getColor(), and getArea().

Three instances of Circles, called c1, c2, and c3, shall be constructed with their respective data members, as shown in the instance diagrams.

Create three constructors

1. C1: Default constructor

2. C2: Accepts one parameter

3. C3: Accepts both parameters