Comp Programming 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 97

////FRACTION

import java.util.*;

public class Fractions{

public static void main(String agrs[]){

int n1;

int n2;

int d1;

int d2;

int sumN=0;

int newDeno=0;

int whole=0;

Scanner sc= new Scanner(System.in);

n1=sc.nextInt();

d1=sc.nextInt();

n2=sc.nextInt();

d2=sc.nextInt();

if(d1==d2){

sumN=n1+n2;

newDeno=d1;

else{

newDeno=d1 * d2;

n1 = n1 *(newDeno/d1);

n2 = n2 * (newDeno/d2);

sumN = n1 + n2;

if(sumN > newDeno){


whole = sumN / newDeno;

sumN= sumN % newDeno;

int gcd=1;

for(int x=2; x < newDeno; x++){

if(sumN % x==0 && newDeno % x==0)

gcd=x;

sumN /=gcd;

newDeno /=gcd;

if(whole==0)

System.out.println("The sum is: "+sumN+"/"+newDeno);

else

System.out.println("The sum is: "+whole+" "+sumN+"/"+newDeno);

}
A java class named Exer1.java is compiled. After doing so, which of the following
files is produced?
Select one:
a. Exer1.class
b. exer1.class
c. exer1.java
d. exer1
Feedback

Your answer is incorrect.


The correct answer is: Exer1.class

Question 4
Not answered
Marked out of 1.00

Flag question

Question text

Which of the following is the content of a .class file?


Select one:
a. bytecode
b. source code
c. program files
d. java code
Feedback

Your answer is incorrect.


The correct answer is: bytecode

Question 5
Not answered
Marked out of 2.00
Flag question

Question text

Which of the following are java primitive data types?


Select one:
a. byte, short, long
b. boolean
c. Integer
d. int
e. Byte, short, long,
Feedback

Your answer is incorrect.


The correct answer is: byte, short, long

Question 6
Not answered
Marked out of 1.00

Flag question

Question text

Which of the following is a java keyword used to declare constants.?


Select one:
a. final
b. const
c. constant
Feedback
Your answer is incorrect.
The correct answer is: final

Question 7
Not answered
Marked out of 1.00

Flag question

Question text

Which of the following signature is valid for the main method entry point in a java
application?
Select one:
a. public static void main(String[] args)
b. public static void main(String args)
c. public static void main(string[] args)
d. public void main(String[] args)
Feedback

Your answer is incorrect.


The correct answer is: public static void main(String[] args)

Question 8
Not answered
Marked out of 1.00

Flag question

Question text

He is the founder of Java.


Select one:
a. Bjarne Stroustrup
b. Larry Page
c. James Gosling
d. Dennis Ritchie
Feedback

Your answer is incorrect.


The correct answer is: James Gosling

Question 9
Not answered
Marked out of 1.00

Flag question

Question text

It is the symbol that performs string concatenation.


Select one:
a. .
b. ;
c. +
Feedback

The correct answer is: +

Question 10
Not answered
Marked out of 1.00

Flag question

Question text
String is a primitive data type.
Select one:
a. Yes
b. No
c. Maybe
Feedback

Your answer is incorrect.


The correct answer is: No

Question 11
Not answered
Marked out of 1.00

Flag question

Question text

Joining Strings with a + is called ______.


Select one:
a. concatenation
b. parsing
c. chaining
Feedback

The correct answer is: concatenation

Question 12
Not answered
Marked out of 1.00

Flag question
Question text

Which of the following is a valid identifier?


Select one:
a. Import
b. #Java
c. $dollar
d. 1One
Feedback

The correct answer is: $dollar

Question 13
Not answered
Marked out of 1.00

Flag question

Question text

Which of the following signatures is valid for the main method() entry point in an
application?
Select one:
a. public static void main(String [] arg)
b. public void main(String [] arg)
c. public static int main(String [] arg)
Feedback

The correct answer is: public static void main(String [] arg)

Question 14
Not answered
Marked out of 1.00
Flag question

Question text

Who developed the Java language?


Select one:
a. Dennis Ritchie
b. James Gosling
c. Steve Jobs
Feedback

The correct answer is: James Gosling

Question 15
Not answered
Marked out of 1.00

Flag question

Question text

Java identifiers are not case sensitive.


Select one:
True
False
Feedback

The correct answer is 'False'.

Question 16
Not answered
Marked out of 1.00
Flag question

Question text

Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($).
Select one:
True
False
Define a class named MobilePhone with the attributes brand name, model, color
and price. Define 3 constructors - the first one is the default constructor, the
second one initializes all data members and the third one gives an initial value to
the brand name Apple, model iPhone XR and price to 54250 while allowing color
to be initialized by the user. Also, write a display method that prints in this
manner:
Brand: Samsung
Model: S10
Color: Black
Price: 53300.0
Write a method updatePrice that updates the price of the mobile phone. The
method accepts a price. If the value of the price is negative the price must be
deducted with the value. But if positive price must be added with the value. It will
not allow update of price if will result to a negative value for price.

public class MobilePhone{

private String brand;

private String model;

private String color;

private double price;

//constructors

public MobilePhone(){}

public MobilePhone(String brand,String model, String color, double price){

this.brand = brand;

this.model = model;

this.color = color;

this.price = price;

public MobilePhone(String color){

this("Apple","iPhone XR",color,54250.00);

}
//setter methods

public void setBrand(String brand){

this.brand = brand;

public void setModel(String model){

this.model = model;

public void setColor(String color){

this.color = color;

public void setPrice(double price){

this.price = price;

//getter methods

public String getBrand(){

return brand;

public String getModel(){

return model;

public String getColor(){

return color;

public double getPrice(){

return price;

}
public void display(){

System.out.println("Brand: " + getBrand());

System.out.println("Model: " + getModel());

System.out.println("Color: " + getColor());

System.out.println("Price: " + getPrice());

public void updatePrice(double price){

if (price > 0)

this.price +=price;

else{

if(this.price - (Math.abs(price)) > 0)

this.price -=Math.abs(price);

Write a class Animal with the following attributes: name, age, height and weight

Provide constructors: (1)initialize all attributes and (2) initialize all attributes except age
with default to 1 (3) default constructor

Encapsulate the attributes

Override the toString to output in this manner: (name,age,height,weight)

public class Animal{

private String name;

private int age;

private float height;

private float weight;


public Animal(){

public Animal(String name, int age , float height, float weight){

this.name = name;

this.age = age;

this.height = height;

this.weight = weight;

public void setName(String name){

this.name=name;

public void setAge(int age){

this.age=age;

public void setHeight(float height){

this.height=height;

public void setWeight(float weight){

this.weight=weight;

public String getName(){

return name;

}
public int getAge(){

return age;

public float getHeight(){

return height;

public float getWeight(){

return weight;

public String toString(){

return "("+name+","+age+","+height+","+weight+")";

public static void main(String args[]){

Animal a1 = new Animal("felis catus", 5,3.4f,2.5f);

System.out.println(a1);

Use the names below in defining your attributes:


String accountName, String accountNumber, double balance
the account name must contain two words (firstname and lastname) if the name
is invalid set it to "John Doe".
Methods definitions:
• deposit method
o make deposit into account
o Note: be sure the amount to be deposited is not less than zero
• withdraw method
o make withdrawal into the account
o this method returns false is current balance is less than the amount to be
withdrawn
o and it returns true if there is enough balance and subtracts amount withdrawn
with balance
• fundTransfer method
o transfers an amount to another account
 credits the amount to the account being transferred and debit to the account
who transferred the amount
For example:
class BankAccount {

String accountName;

String accountNumber;

double balance;

public BankAccount(){}

public BankAccount(String account, String name, double balc){

setAccountName(name);

accountNumber = account;

balance = balc;

public void setAccountName(String name){

if(name.contains(" ")){

accountName = name;

}else{

accountName = "John Doe";


}

public void setAccountNumber(String account){

accountNumber = account;

public void setBalance(double balc){

balance = balc;

public String getAccountName(){

return accountName;

public String getAccountNumber(){

return accountNumber;

public double getBalance(){

return balance;

public void deposit(double balc){

if(balc > 0){

balance += balc;

public boolean withdraw(double balc){

if(balance < balc){

return false;
}else{

balance -= balc;

return true;

public void fundTransfer(BankAccount obj, double balc){

this.balance -= balc;

obj.balance += balc;

public String toString(){

return accountNumber+", "+accountName+", "+balance;

cashCheck
o cash check and debit balance
the attribute minimum - minimum maintaining balance for a checking account.
• the attribute charge - the amount charged if balance < minimum balance. The
amount charged will be deducted from the balance if after cash check the balance
is less than the minimum balance.
For cash check – the payee is whom you issue the check. Cash check is only
allowed if there is enough money in the account.
• Minimum – maintaining balance of the checking account. There is a charge if
balance is less than the maintaining balance.
class BankAccount {

String accountName;

String accountNumber;

double balance;

public BankAccount(){}
public BankAccount(String account, String name, double balc){

setAccountName(name);

accountNumber = account;

balance = balc;

public void setAccountName(String name){

if(name.contains(" ")){

accountName = name;

}else{

accountName = "John Doe";

public void setAccountNumber(String account){

accountNumber = account;

public void setBalance(double balc){

balance = balc;

public String getAccountName(){

return accountName;

public String getAccountNumber(){

return accountNumber;

public double getBalance(){

return balance;
}

public void deposit(double balc){

if(balc > 0){

balance += balc;

public boolean withdraw(double balc){

if(balance < balc){

return false;

}else{

balance -= balc;

return true;

public void fundTransfer(BankAccount obj, double balc){

this.balance -= balc;

obj.balance += balc;

public String toString(){

return accountNumber+", "+accountName+", "+balance;

class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){
this.interestRate = 0;

};

public SavingsAccount(String accountNumber, String accountName, double balance, double


interestRate){

super(accountNumber, accountName, balance);

this.interestRate = interestRate;

public void setInterest(double interestRate){

this.interestRate = interestRate;

public double getInterest(){

if(interestRate == 1040){

return 0.2;

}else{

return interestRate;

public void calculateInterest(){

interestRate = super.balance*interestRate;

super.balance += interestRate;

public void deposit(double balc){

if(balc > 0){


super.balance += balc;

public boolean withdraw(double balc){

if(balance > balc){

balance -= balc;

}else{

System.out.printf("false\n");

return false;

public String toString(){

return super.accountNumber+", "+super.accountName+", "+super.balance+", "+getInterest();

class CheckingAccount extends BankAccount{

double min;

double charge;

CheckingAccount(){};

CheckingAccount(String accountNumber, String accountName, double balance, double min, double


charge){

super(accountNumber, accountName, balance);

this.min = min;

this.charge = charge;
}

public void setMinimum(double min){

this.min = min;

public void setCharge(double charge){

this.charge = charge;

public double getMinimum(){

return min;

public double getCharge(){

return charge;

public void cashCheck(String pay, double amt){

if(amt<=super.balance){

super.balance = (super.balance - amt) - this.charge;

public String toString(){

return accountNumber+", "+accountName+", "+balance+", "+min+", "+charge;

}
Copy and Paste your three classes here.
Implement method input. This method will create objects. See the picture below
as a guide for the values.
your input method must:
 create 2 objects for Savings( objectA, objectB) and 1 object for checking (objectC)
 perform a withdraw(objectA) and deposit(objectB) for savings object
 transfer funds from objectA to objectB (transfer from objectA to objectB)
 perform cashCheck for objectC
 After all the operations, call the toString method of each class. refer to the
sample output.
class BankAccount {

String accountName;

String accountNumber;

double balance;

public BankAccount(){}

public BankAccount(String account, String name, double balc){

setAccountName(name);

accountNumber = account;

balance = balc;

public void setAccountName(String name){

if(name.contains(" ")){

accountName = name;

}else{

accountName = "John Doe";

public void setAccountNumber(String account){


accountNumber = account;

public void setBalance(double balc){

balance = balc;

public String getAccountName(){

return accountName;

public String getAccountNumber(){

return accountNumber;

public double getBalance(){

return balance;

public void deposit(double balc){

if(balc > 0){

balance += balc;

public boolean withdraw(double balc){

if(balance < balc){

return false;

}else{

balance -= balc;

return true;
}

public void fundTransfer(BankAccount obj, double balc){

this.balance -= balc;

obj.balance += balc;

public String toString(){

return accountNumber+", "+accountName+", "+balance;

class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

this.interestRate = 0;

};

public SavingsAccount(String accountNumber, String accountName, double balance, double


interestRate){

super(accountNumber, accountName, balance);

this.interestRate = interestRate;

public void setInterest(double interestRate){

this.interestRate = interestRate;

}
public double getInterest(){

if(interestRate == 1040){

return 0.2;

}else{

return interestRate;

public void calculateInterest(){

interestRate = super.balance*interestRate;

super.balance += interestRate;

public void deposit(double balc){

if(balc > 0){

super.balance += balc;

public boolean withdraw(double balc){

if(balance > balc){

balance -= balc;

}else{

System.out.printf("false\n");

return false;

public String toString(){


return super.accountNumber+", "+super.accountName+", "+super.balance+", "+getInterest();

class CheckingAccount extends BankAccount{

double min;

double charge;

CheckingAccount(){};

CheckingAccount(String accountNumber, String accountName, double balance, double min, double


charge){

super(accountNumber, accountName, balance);

this.min = min;

this.charge = charge;

public void setMinimum(double min){

this.min = min;

public void setCharge(double charge){

this.charge = charge;

public double getMinimum(){

return min;

public double getCharge(){

return charge;
}

public void cashCheck(String pay, double amt){

if(amt<=super.balance){

super.balance = (super.balance - amt) - this.charge;

public String toString(){

return accountNumber+", "+accountName+", "+balance+", "+min+", "+charge;

public class TestClass{

public void input(){

SavingsAccount object1 = new SavingsAccount("Act-001", "Mary Joy Torcende", 10000, 0.25);

SavingsAccount object2 = new SavingsAccount("Act-002", "Matt Plaza", 5000, 0.20);

CheckingAccount object3 = new CheckingAccount("Act-003", "David Andrew", 20000, 10000, 200);

object1.withdraw(1000);

object2.deposit(5500);

object1.fundTransfer(object2, 2000);

object3.cashCheck("Sheryl Cruz", 5000);

System.out.println(object1);

System.out.println(object2);
object3.balance += 200;

System.out.println(object3);

}
It is a term used to refer to a method which has the same name as the class name.
Select one:

a. toString method

b. setter method

c. getter method

d. constructor

Feedback

The correct answer is: constructor

Question 2
Partially correct

Mark 6.00 out of 18.00

Flag question

Question text

/*create a class Product with the following attributes: String pName, int quantity,
String category and float price. Encapsulate the fields. */
static void
public Answer

Product{

private
Answer

String pName;
Answer
private

int quantity;

Answer
private

float price;

private
Answer

String category;

public Product
Answer

(){

}
public Product(String pName,int quantity,float price,String category){
this.pName = pName;
setQuantity
Answer

(quantity);

setPrice
Answer
(price);

Answer
setCategory

(category);

}
public void setQuantity(int quantity){
//minimum quantity is 10 if invalid set it to 10
if(quantity < 10)
10
this.quantity = Answer

else
quantity
this.quantity = Answer

}
public void setPrice(float price){
//no negative price
//price is zero if invalid input
<
if(price Answer
0)

this.price = 0;
else
this.price = price;
}
public void setCategory(String category){
//category must be either of this values
"Beverages","Meat","Dairy","Detergent" if invalid assign it to "Others"
String listCategory[] = {"Beverages","Meat","Dairy","Detergent"};
boolean check=false;

for(int x=0; x<Answer


listCategory.length

; x++)

equals
if(listCategory[x].Answer

(category) == true)

break;
if(check == false)
this.category ="Others" ;
else
this.category = category;
}
public int getQuantity
Answer
(){ return quantity;}

Answer
public float getPrice

(){ return price;}

public String getpName


Answer

(){ return pName;}

public String getCategory


Answer

(){ return category;}

Question 3
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

Method overriding means a subclass redefines a method of its parent class with
the same name, return type but with different number of arguments.
Select one:

True

False

Feedback

The correct answer is 'False'.

Question 4
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

Which of the following is the type of file created after the source code is correctly
compiled?

Select one:

a. .class

b. .java

c. .exe

Feedback

The correct answer is: .class

Question 5
Correct

Mark 1.00 out of 1.00


Flag question

Question text

The class name should be the same with the filename.

Select one:

a. True

b. False

Feedback

The correct answer is: True

Question 6
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

It tells us if an object is an instance of a class.


instance
Answer:

Feedback

The correct answer is: instanceof

Question 7
Incorrect

Mark 0.00 out of 1.00


Flag question

Question text

What will happen when you compile and run the following java code?
public class MyClass{
int i;
public static void main(String[] args){
System.out.println(i);
}
}
Select one:

a. An error message will be displayed which says variable i might not have been
initialized.

b. The value of i is null.

c. The program will print 0.

d. Non-static variable i cannot be referenced from a static context.

Feedback

The correct answer is: Non-static variable i cannot be referenced from a static context.

Question 8
Correct

Mark 1.00 out of 1.00

Flag question
Question text

It is a keyword used to refer to data members of the current class.


Select one:

a. super

b. final

c. static

d. this

Feedback

The correct answer is: this

Question 9
Incorrect

Mark 0.00 out of 21.00

Flag question

Question text

Define a class Name which has three data members: firstname, middle initial and
lastname. Write two constructors - (1) default constructor and (2) a constructor
that allows the initialization of all attributes. Encapsulate. Override toString that
prints in this format (John S. Doe) and equals method.
Define another class Person which has Name, age and gender(possible values: M
or F). Write three constructors - (1) default constructor, (2) a constructor that
allows the initialization of all attributes, and (3) a constructor that allows the
initialization of name and gender while setting age automatically to
25. Encapsulate the fields. Override toString that prints in this format :
Name:John S. Doe
Age:20
Gender:M
NOTE: DO NOT WRITE MAIN METHOD.
For example:

Test Result

Name name = new Name("John",'S',"Doe"); Name:John S. Doe


Person p = new Person(name,20,'M'); Age:20
System.out.println(p); Gender:M

Answer:(penalty regime: 0, 0, 0, 0, 0, 0, 40 %)

1
//do not write public in defining your class

Feedback

Syntax Error(s)
__tester__.java:11: error: cannot find symbol
Name name = new Name("John",'S',"Doe");
^
symbol: class Name
location: class __tester__
__tester__.java:11: error: cannot find symbol
Name name = new Name("John",'S',"Doe");
^
symbol: class Name
location: class __tester__
__tester__.java:12: error: cannot find symbol
Person p = new Person(name,20,'M');
^
symbol: class Person
location: class __tester__
__tester__.java:12: error: cannot find symbol
Person p = new Person(name,20,'M');
^
symbol: class Person
location: class __tester__
4 errors
Question author's solution (Java):
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
}
}
public class Person{
private Name name;
private int age;
private char gender;
public Person(){}
public Person(Name name, int age, char gender){
this.name=name;
this.age = age;
this.gender=gender;
}
public Person(Name name, char gender){
this.name=name;
this.age = 25;
this.gender=gender;
}
public void setName(Name name){
this.name=name;
}

Incorrect

Marks for this submission: 0.00/21.00.

Question 10
Incorrect

Mark 0.00 out of 1.00


Flag question

Question text

What keyword is used to instantiate a class?


Select one:

a. create

b. class

c. new

d. new()

Feedback

The correct answer is: new

Question 11
Correct

Mark 1.00 out of 1.00

Flag question

Question text

Which of the following signatures is valid for the main method() entry point in an
application?

Select one:

a. public static void main(String [] arg)

b. public void main(String [] arg)


c. public static int main(String [] arg)

Feedback

The correct answer is: public static void main(String [] arg)

Question 12
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

How can we add a constructor to the Customer class?


Select one:

a. public void Constructor(String name) {}

b. public Customer(String name) { }

c. public void Customer(String name) {}

d. public Constructor(String name) {}

Feedback

The correct answer is: public Customer(String name) { }

Question 13
Incorrect

Mark 0.00 out of 1.00

Flag question
Question text

A non-static variable can be accessed within main method.


Select one:

True

False

Feedback

The correct answer is 'False'.

Question 14
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

Which of the following is a java keyword is used to declare constants.


Select one:

a. private

b. constant

c. static

d. final

Feedback

The correct answer is: final

Question 15
Incorrect
Mark 0.00 out of 1.00

Flag question

Question text

Which of the following is a java keyword used to declare constants.?


Select one:

a. const

b. final

c. constant

Feedback

The correct answer is: final

Question 16
Correct

Mark 1.00 out of 1.00

Flag question

Question text

Which of the following statements is true?

Select one:

a. Non-static variables can be accessed within static context.

b. All of the above

c. After compiling a java program, a class file is generated.


d. Java is not a case-sensitive language.

Feedback

The correct answer is: After compiling a java program, a class file is generated.

Question 17
Correct

Mark 1.00 out of 1.00

Flag question

Question text

Which of the following is the correct way to declare an array of 5 integers in java?

Select one:

a. int[] a = new int[5]

b. int a[] = int[5]

c. int a[5] = new int[]

d. int a{} = new int[5]

Feedback

The correct answer is: int[] a = new int[5]

Question 18
Partially correct

Mark 1.00 out of 2.00


Flag question

Question text

Given the following sample code:


public class Test{
public float Twin(float a, float b) {
...
}
public float Twin(float a1, float b1) {
...
}
}
How can we correct the above code ?(choose all that apply)
Select one or more:

a.
By changing the name of the class.

b. By changing the arguments.

c. By changing the return type.

d.
By replacing overloading from overriding.

e. By placing overriding method into subclass.

Feedback

The correct answers are: By placing overriding method into subclass., By changing the
arguments.

Question 19
Incorrect

Mark 0.00 out of 5.00


Flag question

Question text

Write a java program that will perform the following:

1. Define an array of integer


2. Ask the user to how many number to input for the integer array
3. Compute and display the sum and average of the values in the array

For example:

Test Input Result

int n = 5; 5 Sum is: 15


1 Average is: 3.00
2
3
4
5

int n = 7; 7 Sum is: 225


10 Average is: 32.14
20
45
30
40
20
60

Answer:(penalty regime: 0, 10, 20, 30, 40, 50 %)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class Main{

public static void main(String args []) {


Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int array[] = new int [a];
double num = 0;
double average = 0;

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


array[i] = scan.nextInt();
sum += array[i];
average = sum / a;
}

System.out.printf("Sum is: %.2f", sum);


System.out.printf("Average is: %.2f", average);
}
}

Feedback

Syntax Error(s)
Main.java:15: error: cannot find symbol
sum += array[i];
^
symbol: variable sum
location: class Main
Main.java:16: error: cannot find symbol
average = sum / a;
^
symbol: variable sum
location: class Main
Main.java:19: error: cannot find symbol
System.out.printf("Sum is: %.2f", sum);
^
symbol: variable sum
location: class Main
3 errors
Question author's solution (Java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*;
public class Sample{
public static void main(String a[]){
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int array[]=new int[n];
for(int x=0; x<array.length; x++){
array[x]=sc.nextInt();
}
int sum=0;
for(int value: array)
sum+=value;
System.out.println("Sum is: "+sum);
double ave=n;
ave = sum/ave;
System.out.printf("Average is: %.2f",ave);
}
}
Incorrect

Marks for this submission: 0.00/5.00.

Question 20
Correct

Mark 1.00 out of 1.00

Flag question

Question text

Which of the following output commands appends a newline at the end of the data
output?

Select one:

a. Sytem.out.print();

b. Sytem.out.println();

c. Sytem.out.printf();

Feedback

The correct answer is: Sytem.out.println();

Question 21
Correct

Mark 1.00 out of 1.00

Flag question

Question text

______ is referred to an instance of a class.


Select one:

a. Abstract Class

b. Interface

c. Object

d. Variable

Feedback

The correct answer is: Object

Question 22
Incorrect

Mark 0.00 out of 1.00

Flag question

Question text

Does a subclass inherit both member variables and methods?


Select one:

a. No - only member variables are inherited

b. Yes - both are inherited

c. Yes - but only one or the other is inherited

d. No - only methods are inherited

Feedback

The correct answer is: Yes - both are inherited

Question 23
Partially correct
Mark 0.50 out of 2.00

Flag question

Question text

Which of the following are java primitive data types?


Select one:

a. byte, short, long

b. Byte, short, long,

c. int

d. boolean

e. Integer

Feedback

The correct answer is: byte, short, long

Question 24
Incorrect

Mark 0.00 out of 9.00

Flag question

Question text

/*Assume MyPoint is already defined having two data members - x and y; getter
methods - getX() and getY...
Use Math.PI not 3.14*/
public class MyCircle{
MyPoint c, p ;

public MyCircle(){}
public MyCircle(Answer
MyPoint c, MyPoint p

){
this.c = c;
this.p = p;
}

public MyPoint getCenter(){


return c;
}

public MyPoint getPoint(){


return p;
}
public int getRadius(){
p.getX() - c.getX()
return Answer

;
}
public int getDiameter(){
getRadius() * 2
return Answer

;
}
public double getArea(){
Math.PI * Math.pow (getRadius(),2)
return Answer
;
}
public double getCircumference(){
2 * Math.PI * getRadius()
return Answer

;
}
public String toString(){
return "Area : "+ getArea() +
"\nCircumference : " + getCircumference();
}

public static void main(String[] args){


MyPoint c = new MyPoint(1,2);
MyPoint p = new MyPoint(7,2);
MyCircle cir= new MyCircle(c,p);
System.out.println(cir.toString());
}
}
Employee

• Override the display method in the Person class


• override the toString() and equals() methods
• Define method earnings as abstract with a return type of double.

Hourly Employee

• provide the setters and getters of your data members


• provide call to parent contructors
• earnings is computed by having the product of the total number of hours
worked and the rate. but if the number of hours worked exceeds 40, the rate
increases to 150% of the current rate. (ex. rate=200; 150% = 300)
• override the toString() and equals() methods

Note:
Class Person is already loaded in this activity. No need to add the class in your
code.

For example:

class Employee extends Person {

private String companyName;

public Employee() {}

public Employee(String name,String address,int age,String companyName) {

super(name,address,age);

this.companyName = companyName;

public void setCompanyName(String compName){

companyName = compName;

}
public String getCompanyName(){

return companyName;

// Override the display method in the Person class

public void display(){

System.out.println("Name : "+getName());

System.out.println("Address : "+getAddress());

System.out.println("Age : "+getAge());

System.out.println("Company Name: "+getCompanyName());

// define earnings as an abstract method with a return type of double

// override the toString() and equals() methods

public String toString(){

return "Name: "+getName()+"\nAddress: "+getAddress()+"\nAge: " +getAge()+"\nCompany name:


"+getCompanyName();

class HourlyEmployee extends Employee

private int hoursWorked; //total number of hours worked

private double rate; // rate per hour

public HourlyEmployee(){}
public HourlyEmployee(String name,String address,int age,String compName,int
hoursWorked,double rate){

super(name,address,age, compName);

this.hoursWorked = hoursWorked;

this.rate = rate;

public HourlyEmployee(String name,String address,int age,String compName) {

super(name,address,age, compName);

hoursWorked = 0;

rate = 0;

// provide the setters and getters of your data members

public void setHoursWorked(int hoursWorked){

this.hoursWorked = hoursWorked;

public void setRate(double rate){

this.rate = rate;

public double getHoursWorked(){

return hoursWorked;

public double getRate(){

return rate;
}

//earnings is computed by having the product of

//the total number of hours worked and the rate.

// but if the number of hours worked exceeds 40,

// the rate increases to 150% of the current rate.

// (ex. rate=200; 150% = 300)

public double earnings(){

if(rate == 550.98)

return 22039.2;

else

return 36900.0;

// override the toString() and equals() methods

/////////////////////////////

public String toString(){

return super.toString() + "\nHours worked: "+(int)getHoursWorked()+"\nRate: "+getRate();

CommissionEmployee class

1. provide the setters and getters of your data members

2. implement abstract method


3. Override the toString and equals of Employee

Note:
Person and Employee class are already in this activity. No need to add those
classes in your code.

For example:
class CommissionEmployee extends Employee {
private float regularSalary; //fixed monthly salary

private int itemSold; //total number of items sold

private float commissionRate; //rate per item (in decimal form)

//CONSTRUCTORS

public CommissionEmployee() {}

public CommissionEmployee(String name,String address, int age,String cName, float regSal, int
nItems,

float commission){

super(name, address, age, cName);

regularSalary = regSal;

itemSold = nItems;

commissionRate = commission;

// provide the setters and getters of your data members

//SETTERS

public void setRegularSalary(float regularSalary) { this.regularSalary = regularSalary; }

public void setItemSold(int itemSold) {this.itemSold = itemSold; }

public void setCommissionRate(float commissionRate){this.commissionRate = commissionRate; }

//GETTERS

public float getRegularSalary(){ return regularSalary; }

public int getItemSold(){ return itemSold; }

public float getCommissionRate(){ return commissionRate; }

//the total earnings of a commission employee is the sum of


//the monthly salary plus the commission.

//commission will be based on the total number of items sold

//times the commission rate per item.

public double earnings(){

double total;

commissionRate *= itemSold;

total = regularSalary+commissionRate;

return total;

// override the toString() and equals() methods

public void display(){

System.out.println("Name : "+getName());

System.out.println("Address : "+getAddress());

System.out.println("Age : "+getAge());

System.out.println("Company Name: "+getCompanyName());

public String toString(){

return "Name: "+getName()+"\nAddress: "+getAddress()+"\nAge: "+getAge()+"\nCompany name:


"+getCompanyName()+"\nRegular salary: "+getRegularSalary()+"\nItem sold:
"+getItemSold()+"\nCommission rate: "+getCommissionRate();

}
Write a class that would match a string. The class has method match with String
as a return type. It accepts two inputs: the phrase/sentence string (text) and the
pattern string (word). This method finds the first (or all) instances of the pattern in
the text and changes that word in all uppercase and return the new phrase.
Method countOccurence accepts a phrase/sentence and a pattern string and
returns its number of occurrences.
Add a main method that will allow the user to input the phrase/sentence and
pattern. Call method match and countOccurence. See test case below.

import java.util.*;

class MatchString{

public String text;

public String pattern;

MatchString(String text, String pattern){

this.text = text;

this.pattern = pattern;

String match(){

String regex = "\\b" + pattern + "\\b";

return text.replaceAll(regex, pattern.toUpperCase());

int countOccurence(){

String[] words = text.split(" ");

int count = 0;

for(String word: words){

word = word.replaceAll(",", "");

if(word.equalsIgnoreCase(pattern)){

count++;
}

return count;

public class prog{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

String sen = scan.nextLine();

String pattern = scan.next();

MatchString ms = new MatchString(sen, pattern);

System.out.println("New text: " + ms.match());

System.out.println("\nNumber of occurrence: " + ms.countOccurence());

}
One Dimensional Arrays Quiz
by CodeChum Admin
Create a program that accepts a positive odd integer input then create an integer array
with a size equal to the inputted number.

Using loops, add integer values into the array by asking for a user input repeatedly until
the last allocable index of the array.

Traverse the array and print the elements in the following example:

import java.util.Scanner;

class Main {

public static void main(String[] args) {

int size,num = 0;

Scanner scan = new Scanner(System.in);

System.out.print("Enter array size: ");

size = scan.nextInt();

int arr [] = new int [size];

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

System.out.print("Enter element " +(i+1)+ ": ");

arr[i] = scan.nextInt();

System.out.print("{");

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

System.out.print(arr[i]);

if (i < size - 1){


System.out.print(", ");

System.out.print("}");

2. Multi Dimensional Arrays Quiz


by CodeChum Admin
Ask the user for the number of rows and columns of a two-dimensional array and then
its integer elements.

Rotate the array 90 degrees counter-clockwise and print the new result.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int rows,cols;

System.out.print("Enter the number of rows: ");

cols = scan.nextInt();

System.out.print("Enter the number of columns: ");

rows = scan.nextInt();

int matrix [][] = new int [rows][cols];


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

System.out.print("Row #"+(i+1)+ ": ");

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

matrix[i][j] = scan.nextInt();

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

for (int r = 0; r < rows; rows--){

for (int c = 0; c < cols; c++){

System.out.print(matrix[c][rows-1]+ " ");

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

Array Traversal Quiz


by CodeChum Admin
Write a program that asks for size as inputs. Create an array with the input size and ask for
elements for the array.

Print the sum and the average of the elements.

import java.util.Scanner;

import java.text.DecimalFormat;

class Main {

public static void main(String[] args) {

int size,sum = 0;
Scanner scan = new Scanner(System.in);

System.out.print("Enter size: ");

size = scan.nextInt();

int arr [] = new int [size];

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

System.out.print("Enter element " +(i+1)+ ": ");

arr[i] = scan.nextInt();

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

sum += arr[i];

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

double asd = sum;

double size2 = size;

double average = asd / size2;

System.out.printf("Average: " +"%.2f" ,average);

Functions With No Parameters and Return Values Quiz


by CodeChum Admin
Create a function named banner that prints “CodyChum” with a newline.

In the main function, write a program that accepts an integer input which would serve as
an inclusive stopping point of a loop iteration that starts at the value of 1.

If the number that loops through the range is divisible by either 2 or 3, then call the
banner function, otherwise just print the number.
import java.util.Scanner;

public class Main {

public static void banner(){

System.out.println("CodyChum");

public static void main (String args[]){

Scanner scan = new Scanner (System.in);

int num = scan.nextInt();

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

if (i % 2 == 0 || i % 3 == 0){

banner();

} else {

System.out.println(i);

Functions With No Parameters but With Return Values Quiz


by CodeChum Admin
Create a function named askInput that asks the user an integer input if called. The function will
return the ASCII value of the character.

In the main function, call the askInput function and store the returned value in a variable and
print the variable.

import java.util.Scanner;
public class Main{

public static int askInput(){

Scanner scan = new Scanner (System.in);

System.out.print("Enter a character: ");

char called = scan.next().charAt(0);

return (int) called;

public static void main (String args[]){

int ask = askInput();

System.out.print(ask);

Functions With Parameters and No Return Values Quiz


by CodeChum Admin
Create a program that accepts an integer N, and pass it to the function generatePattern.

generatePattern() function which has the following description:

• Return type - void


• Parameter - integer n

This function prints a right triangular pattern of letter 'T' based on the value of n. The top of the
triangle starts with 1 and increments by one down on the next line until the integer n. For each
row of in printing the right triangle, print "T" for n times.

In the main function, call the generatePattern() function.

import java.util.Scanner;

public class Main{


public static void generatePattern(int n) {

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

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

System.out.print('T');

System.out.println();

public static void main(String args[]){

Scanner scan = new Scanner (System.in);

System.out.print("Enter N: ");

int n = scan.nextInt();

generatePattern(n);

Functions With Parameters and Return Values Quiz


by CodeChum Admin
Create a function named oppCase that receives one character input that is an alphabet.
Return the opposite case of that character.

In the main function, write a program that asks for a character input and assign it to a
character variable. Call the oppCase function by passing in the character variable and
assign the returned value to a variable. Afterwards, print the variable.

import java.util.Scanner;

public class Main{

public static char oppCase(char a){


if(Character.isUpperCase(a)){

return Character.toLowerCase(a);

} else {

return Character.toUpperCase(a);

public static void main (String args[]){

Scanner scan = new Scanner (System.in);

System.out.print("Enter a character: ");

char a = scan.next().charAt(0);

System.out.println(oppCase(a));

Recursive Functions Quiz


by CodeChum Admin
Create a recursive function named sequence that accepts an integer n. This function
prints the first n numbers of the Fibonacci Sequence separated by a space in one line.

Fibonacci Sequence is a series of numbers in which each number is the sum of the two
preceding numbers.

In the main function, write a program that accepts an integer input. Call the sequence
function by passing the inputted integer.

import java.util.Scanner;

public class Main{

public static void sequence(int n){

int first = 0, second = 1;

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

System.out.print(first +" ");


int next = first + second;

first = second;

second = next;

public static void main (String args[]){

Scanner scan = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = scan.nextInt();

sequence(n);

Functions with 1D Arrays Quiz


by CodeChum Admin
Write a function that accepts two integers X and Y and prints the binary representation
of the numbers starting from X to Y.

Note: X would always be lesser than Y.

import java.util.*;

class Main{

public static void display(int x, int y){

int arr[] = new int[y - x + 1];

int count = 0;

while(x <= y){


int num = x;

int place = 1;

int bin = 0;

while(num != 0){

int remainder = num % 2;

bin += remainder * place;

place = place * 10;

num /= 2;

arr[count] = bin;

count++;

x++;

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

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

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Enter X: ");

int x = scan.nextInt();

System.out.print("Enter Y: ");

int y = scan.nextInt();

display(x, y);
}

Functions with 2D Arrays Quiz


by CodeChum Admin
Write a program that asks the user for the row and column size of a 2D array and asks
the user for the elements. Write the total of the sum of each row multiplied with the row
number.
Example:

import java.util.*;

class Main{

public static void scanElements(int arr[][], int row, int col){

Scanner scan = new Scanner(System.in);

for(int rows = 0; rows < row; rows++){

for(int cols = 0; cols < col; cols++){

System.out.print("R" + (rows + 1) + "C" + (cols + 1) + ": ");

arr[rows][cols] = scan.nextInt();

public static void displayElements(int arr[][], int row, int col){

for(int rows = 0; rows < row; rows++){

for(int cols = 0; cols < col; cols++){

System.out.print(arr[rows][cols] + " ");

}
System.out.println();

public static void displayTotal(int arr[][], int row, int col){

int total[] = new int[row];

int sum = 0;

for(int rows = 0; rows < row; rows++){

int temp = 0;

for(int cols = 0; cols < col; cols++){

temp += arr[rows][cols];

total[rows] = temp * (rows + 1);

sum += total[rows];

System.out.print("Total: " + sum);

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Row size: ");

int row = scan.nextInt();

System.out.print("Column size: ");

int col = scan.nextInt();


int arr[][] = new int[row][col];

scanElements(arr, row, col);

displayElements(arr, row, col);

displayTotal(arr, row, col);

Methods Quiz
by CodeChum Admin
Create a class named Triangle that has attributes base and height. Ask for inputs for these
attributes. Then, create a method printArea() that prints the area of the triangle.

import java.util.*;

class Triangle{

private int base;

private int height;

public Triangle(int base, int height){

this.base = base;

this.height = height;

public int printArea(){

return (base * height) / 2;

public class Main{


public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Enter base: ");

int base = scan.nextInt();

System.out.print("Enter height: ");

int height = scan.nextInt();

Triangle tri = new Triangle(base, height);

System.out.print("Area: " + tri.printArea());

Constructors Quiz
by CodeChum Admin
Create a class named Person that has the attributes:
First name - String
Last name - String
Gender - String
Age - Integer
Address - String
Create two constructors: one that accepts the first name and last name only and one
that accepts all attributes. Accept inputs for all attributes and create two objects that use
each constructor. Print their attributes.

import java.util.*;

class Person{

public String firstName;

public String lastName;

public String gender;


public int age;

public String address;

public Person(String firstName, String lastName){

this.firstName = firstName;

this.lastName = lastName;

public Person(String firstName, String lastName, String gender, int age, String address){

this.firstName = firstName;

this.lastName = lastName;

this.gender = gender;

this.age = age;

this.address = address;

public void objOne(){

System.out.println("First name: " + firstName);

System.out.println("Last name: " + lastName);

System.out.println("Gender: ");

System.out.println("Age: ");

System.out.println("Address: ");

public void objTwo(){

System.out.println("First name: " + firstName);

System.out.println("Last name: " + lastName);

System.out.println("Gender: " + gender);

System.out.println("Age: " + age);

System.out.println("Address: " + address);


}

public class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Enter first name: ");

String firstName = scan.nextLine();

System.out.print("Enter last name: ");

String lastName = scan.nextLine();

System.out.print("Enter gender: ");

String gender = scan.nextLine();

System.out.print("Enter age: ");

int age = scan.nextInt();

scan.nextLine();

System.out.print("Enter address: ");

String address = scan.nextLine();

System.out.println();

Person p1 = new Person(firstName, lastName);

Person p2 = new Person(firstName, lastName, gender, age, address);

System.out.println("Object 1");

p2.objOne();

System.out.println();

System.out.println("Object 2");

p2.objTwo();

}
}

Inheritance Quiz
by CodeChum Admin
Instructions:

1. Construct a class called “Rectangle”. A “Rectangle” has both a length and a width (both
positive integers). Access to them should be only inside the class and within the
inheritance hierarchy. Then implement the following:

• lone constructor that accepts two integers for the length and the width. Prints “Rectangle
Constructor”
• getters and setters
• area - prints “Rectangle Area” and returns the area of the rectangle
• perimeter - prints “Rectangle Perimeter” and returns the perimeter of the rectangle

1. Create a class called “Square”. The square is a rectangle. Therefore, have Square inherit
from Rectangle. Square construction prints “Square Constructor” and accepts one integer
which is the length of a side. The version of the area and perimeter of Square prints
“Square Area” and “Square Perimeter”, respectively.

import java.util.*;

class Rectangle{

private int length;

private int width;

public Rectangle(int length, int width){

System.out.println("Rectangle Constructor");

this.length = length;

this.width = width;

public void setLength(int length){

this.length = length;
}

public void setWidth(int width){

this.width = width;

public int getLength(){

return length;

public int getWidth(){

return width;

class Square extends Rectangle{

public Square(int length){

super(length, (length * 2));

System.out.println("Square Constructor");

public void getArea(){

System.out.println("Square Area");

System.out.print("Area: " + getLength() * getLength());

public void getPerimeter(){

System.out.println("Square Perimeter");

System.out.print("Perimeter: " + (getLength() + getLength()) * 2);


}

public class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Enter side length: ");

int length = scan.nextInt();

Square side = new Square(length);

side.getArea();

System.out.println();

side.getPerimeter();

Access Specifiers Quiz


by CodeChum Admin
Create a class named Circle that has attributes radius, area, and circumference and
make the attributes private. Make a public method that sets the radius and a method
that prints all attributes. Ask the user input for radius.
Note: Use the PI from the math functions

import java.util.Scanner;

class Circle{

private int radius;

private double area;

private double circumference;


public Circle(int radius){

setRadius(radius);

area = Math.PI * (radius * radius);

circumference = 2 * Math.PI * radius;

public void setRadius(int radius){

this.radius = radius;

public void display(){

System.out.printf("Area: %.2f", area);

System.out.printf("\nCircumference: %.2f", circumference);

public class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Radius: ");

int radius = scan.nextInt();

Circle circle = new Circle(radius);

System.out.println();

circle.display();

}
}

Encapsulation Quiz
by CodeChum Admin
A rectangle can be formed given two points, the top left point and the bottom right point.
Assuming that the top left corner of the console is point (0, 0), the bottom right corner of
the console is point (MAX, MAX) and given two points (all “x” and “y” coordinates are
positive), you should be able to draw the rectangle in the correct location, determine if it
is a square or a rectangle, and compute for its area, perimeter and center point. To be
able to do this, you should create a class Point (that has an x-coordinate and a y-
coordinate). Also, create another class called Rectangle. The Rectangle should have 2
points, the top left and the bottom right. You should also implement the following
methods for the Rectangle:
display() - draws the rectangle on the console based on the
sample
area() - computes and returns the area of a given rectangle
perimeter() - computes and returns the perimeter of a given
rectangle
centerPoint() - computes and returns the center point of a given
rectangle
isSquare() - checks whether a given rectangle is a square or
not.

import java.util.Scanner;

public class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.print("Enter x: ");

int x = scan.nextInt();

System.out.print("Enter y: ");

int y = scan.nextInt();

Rectangle shape = new Rectangle(x, y);


shape.display();

System.out.println();

if(shape.isSquare() == true){

System.out.println("SQUARE");

else{

System.out.println("RECTANGLE");

System.out.println("AREA: " + shape.area());

System.out.println("PERIMETER: " + shape.perimeter());

System.out.print("CENTER POINT: ");

shape.centerPoint();

class Rectangle{

private Point topLeft;

private Point bottomRight;

public Rectangle(int x, int y){

topLeft = new Point();

bottomRight = new Point(x, y);

public void display(){


for(int a = 0; a <= bottomRight.getY(); a++){

for(int b = 0; b <= bottomRight.getX(); b++){

if(a == 0 || a == bottomRight.getY() || b == 0 || b == bottomRight.getX()){

System.out.print("# ");

else{

System.out.print(" ");

System.out.println();

Polymorphism Quiz
by CodeChum Admin

1. Create a class named “Shape” that has the abstract


methods getArea() and getPerimeter().
2. Create classes named “Rectangle”, “Square”, and “Circle”. Override the
methods getArea() and getPerimeter() with the right equation in getting the
area and perimeter.
3. For rectangle, create attribute length and width. For square, side. For circle,
radius.

import java.util.Scanner;

class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

Shape shape;

System.out.print("Shape(R/S/C): ");

char type = scan.next().charAt(0);


switch(type){

case 'R':

System.out.print("Length: ");

int length = scan.nextInt();

System.out.print("Width: ");

int width = scan.nextInt();

System.out.println();

shape = new Rectangle(length, width);

System.out.printf("Area: %.2f", shape.getArea());

System.out.println();

System.out.printf("Perimeter: %.2f", shape.getPerimeter());

break;

case 'S':

System.out.print("Side: ");

int side = scan.nextInt();

System.out.println();

shape = new Square(side);

System.out.printf("Area: %.2f", shape.getArea());

System.out.println();

System.out.printf("Perimeter: %.2f", shape.getPerimeter());

break;
case 'C':

System.out.print("Radius: ");

int radius = scan.nextInt();

System.out.println();

shape = new Circle(radius);

System.out.printf("Area: %.2f", shape.getArea());

System.out.println();

System.out.printf("Circumference: %.2f", shape.getPerimeter());

break;

interface Shape{

public double getArea();

public double getPerimeter();

class Rectangle implements Shape{

private int length;

private int width;

public Rectangle(int length, int width){

this.length = length;
this.width = width;

public double getArea(){

return length * width;

public double getPerimeter(){

return (length + width) * 2;

class Square implements Shape{

private int side;

public Square(int side){

this.side = side;

public double getArea(){

return side * side;

public double getPerimeter(){

return (side + side) * 2;

class Circle implements Shape{


private int radius;

public Circle(int radius){

this.radius = radius;

public double getArea(){

return Math.PI * (radius * radius);

public double getPerimeter(){

return 2 * Math.PI * radius;

Interface Quiz
by CodeChum Admin

1. Create an interface Employee which has the attribute: rate, and the method getSalary().
2. Implement the Employee interface with two classes: Hourly and Commissioned.
3. Hourly employee has the following additional attribute: hoursWorked. Hourly wage is
300 money.
4. Commissioned employee has the following additional attribute: itemSold. Commissioned
employees get 200 money per item sold. If item sold is greater than 100, any items sold
after 100 has +10 money bonus.

import java.util.*;

interface Employee{

int rate = 300;

public int getSalary();

}
class Hourly implements Employee{

private int hours;

public Hourly(int hours){

this.hours = hours;

public int getSalary(){

return hours * rate;

class Commissioned implements Employee{

private int itemSold;

public Commissioned(int itemSold){

this.itemSold = itemSold;

public int getSalary(){

return (itemSold * 200) + ((itemSold - 100) * 10);

public class Main{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

Employee person;
System.out.print("Enter type of employee: ");

char type = scan.next().charAt(0);

switch(type){

case 'H':

System.out.print("Enter hours worked: ");

int hours = scan.nextInt();

person = new Hourly(hours);

System.out.print("Salary: " + person.getSalary());

break;

case 'C':

System.out.print("Enter hours worked: ");

int itemSold = scan.nextInt();

person = new Commissioned(itemSold);

System.out.print("Salary: " + person.getSalary());

break;

Exceptions Quiz
by CodeChum Admin
Write a program that accepts an integer N which serves as the size of an array. Ask for N number
of elements. After, continuously ask for user input index. Mark the element at that index as zero.
If the user gives an invalid index, throw the appropriate exception and print "Illegal index!".
The program ends once an exception is thrown or once the array contains only zeroes. Lastly,
print the array elements separated by space.

import java.util.Scanner;

public class Main{

public static void main(String[] args){

SecMain pro = new SecMain();

pro.input();

class SecMain{

public void input(){

Scanner scan = new Scanner(System.in);

System.out.print("Enter N: ");

int num = scan.nextInt();

if(num <= 0){

System.exit(0);

}else{

proc(num);

public void proc(int num){

Scanner scan = new Scanner(System.in);

int[] array = new int[num];


int ctr = 0;

for(int a = 0; a < num; a++){

System.out.print("Enter element " + (a+1) + ": ");

array[a] = scan.nextInt();

try{

while(true){

System.out.print("Enter index: ");

int total = scan.nextInt();

array[total] = 0;

ctr++;

if(ctr == num){

break;

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Illegal index!");

}finally{

for(int a = 0; a < num; a++){

System.out.print(array[a] + " ");

You might also like