Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 75

Variables and Data Type

Exercise 1: Write a Java program to display Hello World on


the screen.

Exercise 2:Write a Java program to display the asterisk


pattern as shown below (Without using loop):

*****

*****

*****

*****

Exercise 3: Write a Java program to declare two integer variables,


one float variable, and one string variable and assign 10, 12.5,
and "Java programming" to them respectively. Then display their
values on the screen.

Exercise 4: Write a Java program by using BufferedReader


class  to prompt a user to input his/her name and then the
output will be shown as an example below:

Hello Dara!
JAVA ARITHMETIC OPERATORS
Exercise 1: Write Java program to allow the user to input two
integer values and then the program prints the results of
adding, subtracting, multiplying, and dividing among the two
values.
See the example below:

Enter value a:30

Enter value b:10

The result of adding is 40.

The result of subtracting is 20;

The result of multiplying is 300.

The result of dividing is 3.

Exercise 2: Write Java program to generate a random


number between 1 to 6.

To generate a random number, you can use the Random class of java.util

package. You may use the abs() method of Math class to make sure you can

get only a positive number.


COMPOUND OPERATORS

Exercise 1: Write Java program to allow the user to input two float values and

then the program adds the two values together. The result will be assigned to

the first variable.

Enter value a:12.5

The value of a before adding is 12.5.

Enter value b:34.9

The value of a after adding is 47.4.

Exercise 2: Write Java program to allow the user to input the amount of

deposit, yearly interest rate (percentage), and income tax(percentage). Then

the program will calculate the amount of interest that the person earns in the

year. See the example output below:

The amount of deposit: 1000

Yearly interest rate: 7.5%

Income tax rate: 4%

The amount of interest earned in the year:72.0


JAVA IF ELSE

Exercise 1: Write Java program to allow the user to input his/her age. Then

the program will show if the person is eligible to vote. A person who is eligible

to vote must be older than or equal to 18 years old.

Enter your age: 18

You are eligible to vote.

Exercise 2: Write a Java program to determine whether an input number is

an even number.

IF ELSE AND LOGICAL OPERATORS


Exercise 1: Write a Java program that determines a student’s
grade.
The program will read three types of scores (quiz, mid-term, and final scores)
and determine the grade based on the following rules:
-if the average score >=90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F

See the example output below:

Quiz score: 80

Mid-term score: 68
Final score: 90

Your grade is B.

Exercise 2: Write a Java program to calculate the revenue


from a sale based on the unit price and quantity of a product
input by the user.
The discount rate is 10% for the quantity purchased between 100 and 120
units, and 15% for the quantity purchased greater than 120 units. If the
quantity purchased is less than 100 units, the discount rate is 0%. See the
example output as shown below:

Enter unit price: 25

Enter quantity: 110

The revenue from sale: 2475.0$

After discount: 275.0$(10.0%)

SWITCH CASE

Exercise 1: Write a Java program to detect key presses.


If the user pressed number keys( from 0 to 9), the program will tell the number
that is pressed,  otherwise, program will show "Not allowed".
Exercise 2: Write a Java program that allows the user to
choose the correct answer of a question.
See the example below:
What is the correct way to declare a variable to store an integer value in
Java?
a. int 1x=10;
b. int x=10;
c. float x=10.0f;
d. string x="10";
Enter your choice: c
Invalid choice

a. int 1x=10;
b. int x=10;
c. float x=10.0f;
d. string x="10";
Enter your choice: b
Congratulations!

LOOPS IN JAVA
Exercise 1: Write a Java program by using two for loops to
produce the output shown below:

*******

******

*****

****

***
**

Exercise 2: Write a Java program by using three for loops to


print the following pattern:

1******

12*****

123****

1234***

12345**

123456*

1234567

WHILE LOOP

Exercise 1: Write Java program to prompt the user to choose


the correct answer from a list of answer choices of a
question.
The user can choose to continue answering the question or stop answering it.
See the example below:

What is the command keyword to exit a loop in Java?

a. int
b. continue

c. break

d. exit

Enter your choice: b

Incorrect!

Again? press y to continue:

Enter your choice: c

Congratulations!

Exercise 2:Write Java program to print the table of


characters that are equivalent to the Ascii codes from 1 to
122.
The program will print the 10 characters per line.
DO WHILE LOOP

Exercise 1: By using do while loop, write Java program to


prompt the user to choose the correct answer from a list of
answer choices of a question.
The user can choose to continue answering the question or stop answering it.
See the example below:

What is the command keyword to exit a loop in Java?

a. int

b. continue

c. break

d. exit

Enter your choice: b


Incorrect!

Again? press y to continue:

Enter your choice: c

Congratulations!

Exercise 2: By using  do while loop, write Java program to


print the table of characters that are equivalent to the Ascii
codes from 1 to 122.
The program will print the 10 characters per line.
Java program to print various patterns
Program 1: write a program to print the following patterns
1
12
123
1234
12345
Program 2:Write a program to print the following patterns
1
12
123
1234
12345
1234
123
12
1
Program 3:Write a program to print the following patterns
12345
1234
123
12
1
12
123
1234
12345
Program 4: Write a program to print the following patterns
*
**
***
****
*****
Program 5: Write a program to print the following patterns
*****
****
***
**
*
Program 6: Write a program to print the following patterns
*****
****
***
**
*

Program 7: Write a program to print the following patterns


*
***
*****
*******
*********
Program 8: Write a program to print the following patterns
*********
*******
*****
***
*
Program 9: Write a program to print the following patterns
*
***
*****
*******
*********
*******
*****
***
*
Program 10: Write a program to print the following patterns

$ ***$
* $ $*
* $ *
* $ $*
$ *** $
Program 11: Write a program to print the following patterns

******
*
*
*
*
******
Program 12:- Write a program to print the following patterns

* ** * *
* *
* *
* *
* * * * *
Program 13:- Write a program to print the following patterns

1
23
345
4567
56789

Program 14: Read a sequence of characters from the terminal until q is read.
Output the largest character read, not including the q.
Program 15: Write a program that given 𝑟, 𝑎, and 𝑛, displays the first 𝑛 terms of
the corresponding geometric progression.
Program 16: Print the sum of the reciprocals of the first 100 natural numbers.
1.

2.
Modify the program above to incorporate a constructor to provide initial value.
3.

4. Modify the program above to include constructors for all the three classes.
5.
6. Write a class named employee with the following fields:
name: The name field references a String object that holds the employee's name.
idNumber: The idNumber is an int variable that holds the employee's ID number.
department: The department field references a String object that holds the name of the
department where the employee works.

position: The position field references a String object that holds the employee's job
title.

The class should have the following constructors:

-A constructor that accepts the following values as arguments and assigns them to the
appropriate fields: employee's name, employee's ID number, department, and position.
-A constructor that accepts the following values as arguments and assigns them to the
appropriate fields: employee's name and ID number. The department and position fields
should be assigned an empty string(“ ”).
-A no-arg constructor that assigns empty strings (“ ”) to the name, department, and
position fields, and 0 to the idNumber field.

Write appropriate mutator that store values in these fields and accessor methods that
return the values in those fields. Once you have the class, write a separate program that
creates three Employee objects to hold the following data:

Name Id Number Department Position

Susan Meyers 47899 Accounting vice Pres.

Mark Jones Joy 39119 IT Programmer

Rogers 81774 Manufacturing Engineer

The program should store this data in the three objects and then display the data for
each employee on the screen.

7. Design a class that holds the following personal data: name, address, age, and
phone
number. Write appropriate accessor and mutator functions. Demonstrate the class
by
writing a program that creates three instances of it. One instance should hold your
information, and the other two should hold your friends or family members
information.
8. Design a Payroll class that has fields for an employee's name, ID number, hourly pay rate,
and number of hours worked. Write the appropriate accessor and mutator methods and a
constructor that accepts the employee's name and ID number as arguments. The class
should also have a method that returns the employee's gross pay, which is calculated as
the number of hours worked multiplied by the hourly rate. Write a program that
demonstrates the class by creating a Payroll object, then asking the user to enter the data
for an employee. The program should display the amount of gross pay earned.
9. Write a class named RetailItem that holds data about an item in a retail store. The class
should have the following fields:
Description: The description field references a String object that holds a brief description of
the item.
unitsOnHand: The unitsOnHand field is an int variable that holds the numbers of units
currently in inventory.
Price: The price filed is a double that holds the item's retail price.

Write a constructor that accepts arguments for each field, appropriate mutator methods that
store values in these fields, and accessor methods that returns the values in these fields. Once
you have written the class, write a separate program that creates three RetailItem objects and
stores the following data in them:
Description Units on Hand Price
Item #1 Jacket 12 59.95
Item #2 Designer Jeans 40 34.95
Item #3 Shirt 20 24.95
10. Design a TestScores class that has fields to hold three test scores. The class should have a
constructor, accessor and mutator methods for the test score fields, and a method that
returns the average of the test scores. Demonstrate the class by writing a separate
program that creates an instance of the class. The program should ask the user to enter
three test scores, which are stored in the TestScores object. Then the program should
display the average of the scores, as reported by the TestScores object.
11. Write a Circle class that has the following fields:
radius: a double
PI: a final double initialized with the value 3.14159
The class should have the following methods:
Constructor: accepts the radius of the circle as an argument.
Constructor: A no-arg constructor that sets the radius field to 0.0.
setRadius: A mutator method for the radius field.
getRadius: An accessor method for the radius field.
getArea: Returns the area of the circle which is calculated as area=PI*radius*radius
getDiameter: Returns the diameter of the circle which is calculated as
diameter=radius*2
getCircumference: Returns the circumference of the circle, which is calculated as
circumference= 2*PI*radius

Write a program that demonstrates the Circle class by asking the user for the circle's radius,
creating a Circle object, and then reporting the circle's area, diameter, and circumference.

12. A bank charges $10 per month plus the following check fees for a commercial checking
account:
$.10 each for fewer than 20 checks
$.08 each for 20 39 checks
$.06 each for 40 59 checks
$.04 each for 60 or more checks

The bank also charges an extra $15 if the balance of the account falls below $400
(before any check fees are applied). Write a program that asks for the beginning balance
and the number of checks written. Compute and display the bank s service fees
for the month.

13. Design a SavingsAccount class that stores a savings account’s annual interest rate
and balance. The class constructor should accept the amount of the savings
account’s starting balance. The class should also have methods for subtracting the
amount of a withdrawal, adding the amount of a deposit, and adding the amount of
monthly interest to the balance. The monthly interest rate is the annual interest rate
divided by twelve. To add the monthly interest to the balance, multiply the monthly
interest rate by the balance, and add the result to the balance.
Test the class in a program that calculates the balance of a savings account at the
end of a period of time. It should ask the user for the annual interest rate, the
starting balance, and the number of months that have passed since the account was
established. A loop should then iterate once for every month, performing the
following:

 Ask the user for the amount deposited into the account during the month. Use the
class method to add this amount to the account balance.
 Ask the user for the amount withdrawn from the account during the month. Use
the class method to subtract this amount from the account balance.
 Use the class method to calculate the monthly interest.

After the last iteration, the program should display the ending balance, the
total amount of deposits, the total amount of withdrawals, and the total interest
earned.

14. The following table lists the freezing and boiling points of several substances.

Substance Freezing Point Boiling Point


Ethyl Alcohol -173 172
Oxygen -362 -306
Water 32 212

Design a class that stores a temperature in a temperature field and has the
appropriate accessor andmutator methods for the field. In addition to appropriate
constructors, the class should have the following methods:

 isEthylFreezing: This method should return the boolean value true if the temperature
stored in the temperature field is at or below the freezing point of ethyl alcohol.
Otherwise, the method should return false.
 isEthylBoiling: This method should return the boolean value true if the temperature
stored in the temperature field is at or above the boiling point of ethyl alcohol. Otherwise,
the method should return false.
 isOxygenFreezing: This method should return the boolean value true if the temperature
stored in the temperature field is at or below the freezing point of oxygen. Otherwise, the
method should return false.
 isOxygenBoiling: This method should return the boolean value true if the temperature
stored in temperature field is at or above the boiling point of oxygen. Otherwise, the
method should return false.
 isWaterFreezing: This method should return the boolean value true if the temperature
stored in the temperature field is at or below the freezing point of water. Otherwise, the
method should return false.
 isWaterBoiling: This method should return the boolean value true if the temperature
stored in the temperature field is at or above the boiling point of water. Otherwise, the
method should return false.

Write a program that demonstrates the class. The program should ask the user to
enter a temperature, and then display a list of the substance that will freeze at that
temperature and those that will boil at that temperature. For example, if the temperature is
-20 the class should report that water will freeze and oxygen will boil at that temperature.

15. Write a class named Coin. The Coin class should have the following field:

 A String named sideUp. The sideUp field will hold either “heads” or “tails”
indicating the side of the coin that is facing up.

The Coin class should have the following methods:

 A no-arg constructor that randomly determines the side of the coin that is
facing up (“heads” or “tails”) and initializes the sideUp field accordingly.
 A void method named toss that simulates the tossing of the coin. When the
toss method is called, it randomly determines the side of the coin that is facing
up (“heads” or “tails”) and sets the sideUp field accordingly.
 A method named getSideUp that returns the value of the sideUp field.

Write a program that demonstrates the Coin class. The program should create an instance
of the class and display the side that is initially facing up. Then, use a loop to toss the
coin 20 times. Each time the coin it tossed, display the side that is facing up. The program
should keep count of the number of times heads is facing up and the number of times tails
is facing up, and display those values after the loop finishes.
A Second look at Classes and Objects
1. Write a class that has three overloaded static methods for calculating the
areas of the following geometric shapes:
 circles
 rectangles
 cylinders
Here are the formulas for calculating the area of the shapes:

Area of a circle Area = pi*r^2


where: pi is Math.PI and r is the circle's radius
Area of a rectangle Area = Width x Length
Area of a cylinder Area = pi*r^2*h
where: n is Math.PI, r is the radius of the cylinder's base,
and h is the cylinder's height
Because the three methods are to be overloaded, they should each have
the same name, but different parameter lists. Demonstrate the class in a
complete program.
2. Make a LandTract class that has two fields, once for the tract's length and
one for the width. The class should have a method that returns the tract's
area, as well as an equals method and a toString method. Demonstrate the
class the class in a program that asks the user to enter the dimensions for
the two tracts of land. The program should display the area of each and
indicate whether the tracts are of equal size.
3. Write a class named month. This class should have an int field named
monthNumber that holds the number of months. For example, January
would be 1. Feburary would be 2, and so forth. In addition, provide this
following methods. 
 A no- arg constructor that sets the monthNumber field to 1.  
 A constructor that accepts the number of the month as an
argument. It should set the monthNumber field to the value
passed as the argument. If a value less than 1 or greater  than
12 is passed, the constructor should set monthNumber to 1. 
 A Constructor that accepts the name of the month, such as
"Janurary" or "February" as an argument. It should set the
monthNUmber field to the correct corresponding value  
 A setMonthNumber method that accepts an int argument,
which is assigned to the monthNumber field. If a value less
than 1 or greater than 12 is passed, the method should
set monthNumber or 1. 
 A getmonthNumber method that returns the value in the
monthNumber field. 
 A getMonthname method that returns the name of the month.
For example, if the monthNumber field contains 1, then this
method should return "january". 
 A toString method that returns the same value as the
getMonthName method. 
 An equals method that accepts a month object as an
argument. If the argument object holds the same data as the
calling object, this method should return true. Otherwise
it should return false. 
 A greaterThan method that accepts a month object as an
argument. If the calling object'smonthNumber field is greater
than the argument's monthNumber field, this method  should
return true. Otherwise, it should return false. 
 A lessThan method that accepts a Month object as an
argument, If the calling object's monthNumber field is less
than the argument's monthNumber field, this method should
return true. Otherwise, it should return false. 
4. For this assignment you will design a set of classes that work together to
simulate a police officer issuing a parking ticket. You should design the
following classes:
 TheParkedCarClass: This class should simulate a parked car. The
class’s responsibilities are as follows:
- To know the car’s make, model, color, license number, and
the number of minutes that the car has been parked.
 TheParkingMeterClass: This class should simulate a parking meter.
The class’s only responsibility is as follows:
- To know the number of minutes of parking time that has
been purchased.
 TheParkingTicketClass: This class should simulate a parking ticket.
The class’s responsibilities are as follows:
-To report the make, model, color, and license number of the
illegally parked car.
-To report the amount of the fine, which is $25 for the first
hour or part of an hour that the car is illegally parked, plus $10
for every additional hour or part of an hour that the car is
illegally parked
-To report the name and badge number of the police officer
issuing the ticket.
 ThePoliceOfficerClass: This class should simulate a police officer
inspecting parked cars. The class’s responsibilities are as follows:
-To know the police officer’s name and badge number.
-To examine a ParkedCar object and a ParkingMeter object,
and determine whether the car’s time has expired.
-To issue a parking ticket (generate a ParkingTicket object). if
the car's time has expired
Write a program that demonstrates how these classes collaborate.
5. For this assignment, you will design a set of classes that work together to
simulate a car's fuel gauge and odometer. The classes you will design are
the following:
The FuelGauge class: This class will simulate a fuel gauge. its
responsibilities are as follows:
 To know the car’s current amount of fuel, in gallons.
 To report the car’s current amount of fuel, in gallons.
 To be able to increment the amount of fuel by 1 gallon. This
simulates putting fuel in the car. ( The car can hold a maximum of 15
gallons.)
 To be able to decrement the amount of fuel by 1 gallon, if the
amount of fuel is greater than 0 gallons. This simulates burning fuel
as the car runs.

The odometer class: This class will simulate the car’s odometer. its
responsibilities are as follows:
 To know the car’s current mileage.
 To report the car’s current mileage.
 To be able to increment the current mileage by 1 mile. The maximum
mileage the odometer can store is 999,999 miles. When this amount
is exceeded, the odometer resets the current mileage to 0.
 To be able to work with a FuelGauge object. It should decrease the
FuelGauge object’s current amount of fuel by 1 gallon for every 24
miles traveled. ( the car’s fuel economy is 24 miles per gallon.)
Demonstrate the classes by creating instances of each. Simulate filling the
car up with fuel, and then run a loop that increments the odometer until
the car runs out of fuel. During each loop iteration, print the car’s current
mileage and amount of fuel.

6. Design a Geometry class with the following methods:


 A static method that accepts the radius of a circle and returns the
area of the circle.
Use the following formula:
Area=πr^2
Use Math.PI for π and the radius of the circle for r.
 A static method that accepts the length and width of a rectangle and
returns the area of the rectangle. Use the following formula:
Area = Length x Width
 A static method that accepts the length of a triangle's base and the
triangle's height. The method should return the area of the triangle.
Use the following formula:
Area = Base x Height x 0.5

The methods should display and error message if negative values are used for the
circle's radius, the rectangle's length or width, or the triangle's base or height.
Next write a program to test the class, which displays the following menu and
responds to the user's selection:
Geometry Calculator
1. Calculate the Area of a Circle
2. Calculate the Area of a Rectangle
3. Calculate the Area of a Triangle
4. Quit

Entre your choice (1 - 4):


Display an error message if the user enters a number outside the range of 1
through 4 when selection an item from the menu.

Arrays
1. Rainfall Class

Write a RainFall class that stores the total rainfall for each of 12 months into an array of doubles. The
program should have methods that return the following;
• the total rainfall for the year

• the average monthly rainfall

• the month with the DOM rain

• the month with the least rain

Demonstrate the class in a complete program.

2. Payroll Class

Write a Payroll class that uses the following arrays as fields:

• employeeId. An array of seven integers to hold employee identification numbers. The

array should be initialized with the following numbers:

5658845 4520125 7895122 8777541

8451277 1302850 7580489

• hours. An array of seven integers to hold the number of hours worked by each employee

• payRate. An array of seven doubles to hold each employees hourly pay rate

• wages. An array of seven doubles to hold each employees gross wages

The class should relate the data in each array through the subscripts. For example, the number in
element 0 of the hours array should be the number of hours worked by the employee whose
identification number is stored in element 0 of the employeeld array. That same employee's pay rate
should be stored in element 0 of the payRate array.

In addition to the appropriate accessor and mutator methods, the class should have a method that
accepts an employee s identification number as an argument and returns the gross pay for that
employee.

Demonstrate the class in a complete program that displays each employee number and asks the user to
enter that employee's hours and pay rate. It should then display each employee's identification number
and gross wages.

3. Charge Account Validation

Create a class with a method that accepts a charge account number as its argument. The method should
determine whether the number is valid by comparing it to the following list of valid charge account
numbers:

5658845 4520125 7895122 8777541 8451277 1302850

8080152 4562555 5552012 5050552 7825877 1250255

L00523L 6545231 3852085 7576651 7881200 4581002


These numbers should be stored in an array or an ArrayList object. Use a sequential search to locate the
number passed as an argument. If the number is in the array, the method should return true, indicating
the number is valid. If the number is not in the array, the method should return false, indicating the
number is invalid.

Problem Write a program that tests the class by asking the user to enter a charge account number.

the program should display a message indicating whether the number is valid or invalid.

4. Charge Account Modification

Modify the charge account validation class that you wrote for Programming Challenge 3 so it reads the
list of valid charge account numbers from a file. Use Notepad or another text editor to create the file.

5. Driver's License Exam

The local Driver's License Office has asked you to write a program that grades the written portion of the
driver's license exam. The exam has 20 multiple choice questions. Here are the correct answers:

1. B 6. A 11. B 16. C

2. D 7. B 12. C 17. C

3. A 8. A 13. D 18. B

4. A 9. C 14. A 19. D

5. C 10. D 15. D 20. A

A student must correctly answer 15 of the 20 questions to pass the exam.

Write a class named DriverExam that holds the correct answers to the exam in an array field.

The class should also have an array field that holds the student's answers. The class should

have the following methods:

• passed. Returns true if the student passed the exam, or false if the student failed

• totalCorrect. Returns the total number of correctly answered questions

• totallncorrect. Returns the total number of incorrectly answered questions

• questionsMissed. An int array containing the question numbers of the questions that

the student missed

Demonstrate the class in a complete program that asks the user to enter a student's answers,

and then displays the results returned from the DriverExam class's methods.

6. Quarterly Sales Statistics


Write a program that lets the user enter four quarterly sales figures for six divisions of a company. The
figures should be stored in a two-dimensional array. Once the figures are entered, the program should
display the following data for each quarter:

• A list of the sales figures by division

• Each division's increase or decrease from the previous quarter (this will not be displayed

for the first quarter)

• The total sales for the quarter

• The company's increase or decrease from the previous quarter (this will not be displayed

for the first quarter)

• The average sales for all divisions that quarter

• The division with the highest sales for that quarter

7. Grade Book

A teacher has five students who have taken four tests. The teacher uses the following grading

scale to assign a letter grade to a student, based on the average of his or her four test scores:

Test Score Letter Grade

90-100 A

80-89 B

70-79 C

60-69 D

0-59 F

Write a class that uses a string array or an ArrayList object to hold the five student’s names, an array of
five characters to hold the five students' letter grades, and five arrays of four doubles each to hold each
student's set of test scores. The class should have methods that return a specific student's name, the
average test score, and a letter grade based on the average.

Demonstrate the class in a program that allows the user to enter each student's name and his or her
four test scores. It should then display each student's average test score and letter grade.

8. Grade Book Modification

Modify the grade book application in Programming Challenge 7 so that it drops each student's lowest
score when determining the test score averages and letter grades.

9. Lottery Application

Write a Lottery class that simulates a lottery. The class should have an array of five integers named
lotteryNumbcrs. The constructor should use the Random class (from the Java API) to generate a random
number in the range of 0 through 9 for each clement in the array. The class should also have a method
that accepts an array of five integers that represent a person's lottery picks. The method is to compare
the corresponding elements in the two arrays and return the number of digits that match. For example,
the following shows the lotteryNumbers array and the user's array with sample numbers stored in each.
There are two matching digits (elements 2 and 4).

lotteryNumbers array:

7 4 9 1 3

User’s array :

4 2 9 7 3

In addition, the class should have a method that returns a copy of the lotteryNumbers array.

Demonstrate the class in a program that asks the user to enter five numbers. The program should
display the number of digits that match the randomly generated lottery numbers. If all of the digits
match, display a message proclaiming the user a grand prize winner.

10. Array Operations

Write a program with an array that is initialized with test data. Use any primitive data type of your
choice. The program should also have the following methods:

• getTotal. This method should accept, a one-dimensional array as its argument and return the total of
the values in the array.

• getAverage. This method should accept a one-dimensional array as its argument and return the
average of the values in the array.

• getHighest. This method should accept a one-dimensional array as its argument and return the highest
value in the array.

• getLowest. This method should accept a one-dimensional array is us argument and return the lowest
value in the array.

Demonstrate each of the methods in the program.

11. 2D Array Operations

Write a program that creates a two-dimensional array initialized with test data. Use any primitive data
type that you wish. The program should have the following methods:

• getTotal. This method should accept a two-dimensional array as its argument and

return the total of all the values in the array.


• getAverage. This method should accept a two-dimensional array as its argument and

return the average of all the values in the array.

• getRowTotal. This method should accept a two-dimensional array as its first argument

and an integer as its second argument. The second argument should be the subscript

of a row1 in the array. The method should return the total of the values in the

specified row.

• getColumnTotal. This method should accept a two-dimensional array as its first argument

and an integer as its second argument. The second argument should he the subscript

of a column in the array. The method should return the total of the values in the

specified column.

• getHighestInRow. This method should accept a two-dimensional array as its first

argument and an integer as us second argument. The second argument should be the

subscript of a row in the array. The method should return the highest value in the

specified row of the array,

• getLowestInRow, This method should accept a two-dimensional array as its first argument

and an integer as its second argument. The second argument should be the subscript of a row
in the array. The method should return the lowest value in the specified row of the array.

Demonstrate each of the methods in this program.

12. Phone Book ArrayList

Write a class named PhoneBookEntry that has fields for a person's name and phone number. The class
should have a constructor and appropriate accessor and mutator methods. Then write a program that
creates at least five PhoneBookEntry objects and stores them in an ArrayList. Use a loop to display the
contents of each object in the ArrayList.

13. Trivia Game

In this programming challenge, you will create a simple trivia game for two players. The program will
work like this;

 Starting with player 1, each player gets a turn at answering 5 trivia questions. (There are 10
questions, 5 for each player.) When a question is displayed, four possible answers are also
displayed. Only one of the answers is correct, and if the player selects the correct answer, he or
she earns a point.
 After answers have been selected for all of the questions, the program displays the number of
points earned by each player and declares the player with the highest number of points the
winner.
You are to design a Question class to hold the data for a trivia question. The Question class should have
String fields for the following data:

• A trivia question

• Possible answer 1

• Possible answer 2

• Possible answer 3

• Possible answer 4

• The number of the correct answer (1,2, 3, or 4)

The Question class should have appropriate constructors), accessor, and mutator methods. The
program should create an array of 10 Question objects, one for each trivia question. (If you prefer, you
can use an ArrayList instead of an array.) Make up your own trivia questions on the subject or subjects
of your choice for the objects.

Text Processing Exercise


1. Backward String
Write a method that accepts a String object as an argument and displays its
contents backward. For instance, if the string argument is "gravity" the method
should display “ytivarg”.
Demonstrate the method in a program that asks the user to input a string and
then passes it to the method.
2. Word Counter
Write a method that accepts a string object as an argument and returns the
number of words it contains. For instance, if the argument is "Four score and
seven years ago" the method should return the number 6. Demonstrate the
method in a program that asks the user to input a string and then passes it to the
method. The number of words in the string should be displayed on the screen.
3. Sentence Capitalizer
Write a method that accepts a String object as an argument and returns a copy of
the string with the first character of each sentence capitalized- For instance, if the
argument is "hello. my name is Joe, what is your name?" the method should
return the string "Hello. My name is Joe. What is your name?" Demonstrate the
method in a program that asks the user to input a string and then passes it to the
method. The modified string should be displayed on the screen.
4. Vowels and Consonants
Write a class with a constructor that accepts a String object as its argument, The
class should have a method that returns the number of vowels in the string, and
another method that returns the number of consonants in the string.
Demonstrate the class in a program that perform the following steps:
1. The user is asked to enter a string.
2. The program displays the following menu:
a. Count the number of vowels in the string
b, Count the number of consonants in the string
C Count both the vowels and consonants in the string
d. Enter another string
e. Exit the program
3. The program performs the operation selected by the user and repeats
until the user selects e, to exit the program.
5. Password Verifier
Imagine you are developing a software package for Amazon.com that requires
users to enter their own passwords. Your software requires that users' passwords
meet the following criteria:
• The password should be at least six characters long.
• The password should contain at least one uppercase and at least one
lowercase letter.
• The password should have at least one digit.
Write a class that verifies that a password meets the stated criteria. Demonstrate
the class in program that allows the user to enter a password and then displays a
message indicating whether it is valid or not.
6. Telemarketing Phone Number List
Write a program that has two parallel arrays of string objects. One of the arrays
should hold people's names and the other should hold their phone numbers. Here
are example contents of both arrays:
name Array Example Content. phone Array example Content*.
"Harrison, Rose" “555-2234”
"James, Jean" “555-9096”
“Smith, William” “555-1785”
"Smith, Brad" “555-9224”
The program should ask the user to enter a name or the first few characters of a
name to search for in the array. The program should display all of the names that
match the user's input and their corresponding phone numbers. For example, if
the user enters "Smith", the program should display the following names and
phone numbers from the list:
Smith, William: 555-1785
Smith, Brad: 555-9224
7. Check Writer
Write a program that displays a simulated paycheck. The program should ask the
user to enter the date, the payee's name, and the amount of the check. It should
then display a simulated check with the dollar amount spelled out, as shown here:

Date: 11/24/2012

Pay to the Order of: John Phillips $1920.85

One thousand nine hundred twenty and 85 cents


8. Sum of Numbers in a String
Write a program that asks the user to enter a series of numbers separated by
commas, Here is an example of valid input:
7, 9,10,2,18,6
The program should calculate and display the sum of all the numbers.
9. Sum of Digits in a String
Write a program that asks the user to enter a series of single digit numbers with
nothing separating them. The program should display the sum of all the single
digit numbers in the string. For example, if the user enters 2514, the method
should return 12, which is the sum of 2, 5, 1, and 4. The program should also
display the highest and lowest digits in the string.
10. Miscellaneous String Operations
Write a class with the following static methods:
• wordcount. This method should accept a reference to a String object as
an argument and return the number of words contained in the object.
• arrayToString. This method accepts a char array as an argument and
converts it to a String object. The method should return a reference to the
String object.
• mostFrequant. This method accepts a reference to a String object as an
argument and returns the character that occurs the most frequently in the
object.
• raplaceSubstring. This method accepts three references to String objects
as arguments. Let's call them string1 , string2, and string3. It searches string
for all occurrences of string2. When it finds an occurrence of string2, it
replaces it with string3 , For example, suppose the three arguments have
the following values:
String1 : "the dog jumped over the fence"
String2: “the”
String3: “that”
With these three arguments, the method would return a reference to a
String object with the value "that dog jumped over that fence".
Demonstrate each of these methods in a complete program.
11. Alphabetic Telephone Number Translator
Many companies use telephone numbers like 555-GFT-FOOD so the number is
easier for their customers to remember. On a standard telephone, the alphabetic
letters are mapped to numbers in the following fashion:
A, B, and C = 2
D, E, and F= 3
G, H, and I =4
J , K , and L=5
M , N , an O = 6
P, Q, R, and S = 7
T,U, and V = 8
W,X,Y, and Z = 9
Write an application that asks the user to enter a 10-character telephone number
in the format xxx-xxx-xxxx. The application should display the telephone number
with any alphabetic characters that appeared in the original translated to their
numeric equivalent. For example, if the user enters 555-GET-FOOD the
application should display 555-438-3663.
12. Word Separator
Write a program that accepts as input a sentence in which all of the words are run
together, but the first character of each word is uppercase. Convert the sentence
to a string in which the words are separated by spaces and only the first word
starts with an uppercase letter. For example, the string "StopAndSmellTheRoses."
would be converted to "Stop and smell the roses.”
13. Pig Latin
Write a program that reads a sentence as input and converts each word to "Pig
Latin". In one version of Pig Latin, you convert a word by removing the first letter,
placing that letter at the end of the word, and then appending "ay" to the word.
Here is an example:
English: I SLEPT MOST OF THE NIGHT
Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY

Applet Exercise
Design the following using Applet-
2)

Event Handling
Event Handling- Event is an action which indicates happening of any operation.for
handling the event in java we must import java.awt.event package & we must
consider on two things-
1. Event Source
2. Event Listener

1. Event Source- It is an object like button, textbox etc on which we perform the
event. Each object support some common events and some special event also.
2. Event Listener Interfaces- java provides a lot of listener interfaces which allows
you for handling the particular event. The listener interfaces provides the scaleton
on which we implement the event.

Steps for handling event-


for handling any event you must follow the following steps-
1. implement the listener interfaces. like
class classname implements EventListenerName
{
_______
}
2. Register the event. Like the following-
objectname.addListenerType(this);
3. Define all the handlers.

Event Handling Interfaces

ListenerName Handlers Purpose


ActionListener actionPerformed(ActionEvent) When any object click by mouse
ItemListener itemStateChanged(ItemEvent) When the selected item changes
KeyListener keyPressed(KeyEvent) When any key is pressed, released or typed
keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseListener mouseClicked(MouseEvent) When mouse related activities occur
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
TextListener textValueChanged(TextEvent) When the value of textbox is change
WindowListener windowActivated(WindowEvent) When window related activities occurs

windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)

Using ActionListener-
import java.awt.*;
import java.awt.event.*;
class win extends Frame implements ActionListener
{
Button b1,b2,b3;
public win()
{
setTitle("Event Handling Window");
setLayout(new FlowLayout());
b1=new Button("Red");
b2=new Button("Blue");
b3=new Button("Green");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setSize(400,150);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
setBackground(Color.red);
else if(e.getSource()==b2)
setBackground(Color.blue);
else if(e.getSource()==b3)
setBackground(Color.green);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}
Example-2
import java.awt.*;
import java.awt.event.*;
class mywin extends Frame implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public mywin()
{
setTitle("Calculation");
setLayout(null);
l1=new Label("First Number ");
l2=new Label("Second Number");
t1=new TextField(20);
t2=new TextField(20);
l3=new Label("Sum");
t3=new TextField(20);
b1=new Button("OK");
l1.setBounds(10,40,150,20);
t1.setBounds(160,40,120,20);
l2.setBounds(10,70,150,20);
t2.setBounds(160,70,120,20);
l3.setBounds(10,100,150,20);
t3.setBounds(160,100,120,20);
b1.setBounds(160,130,120,20);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
b1.addActionListener(this);
setSize(400,250);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int a,b,c;
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
c=a+b;
t3.setText(Integer.toString(c));
}
}
class demo
{
public static void main(String args[])
{
mywin obj=new mywin();
}

___________________________________________________________________
Using TextListener-
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class text extends Frame implements TextListener,ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public text()
{
setTitle("Welcome");
setLayout(new GridLayout(4,2));
setSize(440,250);
l1=new Label("Basic Salary");
l2=new Label("Ta");
l3=new Label("Da");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
b1=new Button("Exit");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
t1.addTextListener(this);
b1.addActionListener(this);
setVisible(true);
}
public static void main(String args[])
{
text e=new text();

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
System.exit(0);

}
public void textValueChanged(TextEvent e)
{

if(e.getSource()==t1)
{
int bs,ta,da;
bs=Integer.parseInt(t1.getText());
ta=(bs*4)/100;
da=(bs*6)/100;
t2.setText(Integer.toString(ta));
t3.setText(Integer.toString(da));

}
}

}
____________________________________________________________
using ItemListener
import java.awt.*;
import java.awt.event.*;
public class item extends Frame implements ActionListener,ItemListener
{
Label l1;
Choice c1=new Choice();
Button b1;
public item(String s)
{
super(s);
setLayout(new FlowLayout());
setSize(240,150);
setBackground(Color.red);
c1.addItem("Red");
c1.addItem("Green");
c1.addItem("Blue");
c1.addItem("Yellow");
l1=new Label("Select Color");
b1=new Button("Exit");
add(l1);
add(c1);
add(b1);
c1.addItemListener(this);
b1.addActionListener(this);
setVisible(true);
}
public static void main(String args[])
{
item e=new item("Event Handling");

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
System.exit(0);
}

}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==c1)
{
String s;
s=c1.getSelectedItem();
if(s.equals("Red"))
setBackground(Color.red);
else if(s.equals("Blue"))
setBackground(Color.blue);
else if(s.equals("Green"))
setBackground(Color.green);
else if(s.equals("Yellow"))
setBackground(Color.yellow);
}
}
}
___________________________________________________________________
______________________
using Mouse Listener
import java.awt.*;
import java.awt.event.*;
public class mouse extends Frame implements MouseListener
{
Button b1;
int w=250,h=150,count=0;
public mouse(String s)
{
super(s);
setLayout(new FlowLayout());
setSize(w,h);
b1=new Button("Mouse Move");
add(b1);
b1.addMouseListener(this);
setVisible(true);
}
public static void main(String args[])
{
mouse e=new mouse("Mouse Handling");

}
public void mouseExited(MouseEvent e)
{
if(e.getSource()==b1)
{
setBackground(Color.pink);
}
}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{
count++;
setTitle(Integer.toString(count)+" No of times cliked");
}
public void mouseEntered(MouseEvent e)
{
if(e.getSource()==b1)
{
w+=50;
h+=20;
setSize(w,h);
System.out.println(w+"\t"+h);
setBackground(Color.yellow);
}
}
}

_____________________________________________________

Key Listener

import java.awt.*;
import java.awt.event.*;
public class key extends Frame implements KeyListener
{
Button b1;
int x=50,y=200;
public key(String s)
{
super(s);
setLayout(new FlowLayout());
setSize(240,150);
b1=new Button("KeyPress");
add(b1);
b1.addKeyListener(this);
setVisible(true);
}
public static void main(String args[])
{
key e=new key("Key Handling");

}
public void keyPressed(KeyEvent e)
{
if(e.getSource()==b1)
{
setBackground(Color.red);
setSize(300,400);
setLocation(x,y);
x+=10;
y+=20;
b1.setLabel("Leave Me");
}
}
public void keyReleased(KeyEvent e)
{
if(e.getSource()==b1)
{
setBackground(Color.blue);
b1.setLabel("Press Me");
setSize(240,150);

}
}

public void keyTyped(KeyEvent e)


{

}
}

_________________________________________________________
Adapter Classes- The problem of Listener interfaces is that we must define all the
handlers either they are required or not?
We can solve this problem by using Adapter class. The adapter classes are-
1. KeyAdapter
2. MouseAdapter
3. WindowAdapter

Example
import java.awt.*;
import java.awt.event.*;
class win extends Frame
{
public win()
{
setTitle("Event Handling Window");
setLayout(new FlowLayout());
setSize(400,150);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setVisible(true);
}

}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

Working with AWT Components -


AWT stands for Abstract Window Toolkit , it is used for designing an user
interface. for adding a component to the window we will use add() and for
removing components to the window we will use remove() method.The AWT
Components are-
1. Label Class-used for showing any message on the window.
Constructor
Label()
Label(String s)
Label(String s,int align)
Label.LEFT
Label.CENTER
Label.RIGHT
Methods
setText()
getText()
2. TextField Class- This class construct an input field, & used for reading a value.
Constrcutors
TextField()
TextField(int size)
TextField(String text)
TextField(String text,int size)
Methods
setText()
getText()
3. Button- This class is used for creating a command button.
Constructors
Button()
Button(String label)
Methods
setLabel()
getLabel()
Example
import java.applet.*;
import java.awt.*;
public class awt extends Applet
{
Label l1;
TextField t1;
Button b1;
public void init()
{
l1=new Label("Enter Your Name ");
t1=new TextField(10);
b1=new Button("Click Here");
add(l1);
add(t1);
add(b1);
}
}
/*
<applet code="awt" width="400" height="200">
</applet>
*/
________________________________________________
4. Checkbox Class- This class is used for creating a checkbox & for creating radio
button we must pass the object of CheckboxGroup class.
Constructors
Checkbox()
Checkbox(String s)
Checkbox(String s,boolean select)
Checkbox(String s,CheckboxGroup object,boolean select) //create a radio
button
Example
import java.applet.*;
import java.awt.*;
public class awt extends Applet
{
Label l1,l2;
Checkbox cb1,cb2,cb3,cb4,cb5;
CheckboxGroup cbg;
public void init()
{

l1=new Label("Hobbies");
l1.setForeground(Color.red);
l2=new Label("Gender");
cb1=new Checkbox("Cricket",true);
cb2=new Checkbox("Singing");
cb3=new Checkbox("Reading");
cbg=new CheckboxGroup();
cb4=new Checkbox("Male",cbg,true);
cb5=new Checkbox("Female",cbg,false);
add(l1);
add(cb1);
add(cb2);
add(cb3);
add(l2);
add(cb4);
add(cb5);
}
}
/*
<applet code="awt" width="400" height="200">
</applet>
*/
______________________________________________________________
6. Choice & List Class - Choice class is used for creating a dropdown list while list
class is used for ceating a list box.
Constructors
Choice()
Constructors
List()
List(int nor,boolean select)
Methods
1. addItem() or add()
2. remove() or removeItem()
3. getSelectedItem()
Example
import java.applet.*;
import java.awt.*;
public class list extends Applet
{
Label l1,l2;
Choice c1;
List li1;

public void init()


{
l1=new Label("Select Name");
l2=new Label("Select City");
c1=new Choice();
li1=new List(3,true);
c1.add("Ravi");
c1.add("Vipin");
c1.add("Janmejay");
c1.add("Shashank");
c1.add("Dev");
li1.add("Allahabad");
li1.add("Delhi");
li1.add("Kanpur");
li1.add("Lucknow");
add(l1);
add(c1);
add(l2);
add(li1);
}
}
/*
<applet code="list" height=200 width=250>
</applet>
*/
_______________________________________________________

TextArea Class - this class used for creating a multiline input textbox
Constructors
TextArea(rows,cols)
Methods
setText()
getText()

import java.applet.*;
import java.awt.*;
public class awt extends Applet
{
Label l1;
TextArea t1;
public void init()
{
l1=new Label("Aaj Ka Vichar");
t1=new TextArea(5,20);
add(l1);
add(t1);
}
}
/*
<applet code="awt" width="400" height="200">
</applet>
*/

Working with Frame- Frame is used for creating a windows


based application.
Constructors
Frame()
Frame(String title)
Methods
setTitle()- sets the title of Frame
setSize(width, height)- sets the size of window
setVisible(boolean value)- sets the visibility of the frame
setLayout()- sets the layout of the frame
Example
import java.awt.*;
class win extends Frame
{
public win()
{
setTitle("My First Window");
setSize(400,300);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

____________________________________
Layout Managers- The Layout Managers allows for setting the layout of a window
means how the controls will arrange on the window, it will set by Layout
Managers.For setting layout managers we must use setLayout() method.
Layout Managers Classes are-
1. FlowLayout
2. GridLayout
3. BorderLayout

1. FlowLayout- This is the default layout of the applet.and it arrange the


components in relative manner.
Constructors
FlowLayout()
FlowLayout(int align)
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT

Example
import java.awt.*;
class win extends Frame
{
Label l1;
TextField t1;
Button b1;
FlowLayout flow;
public win()
{
setTitle("My First Window");
flow=new FlowLayout(FlowLayout.LEFT);
setLayout(flow);
l1=new Label("Enter Name ");
t1=new TextField(20);
b1=new Button("Click");
add(l1);
add(t1);
add(b1);
setSize(400,300);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

_________________________________________
GridLayout- This class arrange the components in tabular form.
Constructor
GridLayout(int rows,int cols);
import java.awt.*;
class win extends Frame
{
Label l1,l2,l3;
TextField t1,t2;
Button b1;
GridLayout grid;
public win()
{
setTitle("My First Window");
grid=new GridLayout(3,2);
setLayout(grid);
l1=new Label("Enter User Name ");
l2=new Label("Enter Password");
l3=new Label("");
t1=new TextField(20);
t2=new TextField(20);
t2.setEchoChar('*');
b1=new Button("Login");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(b1);
setSize(400,150);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

____________________________________________

BorderLayout- This Layout Managers Class arrange the elements into specific zone
of the window may be East,West,North,South or Center by default it is Center &
this is default layout of the Frame.
Example
import java.awt.*;
class win extends Frame
{
Label l1,l2;
public win()
{
setTitle("My First Window");
setLayout(new BorderLayout());
l1=new Label("United College",Label.CENTER);
l1.setBackground(Color.pink);
l2=new Label("Naini");
add(l1,"North");
add(l2,"South");
setSize(400,150);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

__________________________________________________________
import java.awt.*;
class win extends Frame
{
Label l1,l2;
public win()
{
setTitle("My First Window");
setLayout(new BorderLayout());
l1=new Label("Sushant IT College",Label.CENTER);
l1.setBackground(Color.pink);
l2=new Label("Naini");
add(l1,"North");
add(l2,"South");
setSize(400,150);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

__________________________________________
Note- for setting your own layout you can use setBounds() method with following
syntax-
objectname.setBounds(x,y,width,height)
Example
import java.awt.*;
class win extends Frame
{
Label l1,l2;
TextField t1,t2;
Button b1;
public win()
{
setTitle("Login Window");
setLayout(null);
l1=new Label("Enter User Name ");
l2=new Label("Enter Password");
t1=new TextField(20);
t2=new TextField(20);
b1=new Button("Login");
l1.setBounds(10,40,150,20);
t1.setBounds(160,40,120,20);
l2.setBounds(10,70,150,20);
t2.setBounds(160,70,120,20);
b1.setBounds(160,100,120,20);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
setSize(400,150);
setVisible(true);
}
}
class test
{
public static void main(String args[])
{
win obj=new win();
}
}

When we handle any application we interact with two types of


development techniques, this are-
1. FrontEnd Development
2. BackEnd Developement

1. FrontEnd Development- It specifies the user interface of an application. For


such type of developement we use-
a) Windows Application Developement - AWT, Swing
b)Web Technology - HTML,DHTML & Java Script
2. BackEnd Development- It specifies where the records will be stored, it may be
oracle, mysql, sql-server, ms-access etc.
JDBC - Java Database Connectivity- It is a programming technique which allows
you for accessing the contents of a database throgh java program. For
implementing JDBC you must import java.sql package. The important classes
which are used in jdbc are-
1. Connection Class- This class is used for stablishing a database connection. It
the initilized by a static method named as getConnection() of DriverManager
Class. like the following-
Connection c=DriverManager.getConnection();
the important methods are-
1. createStatement()- initilize a statement object
2. close()- close a connection
2. Statement Class - This class is used for working with sql statement. the
important methods are-
1. executeQuery()- process a select statement
2. executeUpdate()- process a DML(insert,update & delete) statement
3. ResultSet Class - This class creates a temporary storage area where the fetched
record by select statement could be stored for a short period of time.the methods
are-
1. next() - fetch the next record, false otherwise
2. getString() or getInt() - read the column value as per the datatype

Steps for Connecting with a database-


1. initilize database driver
2. initilize the connection object
3. pass the sql statement
4. execute the sql statement
JDBC Drivers- JDBC drivers allows you for intracting with database. There are 4
types of JDBC drivers but we use only 2 of then. These are-
1. JDBC - ODBC Driver
2. Pure Driver or Thin Driver

Example -1 Showing record from mysql-

import java.sql.*;
class jdbc
{
public static void main(String args[])
{
Connection con=null;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/adv","root","");
st=con.createStatement();
rs=st.executeQuery("select * from record");
System.out.println("ID\tName\tAge\tAddress");
while(rs.next())
{
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getInt(3)+"\t");
System.out.println(rs.getString(4));
}
con.close();

}catch(Exception e)
{
System.out.println(e.toString());
}
}
}

Example-2
import java.sql.*;
import java.io.*;
class jdbc
{
public static void main(String args[])
{
Connection con=null;
Statement st;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/adv","root","");

st=con.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int id,age;
String name,addr;
System.out.print("Enter ID :");
id=Integer.parseInt(br.readLine());
System.out.print("Enter Name :");
name=br.readLine();
System.out.print("Enter Age :");
age=Integer.parseInt(br.readLine());
System.out.print("Enter Address :");
addr=br.readLine();
//Numeric => "+variableName+"
//String => '"+variableName+"'
String sql="insert into record values("+id+",'"+name+"',"+age+",'"+addr+"')";

int res=st.executeUpdate(sql);
if(res!=0)
System.out.println("Record Inserted");
else
System.out.println("Record Not Inserted");
con.close();
}catch(Exception e)
{
System.out.println(e.toString());
}
}
}

Q1. You are required to design a class hierarchy supporting the polymorphic
code reuse for printing the details of a student that varies with the type of
student i.e. whether he is UG, PG, PhD or some other type of student added in
future. You should clearly bring out the differences among the design of class
hierarchy, application code where polymorphic code reuse is supported and
client code which exploits reuse supported through above design. Explain
various advantages obtained through above design. Implement above design
using Java/C++. (Student details for UG may be student name, roll-no,
department, SPI, CPI, …, For PG some fields like UG degree, UG institution may
be added, further for PhD the name of supervisor(s) may be added.)

You might also like