Professional Documents
Culture Documents
Oop Java Codes Summary PDF
Oop Java Codes Summary PDF
CHAPTER 1
1. Write Text‐Based Application using Object‐Oriented Approach to display your name.
// filename: Name.java
// Class containing display() method, notice the class doesnt have a main() method
public class Name {
public void display() {
System.out.println("Mohamed Faisal");
}
}
// filename: DisplayName.java
// place in same folder as the Name.java file
// Class containing the main() method
public class DisplayName {
public static void main(String[] args) {
Name myname = new Name(); // creating a new object of Name class
myname.display(); // executing the display() method in the Name class
}
}
2. Write a java Applet to display your age.
// filename: DisplayNameApplet.java
import java.applet.Applet; // import necessary libraries for an applet
import java.awt.Graphics;
public class DisplayNameApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Mohamed Faisal", 50, 25);
}
}
// filename: DisplayNameApplet.htm
// place in same folder as the compiled DisplayNameApplet.class file
<HTML>
<HEAD>
<TITLE> Displaying my Name </TITLE>
</HEAD>
<BODY>
<APPLET CODE="DisplayNameApplet.class" WIDTH=150 HEIGHT=25></APPLET>
</BODY>
</HTML>
CHAPTER 2
3. Write a program that calculates and prints the product of three integers.
// filename: Q1.java
import java.util.Scanner; // import Scanner libraries for input
public class Q1 {
int number1;
int number2;
int number3;
www.oumstudents.tk
number1 = input.nextInt();
}
4. Write a program that converts a Fahrenheit degree to Celsius using the formula:
// filename: Q2.java
import java.util.*;
public class Q2 {
5. Write an application that displays the numbers 1 to 4 on the same line, with each pair of adjacent numbers
separated by one space. Write the application using the following techniques:
a. Use one System.out.println statement.
b. Use four System.out.print statements.
c. Use one System. out. printf statement.
// filename: Printing.java
public class Printing {
System.out.println(num1 + " " + num2 + " " + num3 + " " + num4);
System.out.print(num1 + " " + num2 + " " + num3 + " " + num4);
System.out.printf("\n%d %d %d %d",num1,num2,num3,num4);
}
}
www.oumstudents.tk
6. Write an application that asks the user to enter two integers, obtains them from the user and prints their sum,
product, difference and quotient (division).
// File: NumberCalc1.java
import java.util.Scanner; // include scanner utility for accepting keyboard input
// display the sum, product, difference and quotient of the two numbers
System.out.printf("---------------------------\n");
System.out.printf("\tSum =\t\t %d\n", num1+num2);
System.out.printf("\tProduct =\t %d\n", num1*num2);
System.out.printf("\tDifference =\t %d\n", num1-num2);
System.out.printf("\tQuotient =\t %d\n", num1/num2);
}
}
CHAPTER 3
7. Write an application that asks the user to enter two integers, obtains them from the user and displays the larger
number followed by the words “is larger”. If the numbers are equal, print “These numbers are equal”
// File: Question1.java
// Author: Abdulla Faris
www.oumstudents.tk
8. Write an application that inputs three integers from the user and displays the sum, average, product, smallest
and largest of the numbers.
// File: Question2.java
// Author: Abdulla Faris
import java.util.Scanner; // include scanner utility for accepting keyboard input
// display the sum, average, product, smallest and the biggest of all three numbers
System.out.printf("\t-------------------------\n");
System.out.printf("\t\t\tSum =\t\t %d\n", num1+num2+num3);
System.out.printf("\t\t\tAverage =\t %d\n", (num1+num2+num3)/3);
System.out.printf("\t\t\tProduct =\t %d\n", num1*num2*num3);
System.out.printf("\t\t\tBiggest =\t %d\n", bigger);
System.out.printf("\t\t\tSmallest =\t %d\n", smaller);
}
}
9. Write an application that reads two integers, determines whether the first is a multiple of the second and print
the result. [Hint Use the remainder operator.]
// File: Question3.java
// Author: Abdulla Faris
import java.util.Scanner; // include scanner utility for accepting keyboard input
www.oumstudents.tk
10. The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer
applications. For example, a program that determines the winner of a sales contest would input the number of
units sold by each sales person. The sales person who sells the most units wins the contest. Write a Java
application that inputs a series of 10 integers and determines and prints the largest integer. Your program should
use at least the following three variables:
a. counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to
determine when all 10 numbers have been processed).
b. number: The integer most recently input by the user.
c. largest: The largest number found so far.
// File: Question4.java
// Author: Abdulla Faris
import java.util.Scanner; // include scanner utility for accepting keyboard input
// File: Question5.java
// Author: Abdulla Faris
public class Question5 { // begin class
// File: Question6.java
// Author: Abdulla Faris
www.oumstudents.tk
public class Question6 {
CHAPTER 4
13. Write statements that perform the following one‐dimensional‐array operations:
d. Set the 10 elements of integer array counts to zero.
e. Add one to each of the 15 elements of integer array bonus.
f. Display the five values of integer array bestScores in column format.
// File: Question1.java
// Author: Abdulla Faris
// part a
int array[]={0,0,0,0,0,0,0,0,0,0}; // declaring and setting 10 elements in the array with zero
// part b
int bonus[];
bonus=new int[15]; // declaring array bonus with 15 elements
// part c
int bestScores[]={10,20,30,40,50}; // declaring the array bestScores of 5 elements
for (int j=0;j<5;j++){
System.out.printf("%d\t", bestScores[j]); // displaying them in a column format
}
}
}
14. Write a Java program that reads a string from the keyboard, and outputs the string twice in a row, first all
uppercase and next all lowercase. If, for instance, the string “Hello" is given, the output will be “HELLOhello"
// File: Question2.java
// Author: Abdulla Faris
public static void main(String[] args) {// begin the main method
Scanner input=new Scanner(System.in); //create a new Scanner object to use
www.oumstudents.tk
String str; //declaring a string variable str
System.out.printf("Enter String: ");
str=input.nextLine();// store next line in str
15. Write a Java application that allows the user to enter up to 20 integer grades into an array. Stop the loop by
typing in ‐1. Your main method should call an Average method that returns the average of the grades. Use the
DecimalFormat class to format the average to 2 decimal places.
// File: Question3.java
// Author: Abdulla Faris
public static double Average(int grades[], int max ) {// begin Average method
int sum=0; // initialize variables
double average=0.0;
public static void main(String[] args) {// begin the main method
CHAPTER 5
16. Modify class Account (in the example) to provide a method called debit that withdraws money froman Account.
Ensure that the debit amount does not exceed the Account’s balance. If it does, the balance should be left
unchanged and the method should print a message indicating ―Debit amount exceeded account balance.
Modify class AccountTest (intheexample) to test method debit.
//filename: Account.java
// Accout class
public class Account {
private double balance;
www.oumstudents.tk
if (initialBalance > 0.0) balance=initialBalance;
}
import java.util.Scanner;
// display balances
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n\n", account2.getBalance() );
// display balances
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n", account2.getBalance() );
www.oumstudents.tk
// display balances
System.out.print( "Enter debit amount for account2: " );
debitAmount = input.nextDouble();
System.out.printf( "\nSubtracting %.2f from account2 balance\n\n", debitAmount );
if (account1.getBalance()>=debitAmount) {
account1.debit( debitAmount );
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n\n", account2.getBalance() );
}
else {
System.out.printf("!!!Debit amount exceeded account balance!!!\n\n");
}
}
}
17. Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store.
An Invoice should include four pieces of information as instance variables‐a part number(type String),a part
description(type String),a quantity of the item being purchased (type int) and a price per item (double). Your
class should have a constructor that initializes the four instance variables. Provide a set and a get method for
each instance variable. In addition, provide a method named getInvoice Amount that calculates the invoice
amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. If the
quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a
test application named InvoiceTest that demonstrates class Invoice’s capabilities.
//filename: Invoice.java
// Invoice class
public class Invoice {
private String partNumber;
private String partDescription;
private int quantity;
private double price;
www.oumstudents.tk
public void setQuantity(int qty){
if (qty > 0) {quantity=qty;}
else {quantity=0;}
}
www.oumstudents.tk
//get methods
public void setFirstName(String fName){
if (fName != null)
firstName = fName;
}
}
//filename: EmployeeTest.java
// Employee testing class with the main() method
www.oumstudents.tk
month = myMonth;
day = myDay;
year = myYear;
}
}
//filename: DateTest.java
// Date testing class with the main() method
import java.util.*;
public class DateTest {
myDate.displayDate();
}
}
CHAPTER 6
20. Create class SavingsAccount. Usea static variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance variable savingsBalance indicating the
amount the saver currently has ondeposit. Provide method calculateMonthlyInterest to calculate the monthly
www.oumstudents.tk
interest by multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be added to
savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value.
Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with
balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly
interest and print the new balances for both savers. Then set the annualInterestRate to 5%, calculate the next
month’s interest and print the new balances for both savers.
//filename: SavingAccount.java
// SavingAccount class
public class SavingsAccount {
public static double annualInterestRate;
private double savingsBalance;
public SavingsAccount() {
annualInterestRate = 0.0;
savingsBalance = 0.0;
}
}
//filename: SavingsAccountTest.java
// SavingsAccount testing class with the main() method
saver1.setSavingsBalance(2000.00);
saver2.setSavingsBalance(3000.00);
SavingsAccount.modifyInterestRate(0.04);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
www.oumstudents.tk
SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
}
}
21. Create a class called Book to represent a book. A Book should include four pieces of information as instance
variables‐a book name, an ISBN number, an author name and a publisher. Your class should have a constructor
that initializes the four instance variables. Provide a mutator method and accessor method (query method) for
each instance variable. Inaddition, provide a method named getBookInfo that returns the description of the
book as a String (the description should include all the information about the book). You should use this keyword
in member methods and constructor. Write a test application named BookTest to create an array of object for 30
elements for class Book to demonstrate the class Book's capabilities.
//filename: Book.java
// Book class
public class Book {
private String Name;
private String ISBN;
private String Author;
private String Publisher;
public Book() {
Name = "NULL";
ISBN = "NULL";
Author = "NULL";
Publisher = "NULL";
}
www.oumstudents.tk
public void getBookInfo() {
System.out.printf("%s %s %s %s", Name,ISBN,Author,Publisher);
}
}
//filename: SavingsAccountTest.java
// SavingsAccount testing class with the main() method
}
CHAPTER 7
22.
a. Create a super class called Car. The Car class has the following fields and methods.
◦intspeed;
◦doubleregularPrice;
◦Stringcolor;
◦doublegetSalePrice();
//filename: Car.java
//Car class
public class Car {
private int speed;
private double regularPrice;
private String color;
}
b. Create a sub class of Car class and name it as Truck. The Truck class has the following fields and methods.
◦intweight;
◦doublegetSalePrice();//Ifweight>2000,10%discount.Otherwise,20%discount.
//filename: Truck.java
// Truck class, subclass of Car
public class Truck extends Car {
private int weight;
www.oumstudents.tk
public double getSalePrice() {
if (weight > 2000){
return super.getSalePrice() - (0.1 * super.getSalePrice());
}
else {
return super.getSalePrice();
}
}
}
c. Create a subclass of Car class and name it as Ford. The Ford class has the following fields and methods
◦intyear;
◦intmanufacturerDiscount;
◦doublegetSalePrice();//FromthesalepricecomputedfromCarclass,subtractthemanufacturerDiscount.
//filename: Ford.java
// Ford class, subclass of Car
public class Ford extends Car {
private int year;
private int manufacturerDiscount;
www.oumstudents.tk
◦Create an instance of Car class and initialize all the fields with appropriate values.
Display the sale prices of all instance.
//filename: MyOwnAutoShop.java
// Testing class with the main() method
public class MyOwnAutoShop {
(int Speed,double regularPrice,String color, int year, int manufacturerDiscount)
}
CHAPTER 8
CHAPTER 9
23. Write an applet that asks the user to enter two floating‐point numbers, obtains the two numbers from the user
and draws their sum, product (multiplication), difference and quotient (division). Use the techniques shown in
example.
//filename: simpleApplet1.java
import java.awt.*;
import javax.swing.*;
double number1;
double number2;
number1 = Double.parseDouble(firstNumber);
number2 = Double.parseDouble(secondNumber);
www.oumstudents.tk
super.paint(g);
g.drawRect(15, 10, 270, 60);
}
CHAPTER 10
24. Create an applet that can display the following component. No event handling is needed for the components.
//filename: simpleAppet2.java
import javax.swing.*;
import java.awt.*;
public class simpleAppet2 extends JApplet {
private JLabel lblName;
private JLabel lblAddress;
private JLabel lblEmail;
private JTextField txtName;
private JTextField txtAddress;
private JTextField txtEmail;
conpane.add(lblName);
conpane.add(txtName);
conpane.add(lblAddress);
conpane.add(txtAddress);
conpane.add(lblEmail);
conpane.add(txtEmail);
}
}
25. Create an applet that can display the following component. No
event handling is needed for the components.
//filename: simpleAppet3.java
import javax.swing.*;
import java.awt.*;
www.oumstudents.tk
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
button5 = new JButton("Button 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
conpane.add("South",panel);
}
}
CHAPTER 11
26. Temperature Conversion
a. Write a temperature conversion applet that converts from Fahrenheit to Celsius. The Fahrenheit temperature
should be entered from the keyboard (via a JTextField). A JLabel should be used to display the converted
temperature. Use the following formula for the conversion:
Celcius = ((5/9)*(Ferenheit‐32)).
b. Enhance the temperature conversion applet of Q1 by adding the Kelvin temperature scale. The applet should
also allow the user to make conversions between any two scales. Use the following formula for the conversion
between Kelvin and Celsius (in addition to the formulain Q1): Kelvin = Celcius + 273.15
/*
* Filename: tempCon.java
* Author: Abdulla Faris
* Date: 13/04/2010
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
JTextField txtInput;
JLabel lblResult;
JRadioButton rbCelcius, rbKelvin;
www.oumstudents.tk
lblResult= new JLabel ("Enter Ferenheit, Choose an option to convert and Click
Show Result");
conpane.add(lblResult);
}
if (rbKelvin.isSelected())
answer += 273.15;
lblResult.setText(String.valueOf(df.format(answer)));
}
}
www.oumstudents.tk