0% found this document useful (0 votes)
97 views61 pages

OOP Assignment

The document contains 16 programming questions related to Object Oriented Programming concepts in Java. Each question provides sample code to demonstrate a concept such as constructors, methods, loops, arrays, etc. For each question, the code is provided along with sample input/output. The questions cover topics like this keyword, constructors, arrays, selection statements, iteration statements, method overloading, objects as parameters, and ArrayLists.

Uploaded by

Mukhtar Khawaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views61 pages

OOP Assignment

The document contains 16 programming questions related to Object Oriented Programming concepts in Java. Each question provides sample code to demonstrate a concept such as constructors, methods, loops, arrays, etc. For each question, the code is provided along with sample input/output. The questions cover topics like this keyword, constructors, arrays, selection statements, iteration statements, method overloading, objects as parameters, and ArrayLists.

Uploaded by

Mukhtar Khawaja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Assignment:

Object Oriented Programing (OOP)


Name:
Mukhtar Ahmed
Teacher Name:
Mam Rawish Butt
Question # 1
Use of “this” keyword
CODE:
package thisword;

import java.util.Scanner;

class Account

String name;

void setName(String name)

this.name=name;
}

String getName()

return name;

public class ThisWord

public static void main(String[] args)

Scanner input=new Scanner(System.in);

Account obj=new Account();

System.out.println("Please Enter the name");

String name=input.nextLine();

obj.setName(name);

String disp=obj.getName();

System.out.printf("Name in object obj is %n%s%n",disp);

OUTPUT:
Question # 2:
Constructor(Default Constructor)

CODE:
package labb;

class Box

double width;

double height;

double depth;

// This is the constructor for Box. Box()

{
System.out.println("Constructing Box");

width = 10;

height = 10;

depth = 10;

// compute and return volume

double volume()

return width * height * depth; }

public class Labb

public static void main(String[] args)

// declare, allocate, and initialize Box objects

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();

System.out.println("Volume is " + vol);

OUTPUT:

Question # 3:
Constructor(Parameterized Constructor)

CODE:
package defaultconstractor;

import java.util.Scanner;

class First

int a=0;
int b=0;

First(int a,int b)

this.a=a;

this.b=b;

int sum()

int add=a+b;

return add;

public class DefaultConstractor

public static void main(String[] args)

Scanner input=new Scanner(System.in);

System.out.println("Enter first number");

int a=input.nextInt();

System.out.println("Enter second number");

int b=input.nextInt();

First obj=new First(a,b);


int total=obj.sum();

System.out.printf("Sum of two number is %d%n",total);

OUTPUT:

Question # 4:
Arrays (One-Dimensional Arrays)
CODE:
package labb;

public class Labb

public static void main(String[] args)


{

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

System.out.println("April has " + month_days[3] + " days.");

OUTPUT:

Question # 5:
Arrays(Multidimensional Arrays)
CODE:
package labb;

public class Labb

{
public static void main(String[] args)

int twoD[][]= new int[4][5];

int i, j, k = 0;

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

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

twoD[i][j] = k; k++;

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

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

System.out.print(twoD[i][j] + " ");

System.out.println();

OUTPUT:
Question # 6:
Java’s Selection Statements(Nested if else)

CODE:
package labb;

public class Labb

public static void main(String[] args)

int month = 4; // April String season;

String season;

if(month == 12 || month == 1 || month == 2)

season = "Winter";

else
if(month == 3 || month == 4 || month == 5)

season = "Spring";

else

if(month == 6 || month == 7 || month == 8)

season = "Summer";

else

if(month == 9 || month == 10 || month == 11)

season = "Autumn";

else

season = "Bogus Month";

System.out.println("April is in the " + season + ".");

OUTPUT:
Question # 7:
Java’s Selection Statements(switch)

CODE:
package labb;
public class Labb
{
public static void main(String[] args)
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}

OUTPUT:
Question # 8:
Iteration Statements (while Loop)

CODE:
package labb;

public class Labb

public static void main(String[] args)

int n = 10;

while(n > 0)

System.out.println("tick " + n);

n--;

OUTPUT:
Question # 9:
Iteration Statements (Do while Loop)

CODE:
package labb;

public class Labb

public static void main(String[] args)

int n = 10;

do

{
System.out.println("tick " + n);

n--;

while(n > 0);

OUTPUT:

Question # 10:
Iteration Statements (For Loop)

CODE:
package labb;

public class Labb


{

public static void main(String[] args)

int n;

for(n=10; n>0; n--)

System.out.println("tick " + n);

OUTPUT:

Question # 11:
Iteration Statements (For each Statement/Loop)

CODE:
package enhanceforloop;

public class EnhanceForLoop


{

public static void main(String[] args)

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int sum = 0;

// use for-each style for to display and sum the values

for(int x : nums)

System.out.println("Value is: " + x);

sum += x;

System.out.println("Summation: " + sum);

OUTPUT:
Question # 12:
Function/Method Overloading

CODE:
package labb;

class OverloadDemo

void test()

System.out.println("No parameters");

// Overload test for one integer parameter.

void test(int a)

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


}

// Overload test for two integer parameters.

void test(int a, int b)

System.out.println("a and b: " + a + " " + b);

// overload test for a double parameter

double test(double a)

System.out.println("double a: " + a);

return a*a;

public class Labb

public static void main(String args[])

OverloadDemo ob = new OverloadDemo();

double result;

// call all versions of test()

ob.test();

ob.test(10);
ob.test(10, 20);

result = ob.test(123.25);

System.out.println("Result of ob.test(123.25): " + result);

OUTPUT:

Question # 13:
Overloading Constructors

CODE:

package labb;
class Box

double width;

double height;

double depth;

// constructor used when all dimensions specified

Box(double w, double h, double d)

width = w; height = h; depth = d;

// constructor used when no dimensions specified

Box()

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

// constructor used when cube is created

Box(double len)

width = height = depth = len;

}
// compute and return volume

double volume()

return width * height * depth;

public class Labb

public static void main(String args[])

// create boxes using the various constructors

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box();

Box mybox3 = new Box(7.0);

double vol;

// get volume of first

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mybox3.volume();

System.out.println("Volume of mycube is " + vol);

OUTPUT:

Question # 14:
Objects as Parameters

CODE:
package labb;
class Test

int a;

int b;

Test(int a, int b)

this.a = a;

this.b=b;

// return true if o is equal to the invoking object

boolean equals(Test o)

if(o.a == a && o.b == b)

return true;

else

return false;

public class Labb

public static void main(String args[])

{
Test ob1 = new Test(100, 22);

Test ob2 = new Test(100, 22);

Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));

System.out.println("ob1 == ob3: " + ob1.equals(ob3));

OUTPUT:

Question # 15:
Variable-Length Arguments List
CODE:
package variable.length.argument.list;

import java.util.Scanner;

public class VariableLengthArgumentList

public static void main(String[] args)

Scanner input=new Scanner(System.in);

System.out.println("Enter the Integer");

int d1=input.nextInt();

System.out.println("Enter the Integer");

int d2=input.nextInt();

System.out.println("Enter the Integer");

int d3=input.nextInt();

System.out.println("Enter the Integer");

int d4=input.nextInt();

System.out.println("Enter the Integer");

int d5=input.nextInt();

int rd1=average(d1);

int rd2=average(d1,d2);

int rd3=average(d1,d2,d3);
int rd4=average(d1,d2,d3,d4);

int rd5=average(d1,d2,d3,d4,d5);

System.out.printf("Average of First call is = %d%n",rd1);

System.out.printf("Average of Second call is = %d%n",rd2);

System.out.printf("Average of Third call is = %d%n",rd3);

System.out.printf("Average of Fourth call is = %d%n",rd4);

System.out.printf("Average of Fifth call is = %d%n",rd5);

static int average(int ... number)

int total=0;

for(int i:number)

total+=i;

return total/number.length;

OUTPUT:
Question # 16:
ArrayList:

CODE:

package arraylistprogram;

import java.util.ArrayList;

import java.util.Scanner;

public class ArrayListProgram

public static void main(String[] args)


{

ArrayList<Integer> obj=new ArrayList<>();

Scanner input=new Scanner(System.in);

System.out.println("Enter the value in Arraylist");

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

int k=input.nextInt();

obj.add(k);

int total=0;

for(int i:obj

total+=i;

System.out.println("Sum of given Number is = "+total);

OUTPUT:
Question # 17:
Enum Types:

CODE:
package enumtype;

import java.util.EnumSet;

enum Book

JHTP("Java How To Program","2015"),

CHTP("HOW TO PROGRAM","2013"),

CPPHHT("C++ HOW TO PROGRAM","2014");

private final String title;


private final String copyrightyear;

Book(String title,String copyrightyear)

this.title=title;

this.copyrightyear=copyrightyear;

public String gettitle()

return title;

public String getcopyrightyear()

return copyrightyear;

public class EnumType

public static void main(String[] args)

System.out.println("All books");

for(Book book: Book.values())


System.out.printf("%-10s%-
45s%s%n",book,book.gettitle(),book.getcopyrightyear());

System.out.println("display a rang of enum type");

for(Book book:EnumSet.range(Book.JHTP, Book.CHTP))

System.out.printf("%-10s%-
45s%s%n",book,book.gettitle(),book.getcopyrightyear());

OUTPUT:

Question # 18:
Exception Handling:

CODE:
package exception;

public class Exception

public static void main(String[] args) {

int a=20;

int b=0;

int c=0;

int x;

try

x=a/(b+c);

System.out.println("x is="+x);

catch(ArithmeticException e)

System.out.println("Number id divided by 0"+e);

int y=a;

System.out.println("yis="+y);

}
OUTPUT:

Question # 19:
Inheritance(Single Inheritance):

CODE:
package inheritance;

import java.util.Scanner;

class Parents

int x; //field

int y; //field

void getdata(int m,int n) //Method


{

x=m;

y=n;

int add() //Method

int sum;

sum=x+y;

return sum;

class Child extends Parents

// System.out.println("SUB CLASS/CHILD CLASS/DERVIED CLASS");

int mul() //Method

int mult;

mult=x*y;

return mult;

}
}

public class Inheritance

public static void main(String[] args)

Scanner input=new Scanner(System.in);

int a;

int b;

System.out.println("Enter first number");

a=input.nextInt();

System.out.println("Enter second number");

b=input.nextInt();

Child obj=new Child();

int add;

int mul;

obj.getdata(a, b);

mul=obj.mul();

add=obj.add();

System.out.println("Addition of given number is = "+obj.add());

System.out.println("Multiplication of given number is = "+obj.mul());

}
OUTPUT:

Question # 20:
Inheritance(Multilevel Inheritance):

CODE:
//Mukhtar Ahmed

//Multilevel Inheritance

package multilevel_inheritance;

import java.util.Scanner;

class Student

int rol;//Field
void get_roll_no(int x)

rol=x;

void dis_roll_no()

System.out.println("Roll number is = "+rol);

class Test extends Student

int mark1;

int mark2;

void get_marks(int p,int q)

mark1=p;

mark2=q;

void dis_marks()

System.out.println("Marks of First Subject is = "+mark1);


System.out.println("Marks of Second Subject is= "+mark2);

class Result extends Test

void display()

int Average;

dis_roll_no();

dis_marks();

Average=(mark1+mark2)/2;

System.out.println("Average of Marks of Roll number "+rol+" is = "+Average);

public class Multilevel_Inheritance

public static void main(String[] args)

Scanner input=new Scanner(System.in);

Result obj=new Result();

int roll_no;
System.out.println("Enter the roll number");

roll_no=input.nextInt();

obj.get_roll_no(roll_no);

int marks1;

System.out.println("Enter the marks of First subject");

marks1=input.nextInt();

int marks2;

System.out.println("Enter the maks of second subject");

marks2=input.nextInt();

obj.get_marks(marks1, marks2);

obj.display();

OUTPUT:

Question # 21:
Inheritance(Multi Child):
CODE:
/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package multichildclasses;

/**

* @author RAWISH

*/

class parent

int px;

parent()

px=0;

void setp(int a)

px=a;
}

void showp()

System.out.print("px="+px);

class child1 extends parent

int cx;

void setc(int a,int b)

cx=a;

px=b;

void showc()

System.out.println("px="+px+" cx="+cx);

class child2 extends parent

{
int cx;

void setc(int a,int b)

px=a;

cx=b;

void showc()

System.out.println("px="+px+" cx="+cx);

public class Multichildclasses

/**

* @param args the command line arguments

*/

public static void main(String[] args)

// TODO code application logic here

child1 c1=new child1();

child2 c2=new child2();

c1.setc(23,46);
c2.setc(21,54);

c1.showc();

c2.showc();

OUTPUT:

Question # 22:
Polymorphism:

CODE:

package polymorphism;
abstract class Employee

private String firstName;

private String lastName;

private String socialSecurityNumber;

Employee(String firstName,String lastName,String socialSecurityNumber)

this.firstName=firstName;

this.lastName=lastName;

this.socialSecurityNumber=socialSecurityNumber;

public String getFirstName()

return firstName;

public String getLastName()

return lastName;

public String getSocialSecurityNumber()

return socialSecurityNumber;
}

@Override

public String toString()

return String.format("%s %s %n social security number : %s


",getFirstName(),getLastName(),getSocialSecurityNumber());

public abstract double earning();

//*****************************************************************
**************************//

class SalariedEmployee extends Employee

private double weeklySalary;

SalariedEmployee(String firstName,String lastName,String


socialSecurityNumber,double weeklySalary)

super(firstName,lastName,socialSecurityNumber);

if(weeklySalary<0.0)

throw new IllegalArgumentException("weekly salary must be greater


than 0");

this.weeklySalary=weeklySalary;
}

public void setWeeklySalary(double weeklySalary)

this.weeklySalary=weeklySalary;

public double getWeeklySalary()

return weeklySalary;

public double earning()

return getWeeklySalary();

public String toString()

return String.format("salaried employee : %s %n %s :


$%,.2f",super.toString(),"weekly salary",getWeeklySalary());

//*****************************************************************
************************//
class HourlyEmployee extends Employee

private double wage;

private double hours;

HourlyEmployee(String firstName,String lastName,String


socialSecurityNumber,double wage,double hours)

super(firstName,lastName,socialSecurityNumber);

if(wage<0.0)

throw new IllegalArgumentException("wage must be greater than


0.0");

this.wage=wage;

if((hours<0.0)||(hours>=168.0))

throw new IllegalArgumentException("hours is between (0.0_167)");

this.hours=hours;

public void setWage(double wage)

if(wage<0.0)

throw new IllegalArgumentException("wage must be greater than


0.0");

this.wage=wage;
}

public double getWage()

return wage;

public void sethours(double hours)

if((hours<0.0)||(hours>=168.0))

throw new IllegalArgumentException("hours is between (0.0_167)");

this.hours=hours;

public double getHours()

return hours;

@Override

public double earning()

if(getHours()<=40)

return getWage()*getHours();

else

return 40*getWage()+(getHours()*getWage()*1.50);
}

@Override

public String toString()

return String.format("hourly employee : %s%n%s : $%,.2f: %s :%,.2f",


super.toString(),"hourly wage",getWage(),"hours worked ",getHours());

//*****************************************************************
*********************//

public class Polymorphism {

public static void main(String[] args) {

SalariedEmployee salariedEmployee=new
SalariedEmployee("Jojn","Smith","111_11_11",800.00);

HourlyEmployee hourlyEmployee=new
HourlyEmployee("Karen","Price","222_22_22",16.75,40);

System.out.println("Employee prosess individual:");

System.out.printf("%n%s%n%s : $%,.2f%n%n",salariedEmployee," earned


",salariedEmployee.earning());
System.out.printf("%n%s%n%s : $%,.2f%n%n",hourlyEmployee," earned
",hourlyEmployee.earning());

Employee[] employees=new Employee[2];

employees[0]=salariedEmployee;

employees[1]=hourlyEmployee;

for(Employee currentEmployee : employees)

System.out.println(currentEmployee);

OUTPUT:

Question # 23:
Abstract Classes:
CODE:

package pkgabstract;

import java.util.Scanner;

abstract class A

abstract void sum();

class B extends A

int M;

int N;

B(int x,int y)

M=x;

N=y;

@Override

void sum()
{

int add;

add=M+N;

System.out.printf("sum of number is :%d%n",add);

public class Abstract

public static void main(String[] args)

Scanner input=new Scanner(System.in);

int i;

int j;

System.out.println("Enter two number");

i=input.nextInt();

j=input.nextInt();

B obj=new B(i,j);

obj.sum();

}
OUTPUT:

Question # 23:
Interfaces Classes:

CODE:

package pay.roll.system.using.interfaces;

interface Person

@Override
String toString();

interface Employee extends Person

int calculateSalary();

class VisitingEmployee implements Employee

private String name;

private String ID;

protected String gender;

private int workingHours;

private int payRate;

VisitingEmployee(String name,String ID,String gender,int workingHours,int


payRate)

this.name=name;

this.ID=ID;
this.gender=gender;

if((workingHours<0)||(workingHours>24))

throw new IllegalArgumentException("Working Hours is > 0 AND <25");

this.workingHours=workingHours;

if(payRate<0)

throw new IllegalArgumentException("payRate is greater than 0");

this.payRate=payRate;

public String getName()

return name;

public String getID()

return ID;

public String getGender()

return gender;

public int getWorkingHours()


{

return workingHours;

public int getPayRate()

return payRate;

@Override

public int calculateSalary()

return getWorkingHours()*getPayRate();

@Override

public String toString()

return String.format("%s%s%n%s%s%n%s%s%n%s%d%n%s%d%n%s%d%n"

,"Name of Employee :",name,"Employee ID :",ID,"Employee Gender


:",gender,"Working Hours of Employee :"

,getWorkingHours(),"Par Rate of Employee :"

,getPayRate(),"Salary of Employee :",calculateSalary());

}
class PermanentEmployee implements Employee

private int grade;

private String name;

private String ID;

private String gender;

PermanentEmployee(String name,String ID,String gender,int grade)

this.name=name;

this.grade=grade;

this.ID=ID;

this.gender=gender;

if((grade<17)||(grade>19))

throw new IllegalArgumentException("Grade is >=17 & <=19");

this.grade=grade;

public int getGrade()

return grade;

@Override

public int calculateSalary()


{

int salary=0;

if(getGrade()==17)

salary+=30000-(30000*5/100);

else if(getGrade()==18)

salary+=32000-(32000*5/100);

else if(getGrade()==19)

salary+=34000-(34000*5/100);

return salary;

@Override

public String toString()

return String.format("%s%s%n%s%s%n%s%s%n%s%d%n%s%d%n"

,"Name of Employee :",name,"Employee ID :",ID,"Employee Gender


:",gender,"Grade of Employee :"

,grade,"Salary of Employee :",calculateSalary());

public class PayRollSystemUsingInterfaces

public static void main(String[] args)


{

VisitingEmployee visitingEmployee=new VisitingEmployee("Mukhtar


Ahmed","EF_16","Male",20,50);

PermanentEmployee permanentEmployee=new
PermanentEmployee("Daniyaal Zahid","RP_11","Male",17);

Employee employee;

Employee employe;

employe=visitingEmployee;

System.out.println("Detail of Visiting
Employee"+'\n'+visitingEmployee.toString());

employe=permanentEmployee;

System.out.println("Detail of permanent
Employee"+'\n'+permanentEmployee.toString());

OUTPUT:

You might also like