You are on page 1of 73

PROGRAMMING FUNDAMENTALS

(JAVA)

University of Engineering and Technology


Lahore

i
Dedication

I would like to dedicate this compilation to my first programming teacher Sir


Imran Bajwa. I am thankful to him for developing my interest in this subject
and all my achievements ultimately direct towards him.

Coded By: Ahsan Ijaz & UET students (EE dept.)

Compiled By: Ahsan Ijaz

ii
Contents

TITLE Page No.

BASICS OF JAVA LANGUAGE 1


CLASSES AND OBJECTS 8
WRITING CLASSES 13
CONDITIONALS AND LOOPS 32
OBJECT ORIENTED DESIGN 49
POLYMORPHISM 60
ARRAYS 68

Note: errors and omissions are expected

iii
BASICS OF JAVA LANGUAGE

Q.1 Write a program to print your name, roll no., hobbies, favorite book
and favorite movie?

Ans. public class Name{


public static void main(String[] args){
System.out.println("Name:Ahsan");
System.out.println("DOB:26-03-1996");
System.out.println("Hobbies:Browsing and
Reading");
System.out.println("Favourite Book:Quran Pak");
System.out.println("Favourite Movie: The
Imitation Game");
}
}

Output

> run Name


Name:Ahsan
DOB:26-03-1996
Hobbies:Browsing and Reading
Favourite Book:Quran Pak
Favourite Movie: The Imitation Game
>

Q.2 Write a program to print your favorite quote?

Ans. public class Quote{


public static void main(String[] args){
System.out.println("If you waste time, the time
will waste you");
}
}

Output

> run Quote


If you waste time, the time will waste you
>

Q.3 Write a program to print your favorite quote?

1
Ans. public class Quotation{
public static void main(String[] args){
System.out.println("If you rest, you rust");
}
}

Output

> run Quotation


If you rest, you rust
>

Q.4 Write a program to print average of three numbers?

Ans. import java.util.Scanner;


public class Average{
public static void main(String[] args){
int a,b,c,avg;
Scanner input=new Scanner(System.in);
System.out.println("Enter 1st No.:");
a=input.nextInt();
System.out.println("Enter 2nd No.:");
b=input.nextInt();
System.out.println("Enter 3rd No.:");
c=input.nextInt();
input.close();
avg=(a+b+c)/3;
System.out.println("The Average of Given No.'s
is:"+avg);
}
}

Output

2
Q.5 Write a program to print the entered bio date?

Ans. import java.util.Scanner;


public class Bio{
public static void main(String[] args){
String name,clg,pet;
int age;
Scanner scan=new Scanner(System.in);
System.out.println("Enter your name:");
name=scan.nextLine();
System.out.println("Enter your college name:");
clg=scan.nextLine();
System.out.println("Enter your pet name:");
pet=scan.nextLine();
System.out.println("Enter your age:");
age=scan.nextInt();
scan.close();
System.out.println("Hello, my name is "+name+" and
I am "+ag+" years old.I'm enjoying my time at "+clg
+" though I miss my "+pet+" very much!");
}
}

Output

Q.6 Write a program to print sum difference and product of two numbers?

Ans. import java.util.Scanner;


public class Calc{
public static void main(String[] args){
float a,b,sum,diff,product;
Scanner scan=new Scanner(System.in);
System.out.println("Enter 1st No:");
a=scan.nextFloat();

3
System.out.println("Enter 2nd No:");
b=scan.nextFloat();
scan.close();
sum=a+b;
diff=a-b;
product=a*b;
System.out.println("The Sum of given Numbers
is:"+sum);
System.out.println("The Difference of given
Numbers is:"+diff);
System.out.println("The Product of given Numbers
is:"+product);
}
}

Output

Q.7 Write a program to print cube of a number?

Ans. import java.util.Scanner;


public class cubeofNumber{
public static void main(String[] args){
int a,s;
Scanner scan=new Scanner(System.in);
a=scan.nextInt();
scan.close();
s=a*a*a;
System.out.println("The cube of "+a+" is:"+s);
}
}

4
Output

Q.8 Write a program to print area and perimeter of square?

Ans. import java.util.Scanner;


public class square{
public static void main(String[] args){
float l,w,area,perimeter;
Scanner scan=new Scanner(System.in);
System.out.println("Enter length of square:");
l=scan.nextFloat();
System.out.println("Enter width of square:");
w=scan.nextFloat();
scan.close();
area=l*w;
perimeter=l+w;
System.out.println("The perimeter of square is
:"+perimeter);
System.out.println("The area of square is
:"+area);
}
}

Output

5
Q.9 Write a program to print area of square?

Ans. import java.util.Scanner;


public class squareofNumber{
public static void main(String[] args){
int a,s;
Scanner scan=new Scanner(System.in);
a=scan.nextInt();
scan.close();
s=a*a;
System.out.println("The square of "+a+" is:"+s);
}
}

Output

Q.10 Write a program to print the time equivalent to the time entered in
hour, minute and second format?

Ans. import java.util.Scanner;


public class time{
public static void main(String[] args){
int h,m,s,c;
Scanner scan=new Scanner(System.in);
System.out.println("Enter hours:");
h=scan.nextInt();
System.out.println("Enter minutes:");
m=scan.nextInt();
System.out.println("Enter seconds:");
s=scan.nextInt();
scan.close();
c=(h*60*60)+(m*60)+s;
System.out.println(+h+" hour,"+m+" minutes,and
"+s+" seconds is"+" equivalent to "+c+" seconds");
}
}

6
Output

Q.11 Write a program to print the time required for a trip?

Ans. import java.util.Scanner;


public class trip{
public static void main(String[] args){
int v,d;
float t;
Scanner scan=new Scanner(System.in);
System.out.println("Enter speed of
vehicle(m/s):");
v=scan.nextInt();
System.out.println("Enter distance covered:(m)");
d=scan.nextInt();
scan.close();
t=d/v;
System.out.println("Time required for the
trip:"+t);
}
}

Output

7
CLASSES AND OBJECTS
Q.12 Write a program to print two concatenated strings?

Ans. public class Concat{


public static void main(String[] args){
String a,b,c;
a="Ahsan";
b=" Ijaz";
c=a.concat(b);
System.out.println(""+c);
}
}

Output
> run Concat
Ahsan Ijaz
>

Q.13 Write a program to print the comparison of two strings?


Ans. public class Compare{
public static void main(String[] args){
String a,b;
a="Ahsan";
b="Ijaz";
System.out.println(""+a.compareTo(b));
}
}

Output
> run Compare
-8
>

Q.14 Write a program to print the length of a string?

Ans. public class Length{


public static void main(String[] args){
String a;
a="Ahsan";
System.out.println(""+a.length());
}
}
8
Output
> run Length
5
>

Q.15 Write a program to print the upper case of a string?

Ans. public class ToUpperCase{


public static void main(String[] args){
String a,b;
a="ahsan";
b=a.toUpperCase();
System.out.println(""+b);
}
}

Output
> run ToUpperCase
AHSAN
>

Q.16 Write a program to print product and square of products of three


numbers?

Ans. import java.util.Scanner;


public class ProductSquare{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
float a,b,c,p,s;
System.out.println("Enter 1st Number:");
a=scan.nextFloat();
System.out.println("Enter 2nd Number:");
b=scan.nextFloat();
System.out.println("Enter 3rd Number:");
c=scan.nextFloat();
scan.close();
p=a*b*c;
s=p*p;
System.out.println("The product of Numbers"+p);
System.out.println("The square of product of
Numbers"+s);
}

9
}

Output

Q.17 Write a program to print exponential power of a number?

Ans. import java.util.Scanner;


public class Epower{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
float a;
double p;
System.out.println("Enter a Number:");
a=scan.nextFloat();
scan.close();
p=Math.exp(a);
System.out.println("The number raised to power
/'e/' is"+p);
}
}

Output

10
Q.18 Write a program to print your bio data using graphics?

Ans. import java.awt.*;


import javax.swing.*;
public class Brag
{
public static void main(String[] args)
{
JFrame frame=new JFrame("Question?");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel primary=new JPanel();
primary.setBackground(Color.white);
primary.setPreferredSize(new Dimension(200,250));
JLabel label1=new JLabel("Who is the
Programmer?");
JLabel label2=new JLabel("Ans: Ahsan Ijaz");
JLabel label3=new JLabel(" Reg. No.:2014-EE-
422");
primary.add(label1);
primary.add(label2);
primary.add(label3);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}

Output

11
Q.19 Write a program to print your name using graphics?

Ans. import java.awt.*;


import javax.swing.*;
public class Name{
public static void main(String[] args){
JFrame frame=new JFrame("Name");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//...................................................
JPanel panel=new JPanel();
panel.setBackground(Color.yellow);
panel.setPreferredSize(new Dimension(250,75));

//..................................................
JLabel label1=new JLabel("Ahsan");
panel.add(label1);

//...................................................
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Output

12
WRITING CLASSES

Q.20 Write a class called NumberOfGoals that represents the total number
of goals scored by a football team. The NumberOfGoals class should a
single integer as instance data, representing the number of goals scored.
Write a constructor to initialize the number of goals to zero. Write a
method called setGoal that increments the value by one whenever a goal is
scored, and another method called getGoal that returns the total number of
goals scored so far. Finally, create a driver class called GoalTracker that
creates a few NumberOfGoals objects and tests their methods.

Ans. Counter
public class Counter{
private int coun;
public Counter(){
coun=0;
}
public int click(){
coun++;
return coun;
}
public int getCount(){
return coun;
}
public void setCoun(){
coun=0;
}
public String toString(){
String result=Integer.toString(coun);
return result;
}
}

Driver Class
public class CountTest{
public static void main(String[] args){
Counter c1,c2;
c1=new Counter();
c2=new Counter();
c1.click();
System.out.println(""+c1);
c1.getCount();
System.out.println(""+c1);

13
c1.setCoun();
System.out.println(""+c1);
System.out.println("");
System.out.println("");
c2.click();
System.out.println(""+c2);
c2.getCount();
System.out.println(""+c2);
c2.setCoun();
System.out.println(""+c2);
}
}

Output
> run CountTest
1
1
0

1
1
0
>

Q.21 Write a class called BitValue that represents binary digits that can be
set to true or false. Create a driver class called Bits whose main method
instantiates and sets a few bits to true.

Ans.Bulb
public class Bulb{
private int s;
public Bulb(){
s=0;
}
public void setOn(){
s=1;
}
public void setOff(){
s=0;
}
public int getS(){
return s;

14
}
public String toString(){
String result=Integer.toString(s);
return result;
}
}

Driver Class
public class lights{
public static void main(String[] args){
Bulb b1=new Bulb();
Bulb b2=new Bulb();
b1.setOn();
b2.setOff();
b1.getS();
b2.getS();
System.out.println("b1:"+b1+" Bulb is on");

System.out.println("b2:"+b2+" Bulb is off");


}
}

Output
> run lights
b1:1 Bulb is on
b2:0 Bulb is off
>

Q.22 Write a class called Circle that contains instance data that represents
the circle’s radius. Define the Circle constructor to accept and initialize the
radius, and include getter and setter methods for the radius. Include
methods that calculate and return the circumference and area of the
sphere. Include a toString method that returns a one-line description of the
circle. Create a driver class called MultiCircle, whose main method
instantiates and updates several Circle objects. [Circumference = 2pr and
Area = pr2].

Ans. Sphere
public class Sphere{
private int diameter;
private double a;
private double v;
public Sphere(){

15
diameter=0;
}
public int getDiameter(){
return diameter;
}
public void setDiameter(int newdia){
diameter=newdia;
}
public double surface_area(int d){
int r=d/2;
a=4/3*3.14*(r*r*r);
return a;
}
public double volume(int d){
int r=d/2;
v=4*3.14*(r*r);
return v;}
public String toString(){
String r1=Double.toString(a);
String r2=Double.toString(v);
return "Diameter="+diameter+"
Area="+r1+"Volume="+r2;
}
}

Driver Class
public class Multisphere{
public static void main(String[] args){
Sphere s1=new Sphere();
s1.getDiameter();
s1.setDiameter(4);
s1.surface_area(4);
s1.volume(4);
System.out.println(s1);
}
}

Output
> run Multisphere
Diameter=4 Area=25.12Volume=50.24
>

16
Q.23 Write a class called Dog that contains instance data that represents
the dog’s name and age. Define the Dog constructor to accept and initialize
instance data. Include getter and setter methods for the name and age.
Include a method to compute and return the age of the dog in
“personyears” (seven times the dog’s age). Include a toString method that
returns a one-line description of the dog. Create a driver class called
Kennel, whose main method instantiates and updates several Dog objects.

Ans. Dog
public class Dog{
private String name;
private int age;
public Dog(String na,int ag){
name=na;
age=ag;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public void setAge(int setage){
age=setage;
}
public void setName(String setname){
name=setname;
}
public int compute(){
int dog_age_in_person_years=age*7;
return dog_age_in_person_years;
}
public String toString(){
String a=Integer.toString(age);
String comp=Integer.toString((age*7));
return "Dog Name:"+name+" ,Dog Age:"+a+" ,Dog
Age in Person Years:"+comp;
}
}

Driver Class
public class Kennel{
public static void main(String[] args){

17
int a,b,c,d;
String y,z;
Dog d1=new Dog("abc",1);
Dog d2=new Dog("xyz",2);
//----------------------------------------------
y=d1.getName();
System.out.println("Name of d1:"+y);
a=d1.getAge();
System.out.println("Age of d1:"+a);
b=d1.compute();
System.out.println("d1 Age in Person Years:"+b);
//----------------------------------------------
z=d2.getName();
System.out.println("Name of d2:"+z);
c=d2.getAge();
System.out.println("Age of d2:"+c);
d=d2.compute();
System.out.println("d2 Age in Person Years:"+d);
//---------------------------------------------
d1.setName("xyz");
d1.setAge(2);
d2.setName("abc");
d2.setAge(1);
System.out.println(d1);
System.out.println(d2);
}
}

Output
public class Kennel{
public static void main(String[] args){
int a,b,c,d;
String y,z;
Dog d1=new Dog("abc",1);
Dog d2=new Dog("xyz",2);
//---------------------------------------------
y=d1.getName();
System.out.println("Name of d1:"+y);
a=d1.getAge();
System.out.println("Age of d1:"+a);
b=d1.compute();
System.out.println("d1 Age in Person Years:"+b);
//---------------------------------------------

18
z=d2.getName();
System.out.println("Name of d2:"+z);
c=d2.getAge();
System.out.println("Age of d2:"+c);
d=d2.compute();
System.out.println("d2 Age in Person Years:"+d);
//---------------------------------------------
d1.setName("xyz");
d1.setAge(2);
d2.setName("abc");
d2.setAge(1);
System.out.println(d1);
System.out.println(d2);
}
}

Q.24 Write a class name Car which has make, model and year as instance
variables. Define a constructor which initializes all instance data of Car
class. Write a driver class called CarTest which define various car objects
and also make use of its methods?

Ans. Car Class


public class Car{
private String make,model;
private int year;
public Car(String ma,String mo, int ye)
{
make=ma;
model=mo;
year=ye;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public int getYear(){
return year;
}
public void setMake(String ma){
make=ma;
}

19
public void setModel(String mo){
model=mo;
}
public void setYear(int ye){
year=ye;
}
public boolean isAntique(){
if(2015-year>45)
return true;
else
return false;
}
public String toString(){
String a=Integer.toString(year);
return "Make:"+make+"\t Model:"+model+"\t Year:"+a;
}
}

Main Method
public class CarTest{
public static void main(String[] args){
Car A=new Car("Honda","ford",2010);
Car B=new Car("Toyota","corolla",1970);
System.out.println("Make of car A"+A.getMake());
System.out.println("Model of car
A"+A.getModel());
System.out.println("Year of car A"+A.getYear());
A.setMake("Corolla");
A.setModel("xli");
A.setYear(2012);
System.out.println(A);
System.out.println(B);
if(A.isAntique()==true)
System.out.println("The car is Antique");
else
System.out.println("The car is not Antique");
if(B.isAntique()==true)
System.out.println("The car is Antique");
else
System.out.println("The car is not Antique");
}
}

20
Output
> run CarTest
Make of car AHonda
Model of car Aford
Year of car A2010
Make:Corolla Model:xli Year:2012
Make:Toyota Model:corolla Year:1970
The car is not Antique
The car is not Antique
>

Q.25 Write a class called Box that contains instance data that represents
the height, width, and depth of the box. Also include a Boolean variable
called full as instance data that represents whether box is full or not. Define
the Box constructor that initializes various box objects. Create a driver
class called BoxTest whose main method instantiates and updates several
box objects?

Ans. Box
public class Box
{
private double x,y,z;
private boolean f;
public Box(double hieght,double width,double
depth,boolean materialofbox)
{
x=hieght;
y=width;
z=depth;
f=materialofbox;
}
public double sethieght(double hieght)
{
x=hieght;
return x;
}
public double setwidth(double width)
{
y=width;
return y;

21
}
public double setdepth(double depth)
{
z=depth;
return z;
}
public boolean setmaterialofbox(boolean
materialofbox)
{
f=materialofbox;
return f;
}
public double gethieght()
{
return x;
}
public double getwidth()
{
return y;
}
public double getdepth()
{
return z;
}
public boolean getmaterialofbox()
{
return f;
}
public String toString()
{
return x + "\t" + y + "\t" + z + "\t" + f;
}
}

Main Method
import java.util.*;
public class Boxtest
{

22
public static void main(String[] args)
{
double volume;
Box object=new Box(4.0021,2.11,3.00,true);
System.out.println("the hieght is " +
object.gethieght());
System.out.println("the width is " +
object.getwidth());
System.out.println("the depth is " +
object.getdepth());
System.out.println("the material of box is" +
object.getmaterialofbox());
object.sethieght(2.0038);
System.out.println(object);
volume=
object.gethieght()*object.getwidth()*object.getdepth(
);
System.out.println("the voume is " + volume);
{
if (object.getmaterialofbox()==true)

System.out.println("the box is empty");


else
System.out.println("the box is full");
}
}
}

Output
> run Boxtest
the hieght is 4.0021
the width is 2.11
the depth is 3.0
the material of box istrue
2.0038 2.11 3.0 true
the voume is 12.684054
the box is empty
>

23
Q.26 Write a class name Book that contains Title, Author, Publsiher,
Copyright as instance data. Write a constructor called Book that
instantiates various instance data. Include a toString method that
describes one line description of all objects of the book. Write a driver class
called BookShelf which instantiates various Book objects?

Ans. Book
public class Book{
private String title, author, publisher;
private int copyright;
public Book(String ti,String au,String pu, int co){
title=ti;
author=au;
publisher=pu;
copyright=co;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public String getPublisher(){
return publisher;
}
public int getCopyright(){
return copyright;
}
public void setTitle(String ti){
title=ti;
}
public void setAuthor(String au){
author=au;
}
public void setPublisher(String pu){
publisher=pu;
}
public void setCopyright(int co){
copyright=co;
}
public String toString(){
String a=Integer.toString(copyright);

24
return "Title:"+title+"\t Author:"+a
+"Publisher:"+publisher+"Copyright:"+copyright;
}
}

Driver Class
public class BookShelf{
public static void main(String[] args){
Book b1,b2;
b1=new Book("Linear Algebra","Gilbert
Strang","MIT",1995);
b2=new Book("Applied Physics","Giancolli","Oxford
Publishers",1904);
String a,b,c;
a=b1.getTitle();
System.out.println("Title of book1:"+a);
b=b2.getPublisher();
System.out.println("Publisher of book2:"+b);
c=b2.getAuthor();
System.out.print("Author of book2:"+c);
System.out.println("");
System.out.println("");
System.out.println(b1);
System.out.println(b2);
}
}

Output
> run BookShelf
Title of book1:Linear Algebra
Publisher of book2:Oxford Publishers
Author of book2:Giancolli

Title:Linear Algebra
Author:1995Publisher:MITCopyright:1995
Title:Applied Physics Author:1904Publisher:Oxford
PublishersCopyright:1904
>

Q.27 Write a class called Flight that represents an airline flight. It should
contain instance data that represents the airline name, flight number, and
the flight’s origin and destination cities. Define the constructor to accept

25
and initialize the data. Include a toString method to give one line
description of the flight?

Ans. Flight
public class Flight{
private String name;
private int number;
private String origin;
private String destinationCities;
//-------------------------------------------------
public Flight(String na,int nu,String or,String
deCi){
name=na;
number=nu;
origin=or;
destinationCities=deCi;
}
//-----------------------------------------------
public String getName(){
return name;
}
public int getNumber(){
return number;
}
public String getOrigin(){
return origin;
}
public String getdestinationCities(){
return destinationCities;
}
//------------------------------------------------
public void setName(String setname){
name=setname;
}
public void setNumber(int setNumber){
number=setNumber;
}
public void setOrigin(String setOrigin){
origin=setOrigin;
}
public void setdestinationCities(String
setdestination){
destinationCities=setdestination;

26
}
public String toString(){
String a=Integer.toString(number);
return "Flight:"+name+", Flight Number:"+a+" ,
Origin:"+origin+", Destination
Cities:"+destinationCities;
}
}

Driver Class
public class FlightTest{
public static void main(String[] args){
int a,b;
String u,v,w,x,y,z;
Flight f1=new Flight("Qatar
Airways",156,"Houston","Montreal-Miami,Miami-
Chicago");
Flight f2=new Flight("Turkish
Airlines",651,"Aman","Behrain-Kuwait,Kuwait-Abu
Dabhi");
//---------------------------------------------
System.out.println( ".....USING GETTERS.....");
u=f1.getName();
System.out.println("Name of flight:"+u);
a=f1.getNumber();
System.out.println("Flight number "+a);
v=f1.getOrigin();
System.out.println("Origin of flight:"+v);
w=f1.getdestinationCities();
System.out.println("Destinations of flight:"+w);
System.out.println("");
//----------------------------------------------
x=f2.getName();
System.out.println("Name of flight:"+x);
b=f2.getNumber();
System.out.println("Flight number "+b);
y=f2.getOrigin();
System.out.println("Origin of flight:"+y);
z=f2.getdestinationCities();
System.out.println("Destinations of flight:"+z);
System.out.println("");
//----------------------------------------------

27
System.out.println( ".....USING SETTERS AND
toString.....");
f1.setName("Turkish Airlines");
f1.setNumber(651);
f1.setOrigin("Aman");
f1.setdestinationCities("Behrain-Kuwait,Kuwait-Abu
Dabhi");
//----------------------------------------------
f2.setName("Qatar Airways");
f2.setNumber(156);
f2.setOrigin("Houston");
f2.setdestinationCities("Montreal-Miami,Miami-
Chicago");
//----------------------------------------------
System.out.println(f1);
System.out.println(f2);
}
}

Output
> run FlightTest
.....USING GETTERS.....
Name of flight:Qatar Airways
Flight number 156
Origin of flight:Houston
Destinations of flight:Montreal-Miami,Miami-Chicago

Name of flight:Turkish Airlines


Flight number 651
Origin of flight:Aman
Destinations of flight:Behrain-Kuwait,Kuwait-AbuDabhi

.....USING SETTERS AND toString.....


Flight:Turkish Airlines, Flight Number:651 ,
Origin:Aman, Destination Cities:Behrain-
Kuwait,Kuwait-Abu Dabhi
Flight:Qatar Airways, Flight Number:156 ,
Origin:Houston, Destination Cities:Montreal-
Miami,Miami-Chicago
>
Q.28 Using the Die class defined in this chapter, design and implement a
class called PairOfDice, composed of two Die objects. Include methods to
set and get the individual die values, a method to roll the dice, and a

28
method that returns the current sum of the two die values. Create a driver
class called RollingDice2 to instantiate and use a PairOfDice object.

Ans. public class PairOfDice {


private final int MAX = 6;
private int faceValue1,faceValue2;
public PairOfDice()
{
faceValue1 = 1;
faceValue2 = 1;
}
public int roll()
{
faceValue1 = (int)(Math.random()*MAX) + 1;
faceValue2 = (int)(Math.random()*MAX) + 1;
return (faceValue1+faceValue2);
}
public void setFaceValue (int val1,int val2)
{
faceValue1 = val1;
faceValue2 = val2;
}
public int getFaceValue()
{
return (faceValue1+faceValue2);
}
public String toString()
{
String result1 = Integer.toString(faceValue1);
String result2 = Integer.toString(faceValue2);
return (result1 + result2);
}}
Driver class
public class RollingDice2 {
public static void main (String[] args) {
PairOfDice pod1 = new PairOfDice();
PairOfDice pod2 = new PairOfDice();
System.out.println ("First pair of dies: " +
pod1.roll() + "\nSecond pair of dies: " +
pod2.roll());
System.out.println("---------------------------------
-------------------");
pod1.setFaceValue(5,1);

29
pod2.setFaceValue(4,6);
System.out.println ("First pair of dies: " +
pod1.getFaceValue() + "\nSecond pair of dies: " +
pod2.getFaceValue());
}}
Output

Q.29 Design and implement a class called Course. It should contain


instance data that represents thetitle,name,crediet hours and code. Define
the course constructor to accept and initialize all instance data. Include
getter and setter methods for all instance data. Include a toString method
that returns a one-line description of the course. Create a driver class
called course details, whose main method instantiates and updates several
course objects.

Ans. public class Course{


String Title,Name;
int Credits,Code;
public Course(String title,int code,String name,int
credits){;
Title= title;
Code= code;
Name=name;
Credits= credits;
}
public void settitle(String title){
Title= title;
}
public void setcode(int code){
Code= code;
}
public void setname(String name){
Name=name;
}

30
public void setcrediets(int crediets){
Credits = Credits;
}
public String gettitle(){
return Title;
}
public int getcode(){
return Code;
}
public String getname(){
return Name;
}
public int getcredits(){
return Credits;
}
public String toString(){
return "\n course title:"+Title+"\n course
code:"+Code+"\n instructor's name:"+Name+"\n the
credits hours:"+Credits;
}
}
Driver class
public class CourseDetails{
public static void main (String[] args) {
Course z1=new Course("linear
Algebra",100,"widmer",3);
Course z2=new Course("ADE",200,"tocci",2);
Course z3=new Course("java",300,"lewis loftus",1);
System.out.print(z1+"\n"+z2+"\n"+z3);
z1.settitle("Circuit Analysis");
z1.gettitle();
System.out.print(z1);
}
}
Output

31
CONDITIONALS AND LOOPS
Q.30 Write a program to print the required rows of a pyramid?

Ans. import java.util.Scanner;


public class AhsanLoop{
public static void main(String[] args){
int row,col,n,control;
Scanner scan=new Scanner(System.in);
System.out.println("How many rows you want to see
in the star(Enter even No.):");
n=scan.nextInt();
scan.close();
control = n;
//Upper Pyramid
for ( row = 1 ; row <= n ; row++ )
{
for ( col= 1 ; col < control ; col++ )
System.out.print(" ");
control--;
for ( col = 1 ; col <= 2*row - 1 ; col++ )
System.out.print("*");
System.out.println();
}
}
}

Output

Q.31 Write a program to print the following output?


1
22
333

32
4444
55555

Ans. public class LoopExample{


public static void main(String[] args)
{
for (int i=1; i<=5;i++){
for(int j=1;j<=(5-i);j++){
System.out.print(" ");
}
for (int k=1;k<=i; k++){
System.out.print(i);
}
System.out.println();
}
}
}

Output

Q.32 Write program to print multiplication tables of different numbers?

Ans. public class multiplicationTable


{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
System.out.print(i+"|");
for (int j=1; j<=10; j++)
{
System.out.print(" "+i*j);
}
System.out.println();
}
}
}
33
Output
1| 1 2 3 4 5 6 7 8 9 10
2| 2 4 6 8 10 12 14 16 18 20
3| 3 6 9 12 15 18 21 24 27 30
4| 4 8 12 16 20 24 28 32 36 40
5| 5 10 15 20 25 30 35 40 45 50
6| 6 12 18 24 30 36 42 48 54 60
7| 7 14 21 28 35 42 49 56 63 70
8| 8 16 24 32 40 48 56 64 72 80
9| 9 18 27 36 45 54 63 72 81 90
10| 10 20 30 40 50 60 70 80 90 100

Q.33 Write a program to count different from 1 to 10?

Ans. public class testFor


{
public static void main(String [] args)
{
for (int i=1; i<=9; i++)
{
System.out.println();
for (int j=1; j<=i; j++)
{
System.out.print(j);
}
}
System.out.println();
}
}

Output
1
12
123
1234
12345
123456
1234567
12345678
123456789

Q.34 Write a program to print different numbers in reverse order?

34
Ans. public class multiplicationTable
{
public static void main(String args[])
{
for(int i = 9; i > 0; i--)
{

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

System.out.print("_");

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

System.out.print(i);
}

System.out.println();
}
}
}

Output
999999999
_88888888
__7777777
___666666
____55555
_____4444
______333
_______22
________1

Q.35 Write a program to draw a star?

Ans. public class Pyramids {


public static void main(String[] args)
{
for (int i = 1; i <= 5; i++) {
for (int s = 5; s > i; s--) {
System.out.print(" ");
}

35
for (int j = 1; j < i; j++) {
System.out.print("#");
}
for (int j = 1; j < i; j++) {
System.out.print("#");
}
System.out.println("");
}
for (int i = 1; i <= 5; i++) {
for (int s = 1; s < i; s++) {
System.out.print(" ");
}
for (int j = 5; j > i; j--) {
System.out.print("#");
}
for (int j = 5; j > i; j--) {
System.out.print("#");
}
System.out.println("");
}
}
}

Output
##
####
######
########
########
######
####
##

Q.36 Write a program to print prime numbers?

Ans. import java .util.*;


public class Numbers
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int num=Scan.next Int();
int a=1;b=1;

36
while(a<=num)
{
while(b<a+1)
{
system.out.println(2*a-1);
b++;
}
a++;
System.out.println(" ");
}
}
}
Output
Array length: 8
The first few prime numbers are:
2 3 5 7 11 13 17 19 >

Q.37 Design and implement an application that reads an integer value from
the user representing a year. The purpose of the program is to determine if
the year is a leap year (and therefore has 29 days in February) in the
Gregorian calendar. A year is a leap year if it is divisible by 4, unless it is
also divisible by 100 but not 400. For example, the year 2003 is not a leap
year, but 2004 is. The year 1900 is not a leap year because it is divisible by
100, but the year 2000 is a leap year because even though it is divisible by
100, it is also divisible by 400. Produce an error message for any input
value less than 1582 (the year the Gregorian calendar was adopted).

Ans. import java.util.Scanner;


public class leapyear
{
public static void main (String[] args)
{
Scanner read = new Scanner(System.in);
int year;
System.out.println ("This program calculates leap
year.");
year = read.nextInt();
if (year == 1582)
{
System.out.println ( "Georgeon calendar starts from
year 1582 ");
}

37
else if ((year % 4 == 0) && year % 100 != 0)
{
System.out.println (year + " is a leap year.");
}
else if ((year % 4 == 0) && (year % 100 == 0) &&
(year % 400 == 0))
{
System.out.println (year + " is a leap year.");
}
else
{
System.out.println (year + " is not a leap year.");
}
}
}

Output

Q.38 Modify the solution to the previous project so that the user can
evaluate multiple years. Allow the user to terminate the program
using an appropriate sentinel value. Validate each input value to ensure
it is greater than or equal to 1582.

Ans. import java.util.Scanner;


public class leap year {
public static void main (String[] args)
{
Scanner read = new Scanner(System.in);
int year;
int another_year;
do
{
System.out.println ("Enter the year.");
year = read.nextInt();
if (year >= 1582)
38
{
if ((year % 4 == 0) && year % 100 != 0)
{
System.out.println (year + " is a leap year.");
}
else if ((year % 4 == 0) && (year % 100 == 0) &&
(year % 400 == 0))
{
System.out.println (year + " is a leap year.");
}
else
{
System.out.println (year + " is not a leap year.");
System.out.println ( "re-enter a new year :press y
for yes n for NO ");
another_year= read.nextInt();
}
}
else
System.out.println ( "Georgeon calendar starts from
year 1582 ");
System.out.println ( "re-enter a new year: press y
for yes n for NO ");
another_year= read.nextInt();
}
while(another_year == 1);
}
}

Output

39
Q.39 Design and implement an application that determines and prints
the number of odd, even, and zero digits in an integer value read from
the keyboard.

Ans. import java.util.Scanner;


public class Numbers {
public static void main (String[] args)
{
int num, pos, odd=0, even=0, zero=0, length = 0;

Scanner scan = new Scanner (System.in);


System.out.println ("Please enter an integer: ");
num = scan.nextInt();
length = String.valueOf(num).trim().length();
for (pos = length - 1; pos >= 0; pos--)
{
if (pos == 0)
zero++;
if (pos % 2 == 0)
even++;
if (pos % 2 != 0)
odd++;
}
System.out.println("zeros: " + zero);
System.out.println("evens: " + even);
System.out.println("odds: " + odd);
}
}

Output

40
Q.40 Design and implement an application that plays the Hi-Lo guessing
game with numbers. The program should pick a random number between
1 and 100 (inclusive), then repeatedly prompt the user to guess the number.
On each guess, report to the user that he or she is correct or that the guess
is high or low. Continue accepting guesses until the user guesses correctly
or chooses to quit. Use a sentinel value to determine whether the user wants
to quit. Count the number of guesses and report that value when the user
guesses correctly. At the end of each game (by quitting or a correct guess),
prompt to determine whether the user wants to play again. Continue
playing games until the user chooses to stop.

Ans. import java.util.Random;


import java.util.Scanner;
public class class2
{
public static boolean GuessingGame() {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
int answer = generator.nextInt(100)+1;
int numGuesses = 1;
int guess = 0;
while ((numGuesses <= 7) && (guess != answer))
{
System.out.print("Guess a number: ");
guess = keyboard.nextInt();
if (numGuesses < 7)
{
if (guess < answer)
{
System.out.println("Higher...");

41
}
else if (guess > answer)
{
System.out.println("Lower...");
}
else
{
System.out.println("You Win");
return true;
}
}
else
{
if (guess == answer)
{
System.out.println("You Win");
return true;
}
else
{
System.out.println("I Win, the number was " +
answer);
return false;
}
}
numGuesses++;
}
return false;
}
}

Driver class
import java.util.Scanner;
public class d {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String playAgain = "Y";
int userWins = 0;
int computerWins = 0;
while (playAgain.compareToIgnoreCase("Y") == 0)
{
boolean youWin = class2.GuessingGame();
if (youWin){
42
userWins++;
}else{
computerWins++;
}
System.out.print("Would you like to play another
game? (Y/N): ");
playAgain = keyboard.next();
}
System.out.println("Final Score: You " + userWins + "
Computer " + computerWins);
}
}

Output

Q .41 Create a modified version of the PalindromeTester program so that


the spaces, punctuation, and changes in uppercase and lowercase are not
considered when determining whether a string is a palindrome. Hint: These
issues can be handled in several ways. Think carefully about your design.
Ans. import java.util.Scanner;
public class PalindromeTester
{
43
public static void main (String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y"))
{
System.out.println ("Enter a potential
palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left
< right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a
palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)?
");
another = scan.nextLine();
}
}
}

Output

44
Q.42 Design and implement an application that plays the Rock-Paper-
Scissors game against the computer. When played between two people,
each person picks one of three options (usually shown by a hand gesture)
at the same time, and a winner is determined. In the game, Rock beats
Scissors, Scissors beats Paper, and Paper beats Rock. The program
should randomly choose one of the three options (without revealing it),
then prompt for the user’s selection. At that point, the program
reveals both choices and prints a statement indicating if the user
won, the computer won, or if it was a tie. Continue playing until the
user chooses to stop, then print the number of user wins, losses, and
ties.

Ans. import java.util.Scanner;


import java.util.Random;
public class game {
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
Random any = new Random();
int game = (int) (Math.random()*3);
System.out.println("press 0 - Rock");
System.out.println("press 1 - paper");
System.out.println("press 2 - Scissors");
int Selection;
Selection = input.nextInt();

45
if (Selection == 0)
System.out.println("Rock");
if (Selection == 1)
System.out.println("Paper");
if (Selection == 2)
System.out.println("Scissors");
if ( game==0)
System.out.println("Rock");
if (game == 1)
System.out.println("Paper");
if (game == 2)
System.out.println("Scissors");
if (Selection == game)
System.out.println("Same try again");
if (Selection == 0 && game == 1 )
System.out.println("Computer wins");
if (Selection == 0 && game == 2 )
System.out.println("You WON");
if (Selection == 1 && game == 0 )
System.out.println("You WON");
if (Selection == 1 && game == 2 )
System.out.println("Computer wins");
if (Selection == 2 && game == 0 )
System.out.println("Computer wins");
if (Selection == 2 && game == 1 )
System.out.println("You WON");
}
}

Output

Q.43 Design and implement an application that simulates a simple slot


machine in which three numbers between 0 and 9 are randomly selected
and printed side by side. Print an appropriate statement if all three of the
46
numbers are the same, or if any two of the numbers are the same. Continue
playing until the user chooses to stop.

Ans. import java.util.Scanner;


import java.util.Random;
public class game
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
int num1,num2,num3,choice,j = 0;
System.out.println("how many times you want to
play");
choice = input.nextInt();
do
{
int a = (int) (Math.random()*9);
num1 = a;
int b = (int) (Math.random()*9);
num2 = b;
int c = (int) (Math.random()*9);
num3 = c;
System.out.println(num1 );
System.out.println(num2 );
System.out.println(num3);
if (num1 == num2 &&num1==num3 && num2 == num3 )
System.out.println("number are same");
if (num1 == num2)
System.out.println("num1 and num2 are same");
if (num1 == num3)
System.out.println("num1 and num3 are same");
if (num2 == num3)
System.out.println("num2 and num3 are same");
j++;
}
while(choice >= j);
}
}

Output

47
48
OBJECT ORIENTED DESIGN
Q.44 Modify the Account class from Chapter 4 so that it also permits an
account to be opened with just a name and an account number, assuming
an initial balance of zero. Modify the main method of the Transactions
class to demonstrate this new capability.

Ans. Account
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.035;
private long acctNumber;
private double balance;
private String name;

public Account (String owner, long account)


{
name = owner;
acctNumber = account;
balance = 0;
}

public double deposit (double amount)


{
balance = balance + amount;
return balance;
}
public double withdraw (double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
public double getBalance ()
{
return balance;
}

public String toString ()


{

49
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "\t" + name + "\t" + fmt.format(balance);
}
}
Main program
public class Transactions
{
public static void main (String[] args)
{
Account acct1 = new Account ("Ted Murphy", 72354);
Account acct2 = new Account ("Jane Smith", 69713);
Account acct3 = new Account ("Edward Demsey", 93757);
acct1.deposit (25.85);
double smithBalance = acct2.deposit (500.00);
System.out.println ("Smith balance after deposit: " +
smithBalance);
System.out.println ("Smith balance after withdrawal:
" +
acct2.withdraw (430.75, 1.50));
acct1.addInterest();
acct2.addInterest();
acct3.addInterest();
System.out.println ();
System.out.println (acct1);
System.out.println (acct2);
System.out.println (acct3);
}
}
output

Smith balance after deposit: 500.0


Smith balance after withdrawal: 67.75

72354 Ted Murphy £26.75


69713 Jane Smith £70.12
93757 Edward Demsey £0.00

Q.45 Modify the RationalNumber class so that it implements the interface.


To perform the comparison, compute an equivalent floating point value
50
from the numerator and denominator for both RationalNumber objects,
then compare them using a tolerance value of 0.0001. Write a main driver
to test your modifications.

Ans. RationalNumber
public class RationalNumber
{
private int numerator,denominator;
public static String s;
public RationalNumber(int numer,int denom)
{
if(denom==0)
denom=1;
if (denom < 0)
{
numer = numer * -1;
denom = denom * -1;
}
numerator = numer;
denominator = denom;
reduce();
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public RationalNumber reciprocal()
{
return new RationalNumber(denominator, numerator);
}
public RationalNumber add(RationalNumber op2)
{
int commonDenominator = denominator *
op2.getDenominator();

51
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int sum = numerator1 + numerator2;
return new RationalNumber(sum, commonDenominator);
}
public RationalNumber subtract(RationalNumber op2)
{
int commonDenominator = denominator *
op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator;
int difference = numerator1 - numerator2;
return new RationalNumber(difference,
commonDenominator);
}
public RationalNumber multiply(RationalNumber op2)
{
int numer = numerator * op2.getNumerator();
int denom = denominator * op2.getDenominator();
return new RationalNumber(numer, denom);
}
public RationalNumber divide(RationalNumber op2)
{
return multiply(op2.reciprocal());
}
public boolean isLike(RationalNumber op2)
{
return ( numerator == op2.getNumerator() &&
denominator == op2.getDenominator() );
}
public String toString()
{
String result;
if (numerator == 0)
result = "0";
else
if (denominator == 1)
result = numerator + "";

52
else
result = numerator + "/" + denominator;
return result;
}
private void reduce()
{
if (numerator != 0)
{
int common = gcd(Math.abs(numerator), denominator);
numerator = numerator / common;
denominator = denominator / common;
}
}
private int gcd( int num1, int num2)
{
while (num1 != num2)
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
return num1;
}
public void compareTo(RationalNumber R)
{
float f=(float)numerator/denominator;
float
f1=(float)(R.getNumerator())/(R.getDenominator());
if(f==f1)
{
System.out.println("both are Equal");

}
else
{
if(f<f1)
{
float d=f1-f;
if(d<=0.0001)

53
System.out.println("both are aproximately
equal");
else
System.out.println ("these are not equal");
}
else
{
float d1=f-f1;
if(d1<=0.0001)
System.out.println("both are aproximately equal");

}
}

}
}
Constructer Class
public class RationalTester
{
public static void main(String[] args)
{

RationalNumber r1 = new RationalNumber(6, 18);


RationalNumber r2 = new RationalNumber(10, 3);
r1.compareTo(r2)
}
}
Q.46 Modify the Task class from PPs 7.5 and 7.6 so that it also implements
the Comparable interface from the Java standard class library. Implement
the interface such that the tasks are ranked by priority. Create a driver
class whose main method shows these new features of Task objects.
Ans. Interface classes: -
1.
public interface Priority
{
public void setPriority(int level);
public intgetPriority();
}
54
2.
public interface Complexity
{
public void setcomplexity( int complexity);
public intgetcomplexity();
}

Method Class

import java.util.*;
public class Task implements Priority,Complexity
{
private String question, priority,answer;
private int complexity;

//---------------------------------------------------
--
// Constructor: Creates a task and a priority level.
//---------------------------------------------------
--
public Task (String question, intcomplexity,String
answer)
{
this.question = question;
this.answer = answer;
this.complexity = complexity;

if (complexity == 1)
priority = "Critical";
if (complexity == 2)
priority = "Very Important";
if (complexity == 3)
priority = "Normal";
if (complexity == 4)
priority = "Low";
if (complexity == 5)
priority = "Not Important";
}

55
//---------------------------------------------------
--
// Sets the priority level.
//---------------------------------------------------
--
public void setcomplexity( int complexity)
{
this.complexity=complexity;
}
public void setPriority (int complexity)
{
this.complexity = complexity;

if (complexity == 1)
priority = "Critical";
if (complexity == 2)
priority = "Very Important";
if (complexity == 3)
priority = "Normal";
if (complexity == 4)
priority = "Low";
if (complexity == 5)
priority = "Not Important";
}
public void setquestion(String question)
{
this.question = question;
}
public String getquestion()
{
return question;
}
public String getanswer()
{
return answer;
}

56
//---------------------------------------------------
--
// Returns the priority level.
//---------------------------------------------------
--
public intgetPriority()
{
return complexity;
}
public intgetcomplexity()
{
return complexity;
}
public booleananswerCorrect(String candidateAnswer)
{
return answer.equals(candidateAnswer);
}
public intcompareTo(Task obj)
{
Task st=(Task)obj;
if(complexity==st.complexity)
return 0;
else if(complexity>st.complexity)
return 1;
else
return -1;
}
//---------------------------------------------------
--
// Returns a description of the task object.
//---------------------------------------------------
--
public String toString()
{
return question + "\t" + "Priority Level: " +
complexity + "\t" + priority + "\t"+ answer + "\t"
+"(Complexity Level: "+complexity+")";
}

57
}

Main Class

import java.util.*;
public class main_imp
{
public static void main(String arg[])
{
Scanner scan = new Scanner(System.in);
Task q1,q2;
String possible;
q1 = new Task("What is the capital of Jamaica?",3,
"Kingston");
q2 = new Task("Which is worse, ignorance or
apathy?",2, "I don't know and I don't care");
System.out.print(q1.getquestion());
possible = scan.nextLine();
if (q1.answerCorrect(possible))
System.out.println("Correct");
else
System.out.println("No, the answer is " +
q1.getanswer());
System.out.println();
System.out.print(q2.getquestion());
System.out.println(" (Level: " + q2.getcomplexity() +
")");
possible = scan.nextLine();
if (q2.answerCorrect(possible))
System.out.println("Correct");
else
System.out.println("No, the answer is " +
q2.getanswer());
if (q1.compareTo(q2) < 0)
System.out.println("complexity of question1 is less
than complexity of question2");
else

58
System.out.println("complexity of question1 is
greator or equal than complexity of question2");
System.out.println(q2.toString());
q2.setPriority (1);
q2.setquestion ("two");
System.out.println(q1.toString());
System.out.println(q2.toString());
}
}

Output

What is the capital of Jamaica? [Kingston]


Correct

Which is worse, ignorance or apathy? (Level: 2)


[Any thing]
No, the answer is I don't know and I don't care
complexity of question1 is greater or equal than
complexity of question2
Which is worse, ignorance or apathy?
Priority Level:2 Very Important I don't know and I
don't care (Complexity Level: 2)
What is the capital of Jamaica?
Priority Level: 3 Normal Kingston (Complexity Level:
3)
two Priority Level: 1
Critical I don't know and I don't care (Complexity
Level: 1)

59
POLYMORPHISM
Q.47 Design and implement a set of classes that keeps track of various
sports statistics. Have each low-level class represent a specific sport. Tailor
the services of the classes to the sport in question, and move common
attributes to the higher-level classes as appropriate. Create a main driver
class to instantiate and exercise several of the classes.
Driver class
public class Driver{
public static void main(String args[]){
String a,b,a1,b1,a2,b2,a3,b3,a4,b4;
double x;
Player player1=new Player();
Player player2=new Player();
player1.setPlayer1("Ali");
player2.setPlayer2("Nouman");
a=player1.getPlayer1();
b=player2.getPlayer2();
Badminton bad=new Badminton();
x=bad.computeDiff();
System.out.println("Player1: "+a+" Player2: "+b+"
Difference b/w goals: "+x);
if(bad.computeProbability()>=1)
System.out.println("Probability holds to win for
player(having less goals)");
else
System.out.println("Probability does not holds
for(having less goals)");
System.out.println("");
player1.setPlayer1("Mazhar");
player2.setPlayer2("Sanan");
a1=player1.getPlayer1();
b1=player2.getPlayer2();
Soccer soc=new Soccer();
x=soc.computeDiff();
System.out.println("Player1: "+a1+" Player2:
"+b1+" Difference b/w goals: "+x);
if(soc.computeProbability()>=1)
System.out.println("Probability holds to win for
player(having less goals)");
60
else
System.out.println("Probability does not holds
for(having less goals)");
System.out.println("");
player1.setPlayer1("Ahsan");
player2.setPlayer2("Awais");
a2=player1.getPlayer1();
b2=player2.getPlayer2();
Shooting sho=new Shooting();
x=sho.computeDiff();
System.out.println("Player1: "+a2+" Player2:
"+b2+" Difference b/w goals: "+x);
if(sho.computeProbability()>=1)
System.out.println("Probability holds to win for
player(having less goals)");
else
System.out.println("Probability does not holds
for(having less goals)");
System.out.println("");
player1.setPlayer1("Mustafa");
player2.setPlayer2("Umer");
a3=player1.getPlayer1();
b3=player2.getPlayer2();
Swiming swi=new Swiming();
x=swi.computeDiff();
System.out.println("Player1: "+a3+" Player2:
"+b3+" Difference b/w goals: "+x);
if(swi.computeProbability()>=1)
System.out.println("Probability holds to win for
player(having less goals)");
else
System.out.println("Probability does not holds
for(having less goals)");
System.out.println("");
player1.setPlayer1("Amir");
player2.setPlayer2("Salman");
a4=player1.getPlayer1();
b4=player2.getPlayer2();

61
Rowing row=new Rowing();
x=row.computeDiff();
System.out.println("Player1: "+a4+" Player2:
"+b4+" Difference b/w goals: "+x);
if(row.computeProbability()>=1)
System.out.println("Probability holds to win for
player(having less goals)");
else
System.out.println("Probability does not holds
for(having less goals)");
}
}
Parent class
public class Player{
protected String p1;
protected String p2;
protected int difference=4;
public void setPlayer1(String play)
{
p1=play;
}
public void setPlayer2(String play)
{
p2=play;
}
public String getPlayer1()
{
return p1;
}
public String getPlayer2()
{
return p2;
}
}
Different child classes
public class Badminton extends Player
{
private int p1Score=4;
62
private int p2Score=8;
private int turnsRemaining=5;
public double computeDiff()
{
return (double) p2Score-p1Score;
}
public double computeProbability()
{
return (double) turnsRemaining-difference;
}
}
public class Rowing extends Player
{
private int p1Score=0;
private int p2Score=4;
private int turnsRemaining=2;
public double computeDiff()
{
return (double) p2Score-p1Score;
}
public double computeProbability()
{
return (double) turnsRemaining-difference;
}
}
public class Shooting extends Player
{
private int p1Score=0;
private int p2Score=4;
private int turnsRemaining=9;
public double computeDiff()
{
return (double) p2Score-p1Score;
}
public double computeProbability()
{
return (double) turnsRemaining-difference;
}

63
}
public class Soccer extends Player
{
private int p1Score=8;
private int p2Score=12;
private int turnsRemaining=3;
public double computeDiff()
{
return (double) p2Score-p1Score;
}
public double computeProbability()
{
return (double) turnsRemaining-difference;
}
}
public class Swiming extends Player
{
private int p1Score=2;
private int p2Score=6;
private int turnsRemaining=2;
public double computeDiff()
{
return (double) p2Score-p1Score;
}
public double computeProbability()
{
return (double) turnsRemaining-difference;
}
}
Output
> run Driver
Player1: Ali Player2: Nouman Difference b/w goals:
4.0
Probability holds to win for player(having less
goals)

Player1: Mazhar Player2: Sanan Difference b/w goals:


4.0
64
Probability does not holds for(having less goals)

Player1: Ahsan Player2: Awais Difference b/w goals:


4.0
Probability holds to win for player(having less
goals)

Player1: Mustafa Player2: Umer Difference b/w goals:


4.0
Probability does not holds for(having less goals)

Player1: Amir Player2: Salman Difference b/w goals:


4.0
Probability does not holds for(having less goals)
>

Q.48 Write a program that extend the Bicycle class with


a MountainBike and a RoadBike class. For MountainBike, add a field
forsuspension, which is a String value that indicates if the bike has a front
shock absorber, Front. Or, the bike has a front and back shock
absorber, Dual.

Ans. MountainBike

public class MountainBike extends Bicycle {


private String suspension;
public MountainBike(
int startCadence,
int startSpeed,
int startGear,
String suspensionType){
super(startCadence,
startSpeed,
startGear);
this.setSuspension(suspensionType);
}

public String getSuspension(){


return this.suspension;
}

65
public void setSuspension(String suspensionType)
{
this.suspension = suspensionType;
}

public void printDescription() {


super.printDescription();
System.out.println("The " + "MountainBike has
a" +
getSuspension() + " suspension.");
}
}

RoadBike
public class RoadBike extends Bicycle{
// In millimeters (mm)
private int tireWidth;

public RoadBike(int startCadence,


int startSpeed,
int startGear,
int newTireWidth){
super(startCadence,
startSpeed,
startGear);
this.setTireWidth(newTireWidth);
}

public int getTireWidth(){


return this.tireWidth;
}

public void setTireWidth(int newTireWidth){


this.tireWidth = newTireWidth;
}

public void printDescription(){


super.printDescription();
System.out.println("The RoadBike" + " has " +
getTireWidth() +
" MM tires.");
}

66
}

Main Method
public class TestBikes {
public static void main(String[] args){
Bicycle bike01, bike02, bike03;

bike01 = new Bicycle(20, 10, 1);


bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);

bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}

Output

Bike is in gear 1 with a cadence of 20 and travelling


at a speed of 10.

Bike is in gear 5 with a cadence of 20 and travelling


at a speed of 10.
The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling


at a speed of 20.
The RoadBike has 23 MM tires.

67
ARRAYS

Q.49 Write a program that creates an array of integers, puts some values in
the array, and prints each value to standard output.
Ans. ArrayDemo

class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;

// allocates memory for 10 integers


anArray = new int[10];

// initialize first element


anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: "


+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
68
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}

Output
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000

Q.50 write a java program that uses char array loop

Ans. public class Program {


public static void main(String[] args) {

// Create an array of four chars.


char[] values = new char[4];
values[0] = 'j';
values[1] = 'a';
values[2] = 'v';
values[3] = 'a';

// Loop over array with for-loop.


for (char value : values) {
System.out.println(value);
}
}
}
Output

j
a
v
a

69
Q.51 write a java program that merges two arrays?

Ans. import java.util.Arrays;

public class Program {


public static void main(String[] args) {

int[] values = { 10, 20, 30 };


int[] values2 = { 100, 200, 300 };

// Merge the two arrays with for-loops.


int[] merge = new int[values.length +
values2.length];
for (int i = 0; i < values.length; i++) {
merge[i] = values[i];
}
for (int i = 0; i < values2.length; i++) {
merge[i + values.length] = values2[i];
}

// Display the merged array.


System.out.println(Arrays.toString(merge));
}
}
Output

[10, 20, 30, 100, 200, 300]

70

You might also like