0% found this document useful (0 votes)
8 views

java.exam

The document contains multiple Java programming examples, including payroll calculations for salaried and hourly employees, animal behavior interfaces, GUI applications for text manipulation and mouse tracking, sorting a product list, and managing properties files. It also includes a database connection example to retrieve and display data from a MySQL database. Each section demonstrates different aspects of Java programming, including object-oriented principles, GUI development, and file I/O operations.

Uploaded by

itsmeaung01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

java.exam

The document contains multiple Java programming examples, including payroll calculations for salaried and hourly employees, animal behavior interfaces, GUI applications for text manipulation and mouse tracking, sorting a product list, and managing properties files. It also includes a database connection example to retrieve and display data from a MySQL database. Each section demonstrates different aspects of Java programming, including object-oriented principles, GUI development, and file I/O operations.

Uploaded by

itsmeaung01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter-10

1. A company pays its employees on a weekly basis. The employees are of two types:
Salaried employees are paid a fixed weekly salary, hourly employees are paid by the hour and
receive overtime pay (i.e., 1.5 times their hourly salary rate) for all hours worked in excess of
40 hours. Write an application that performs its payroll calculations polymorphically.

//Employee.java

public abstract class Employee {

public String firstName;

public String lastName;

public Employee(String f, String l) {

firstName = f;

lastName = l;

public String toString() {

return String.format("Name: %s %s", firstName,lastName);

public abstract double earning();

// SalariedEmployee.java

public class SalariedEmployee extends Employee {

public double salary;

public SalariedEmployee(String f, String l, double s) {

super(f, l);

salary = s;

public double earning() {

return salary;

}
public String toString() {

String n = super.toString();

String s = "Salary: " + salary;

String e = "Total Earn: " + earning();

String info = String.format(" %s \n %s \n %s \n",n,s,e);

return info;

// HourlyEmployee.java

public class HourlyEmployee extends Employee {

public double wage;

public double hours;

public HourlyEmployee(String f, String l, double w, double h) {

super(f, l);

wage = w;

hours = h;

public double earning() {

if ( hours <= 40 )

return wage * hours;

else

return 40 * wage + ( hours - 40 ) * wage * 1.5;

public String toString() {

String n = super.toString();

String w = "Wage: " + wage;

String h = "Hours: " + hours;

String e = "Total Earn: " + earning();


String info = String.format(" %s \n %s \n %s \n %s \n",n,w,h,e);

return info;

//PayRollSystem.java

public class PayRollSystem {

public static void main(String[] args) {

Employee e1 = new SalariedEmployee("John","Smith",1538);

Employee e2 = new HourlyEmployee("Alex","Vance",25,42);

System.out.println(e1.toString());

System.out.println(e2.toString());

Output:

Name: John Smith

Salary: 1538.0

Total Earn: 1538.0

Name: Alex Vance

Wage: 25.0

Hours: 42.0

Total Earn: 1075.0

2. Write a program that demonstrate the use of interfaces for different animals. Create three
interfaces: Walkable, Swimmable and Flyable. Each interface should declare a method that
describe the animal’s ability. Create two animal classes that implement any or all of these
interfaces and display the result.

public interface Walkable {

void walk();
}

public interface Swimmable {

void swim();

public interface Flyable {

void fly();

public class Duck implements Walkable, Swimmable, Flyable {

public void walk() {

System.out.println("Duck can walk by using its legs.");

public void swim() {

System.out.println("Duck can swim by using its legs.");

public void fly() {

System.out.println("Duck can fly by using its wings.");

public class Fish implements Swimmable {

public void swim() {

System.out.println("Fish can swim by using its fins.");

public class AnimalTest {

public static void main(String[] args) {

System.out.println("Animals That Can Walk:");


Walkable duck1 = new Duck();

duck1.walk();

System.out.println();

System.out.println("Animals That Can Swim:");

Swimable duck2 = new Duck();

Swimable fish = new Fish();

duck2.swim();

fish.swim();

Output:

Animals That Can Walk:

Duck can walk by using its legs.

Animals That Can Swim:

Duck can swim by using its legs.

Fish can swim by using its fings.

Chapter-14
2. Write a GUI application that display a window containing one textfield and two checkboxes.
Users should be able to change the font style of the textfield by activating/deactivating those
checkboxes. The output window would look like the following figure.
Program:

import java.awt.*;

import javax.swing.*;

public class CheckBoxFrame extends JFrame{

JTextField text;

private JCheckBox bold;

private JCheckBox itallic;

private Font defaultFont = new Font("Serif",Font.PLAIN,20);

public CheckBoxFrame() {

super("JCheckbox Test");

setLayout(new FlowLayout());

text = new JTextField("Watch the font style change",20);

text.setFont(defaultFont);

add(text);

bold = new JCheckBox("Bold");

add(bold);

bold.addItemListener(

e ->{

ChangeStyle();

);

itallic = new JCheckBox("Itallic");

add(itallic);

itallic.addItemListener(
e ->{

ChangeStyle();

);

void ChangeStyle() {

text.setFont(defaultFont);// reset to initial style

if(bold.isSelected() && itallic.isSelected()) {

text.setFont(new Font("Serif",Font.BOLD + Font.ITALIC,20));

}else if(bold.isSelected()){

text.setFont(new Font("Serif",Font.BOLD,20));

}else if(itallic.isSelected()) {

text.setFont(new Font("Serif",Font.ITALIC,20));

public class CheckBoxFrameTest {

public static void main(String[] args) {

CheckBoxFrame frame = new CheckBoxFrame();

frame.setSize(300,150);

frame.setVisible(true);

5. Implement a GUI window that contains a JTextArea. The program should detect three inputs
from user: mouse position, mouse button press and keyboard button press. Update JTextArea’s
text based on user inputs to display the information. The GUI window would look like the
following figure.
// MouseTrackerFrame.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class MouseTrackerFrame extends JFrame{

private JTextArea stats;

private String mousePos = "Mouse position: ";

private String mouseButton = "Mouse button: ";

private String keyPressed ="Key pressed: ";

public MouseTrackerFrame(){

super("Demonstrating mouse events");

stats = new JTextArea("Mouse position: ");

stats.setFont(new Font("Serif",3,20));

stats.setEditable(false);

add(stats);

MouseHandler handler = new MouseHandler();

stats.addMouseListener(handler);

stats.addMouseMotionListener(handler);

stats.addKeyListener(new KeyHandler());

UpdateStats();

}
private class KeyHandler extends KeyAdapter{

public void keyPressed(KeyEvent e) {

keyPressed = "Key pressed: " + e.getKeyText(e.getKeyCode());

UpdateStats();

private class MouseHandler extends MouseAdapter{

public void mousePressed(MouseEvent event){

mouseButton = String.format("Mouse button: %s",event.getButton());

UpdateStats();

public void mouseMoved(MouseEvent event){

mousePos = String.format("Mouse position: %d, %d", event.getX(), event.getY());

UpdateStats();

void UpdateStats() {

String s = String.format("%s\n%s\n%s",mousePos,mouseButton,keyPressed);

stats.setText(s);

//MouseTrackerTest.java

public class MouseTrackerTest{

public static void main(String[] args){

MouseTrackerFrame frame = new MouseTrackerFrame();

frame.setSize(400, 200);

frame.setVisible(true);
}

6. Create a java application that display a GUI window containing two JTextArea and one
JButton. User should be able to copy the selected text from first JTextArea to the second
JTextArea when the button is clicked. The output window would look like the following figure.

// TextAreaFrame.java

import java.awt.event.*;

import javax.swing.*;

public class TextAreaFrame extends JFrame{

private JTextArea textArea1;

private JTextArea textArea2;

private JButton copyJButton;

public TextAreaFrame(){

super("TextArea Demo");

Box box = Box.createHorizontalBox();

String demo = "this is a demo string to\n" +

"illustrate copying text\nfrom on textarea to\n" +

"another textarea using an\nexternal event\n";

textArea1 = new JTextArea(demo, 10, 15);


box.add(new JScrollPane(textArea1));

copyJButton = new JButton("Copy >>>");

box.add(copyJButton);

copyJButton.addActionListener(

new ActionListener(){

public void actionPerformed(ActionEvent event){

textArea2.setText(textArea1.getSelectedText());

});

textArea2 = new JTextArea(10, 15);

textArea2.setEditable(false);

box.add(new JScrollPane(textArea2));

add(box);

//TextAreaDemo.java

public class TextAreaDemo{

public static void main(String[] args){

TextAreaFrame frame = new TextAreaFrame();

frame.setSize(425, 200);

frame.setVisible(true);

Chapter-20
1. Write a java application that sort the following product list and display the sorted results.
Create a class called Item that has three instance variables: ID, itemName, and price. Use a
collection data structure to store a list of Item objects and sort them based on their unit price
in descending order.

ID Product Name Price


1 HDMI cable 10.99
2 USB Hub 25.8
3 Mouse Pad 6.5
4 Wireless Mouse 31.99

Program:

//Item.java

public class Item {

public int ID;

public String productName;

public double price;

public Item(int id, String name, double p) {

ID = id;

productName = name;

price = p;

// PriceComparator.java

import java.util.*;

public class PriceComparator implements Comparator<Item> {

public int compare(Item a, Item b) {

int result;

if(a.price > b.price) {

result = -1;
}else if(a.price < b.price){

result = 1;

}else {

result = 0;

return result;

//InvoiceDisplay.java

import java.util.*;

public class InvoiceDisplay {

public static ArrayList<Item> products = new ArrayList<Item>();

public static void main(String[] args) {

products.add(new Item(1,"HDMI cable",10.99));

products.add(new Item(2,"USB Hub",25.8));

products.add(new Item(3,"Mouse Pad",6.5));

products.add(new Item(4,"Wireless mouse",31.99));

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

DisplayList();

System.out.print("\nInvoice list sorted in descending unit price\n");

Collections.sort(products,new PriceComparator());

DisplayList();

public static void DisplayList() {

System.out.printf("%3s %-20s %s \n\n","ID","Product","Price");

for(Item i : products) {
System.out.printf("%3d %-20s %.2f \n",i.ID,i.productName,i.price);

Output:

Invoice list

ID Product Price

1 HDMI cable 10.99

2 USB Hub 25.80

3 Mouse Pad 6.50

4 Wireless mouse 31.99

Invoice list sorted in descending unit price

ID Product Price

4 Wireless mouse 31.99

2 USB Hub 25.80

1 HDMI cable 10.99

3 Mouse Pad 6.50

*/Data Persistence with Properties and File IO in Java*/


2. Write an application to create a properties table and display the information in it. The
program should ask the user whether to create a new properties table or to load an existing
file form disk. If the user choose to create, initialize a properties table with the information
provided in the following and save it as a file into the disk. If user choose to load, read the
created file from disk and display it as a properties table.

#Server Config
host=localhost
level=DEBUG
password=1234
port=800
username=root

Program:
import java.io.*;
import java.util.*;
public class PropertiesTest {
public static void main(String[] args) {
Properties table = new Properties();

System.out.print("1.Create Table 2.Load Table: ");


Scanner input = new Scanner(System.in);
int option = Integer.parseInt(input.nextLine());
if(option == 1) {

table.setProperty("port","800");
table.setProperty("host","localhost");
table.setProperty("username","root");
table.setProperty("password","1234");
table.setProperty("level","DEBUG");
saveFile(table);
}
if(option == 2) {
loadFile(table);
}

}
public static void loadFile(Properties table) {
try {
FileInputStream file = new FileInputStream("props.ini");
table.load(file);
file.close();
System.out.print("\nFile Loaded!");
displayTable(table);
}catch(IOException e) {
System.out.print("\nFailed to load file!");
e.printStackTrace();
}
}
public static void saveFile(Properties table) {
try {
displayTable(table);
FileOutputStream file = new FileOutputStream("props.ini");
table.store(file, "Server Config");
file.close();
System.out.print("\nFile Saved!");
}catch(IOException e) {
System.out.print("\nFailed to save file!");
e.printStackTrace();
}
}
public static void displayTable(Properties table) {
System.out.print("\n----Properties Table----\n");
for(Object key : table.keySet()) {
String value = table.getProperty((String)key);
System.out.printf("%-10s %-10s\n",key, value);
}
}
}

Chapter-25
Chapter-28
1. Develop a Java application that connect to a database and print the table using the
following information.

url: jdbc:mysql://localhost/library

username: root

password: root

table name: invoice

i name
d
1 laptop
2 smartphone
3 wireless
mouse

Program:

import java.sql.*;

public class DBTest2 {

public static void main(String[] args) {

System.out.println("Logging In....Please Wait");

try {

String url = "jdbc:mysql://localhost/halo";

String username = "root";

String password = "root";

Connection con = DriverManager.getConnection(url,username,password);

Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from hein");

ResultSetMetaData metaData = rs.getMetaData();

int numberOfColumns = metaData.getColumnCount();

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

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

System.out.printf( "%-6s\t",metaData.getColumnName( i ));

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

while(rs.next()) {

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

System.out.printf( "%-6s\t",rs.getObject(i));

System.out.println();

}catch(SQLException e) {

System.out.println("Error "+e);

You might also like