CMP 301 (NEW) Object Oriented Programming Langauage I
CMP 301 (NEW) Object Oriented Programming Langauage I
COURSE CONTENTS
Basic OOP Concepts: classes, objects, inheritance, polymorphism, Data abstraction, tools for
developing, compiling, interpreting and debugging, java programs, java syntax and data
objects, operators. Central flow constructs, objects and classes programming, arrays, methods,
exception, applets and the abstract, OLE, persistence, window toolkit, laboratory exercises in
an OOP language.
OBJECTIVES:
1. To teach the student the concepts of object oriented and procedure programming.
2. To differentiate between the basic OOP concepts of classes, objects, methods,
encapsulation, inheritance, polymorphism, data abstraction and method overloading.
3. To implement the basic concepts of OOP.
4. To design applications using JAVA syntax and data objects.
5. To teach student to implement arrays, exception handling, GUI and Windows.
LEARNING OUTCOMES
The students should be able to:
1. Differentiate the principles of object-oriented programming and procedural
programming.
2. Outline the essential features and elements of the Java programming language.
3. Explain programming fundamentals, including statement and control flow and
recursion.
4. Codes basic programs in Java programming language.
5. Uses objects and classes.
6. Lists the object-oriented programming concepts.
7. Codes object-oriented programs.
8. Explains and handles exceptions.
9. Writes multithreaded Java programs.
10. Understands the concepts of database and database management systems.
11. Uses generic classes and methods.
TEXT BOOK(S):
1. Object Oriented Programming and Java by Danny Poo, Derek Kiong and Swarnalatha Ashok
2. Java How To Program (9ed.) Deitel.
E-mail: [email protected]
1.0 BASIC OOP CONCEPTS
Object Oriented Programming (OOP) allows us to decompose a problem into a number of
entities called objects and then builds data and methods around these entities.
DEFINIION: OOP is a programming paradigm based upon objects (having both data and
methods) that aims to incorporate the advantages of modularity and reusability. Objects, which
are usually instances of classes, are used to interact with one another to design applications and
computer programs.
The important characteristics of OOP are:
i. Bottom–up approach in program design
ii. Programs organized around objects, grouped in classes
iii. Focus on data with methods to operate upon object’s data
iv. Interaction between objects through methods
v. Better abstraction (modelling data and methods together)
vi. Better maintainability (more comprehensible, less fragile)
vii. Better reusability design through creation of new classes by adding features to existing
classes.
Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi,
C#, Perl, Python, Ruby, and PHP etc.
Procedure Oriented Programming (POP)
In this approach, the problem is always considered as a sequence of tasks to be done. A number
of functions are written to accomplish these tasks. Here primary focus is on functions and little
attention on data.
There are many high-level languages like COBOL, FORTRAN, PASCAL, and C used for
conventional programming commonly known as POP.
Difference between POP and OOP
POP OOP
1. Program is divided into small parts called Program is divided into parts called objects.
functions.
2. Importance is not given to data but to Importance is given to the data rather than
functions as well as sequence of actions to procedures or functions because it works
be done. as a real world.
3. Follows Top Down approach. OOP follows Bottom Up approach.
4. It does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
5. Data can move freely from function to Objects can move and communicate with
function in the system. each other through member functions.
6. To add new data and function in POP is OOP provides an easy way to add new data
not so easy. and function.
7. Most function uses Global data for sharing In OOP, data cannot move easily from
that can be accessed freely from function function to function, it can be kept public or
to function in the system. private so we can control the access of data.
8. It does not have any proper way for hiding OOP provides Data Hiding so provides
data so it is less secure. more security.
9. Overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
10. Examples of POP are : C, VB, Examples of OOP are : C++, JAVA,
FORTRAN, Pascal, etc. VB.NET, C#.NET, Python, etc.
Declaring a Class
Line 4 begins a class declaration for class Welcome1. Every Java program consists of at least
one class that you (the programmer) define. The class keyword introduces a class declaration
and is immediately followed by the class name (Welcome1). Keywords (sometimes called
reserved words) are reserved for use by Java and are always spelled with all lowercase letters.
public class Welcome1
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type).
instanceof operator is written as:
(Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A
check for the class/interface type on the right side, then the result will be true. Following
is the example:
String name = “James”;
boolean result = name instanceof String; // This will return true since name is type of
String.
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more
Example:
Class Vehicle{
}
public class Car extends Vehicle{
public static void main(String args[]){
Vehicle ab =new Car();
boolean result = ab instanceof Car;
System.out.println(result);
}
}
This would produce the following result:
True
Example:
Class SingleSelection{
public static void main(String args[]){
int grade;
if(grade>=60)
System.out.println(“passed”);
}
}
• The if…else double selection statement performs an action if a condition is true and
performs a different action if the condition is false. Figure 3.3 illustrates the flow of
control in the if…else statement.
Class DoubleSelection{
public static void main(String args[]){
int grade;
if(grade>=60){
System.out.println(“passed”);
}else{
System.out.println(“failed”);
}
}
}
}
}
Figure 3.4 shows the UML activity diagram for the general switch statement. Most switch
statements use a break in each case to terminate the switch statement after processing the case.
Figure 3.4 emphasizes this by including break statements in the activity diagram. The diagram
makes it clear that the break statement at the end of a case causes control to exit the switch
statement immediately. The break statement is not required for the switch’s last case (or the
optional default case, when it appears last), because execution continues with the next
statement after the switch.
Fig. 3.4 | switch multiple-selection statement UML activity diagram with break statements.
Output:
1234
Broke out of loop
Continue statement
The continue statement, when executed in a while, for or do…while, skips the remaining
statements in the loop body and proceeds with the next iteration of the loop. In while and
do…while statements, the program evaluates the loop-continuation test immediately after the
continue statement executes. In a for statement, the increment expression executes, then the
program evaluates the loop-continuation test.
Example:
1 // ContinueTest.java
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4{
5 public static void main( String[] args )
6{
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8{
9 if ( count == 5 ) // if count is 5,
10 continue;
11 System.out.printf( "%d ", count );
12 } // end for
13 System.out.println( "\nUsed continue to skip printing 5" );
14 } // end main
15 } // end class ContinueTest
Output:
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
2. Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields within the class. For this reason,
encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is
tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.
Example: Let us look at an example that depicts encapsulation:
/* File name: EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
Public String getName(){
return name;
}
Public String getIdNum(){
return idNum;
}
Public void setName(String newName){
name = newName;
}
Public void setIdNum(String newIdNum){
idNum = newIdNum;
}
Public void setAge(int newAge){
age = newAge;
}
/* Run EncapTest.java */
public static void main(String args[]){
EncapTest encap =new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : "+ encap.getName()+" Age : "+ encap.getAge());
}
}
This would produce the following result:
Name:JamesAge:20
The public methods are the access points to this class' fields from the outside java world.
Normally, these methods are referred as getters and setters. Therefore, any class that wants
to access the variables should access them through these getters and setters. The variables
of the EncapTest class can be access as below:
3. Data abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one
that cannot be instantiated. All other functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot create an
instance of the abstract class. If a class is abstract and cannot be instantiated, the class does
not have much use unless it is subclass. This is typically how abstract classes come about
during the design phase. A parent class contains the common functionality of a collection
of child classes, but the parent class itself is too abstract to be used on its own.
An abstract class’s purpose is to provide an appropriate superclass from which other classes
can inherit and thus share a common design. When we think of a class, we assume that
programs will create objects of that type. Sometimes it’s useful to declare classes—called
abstract classes—for which you never intend to create objects. Because they’re used only
as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These
classes cannot be used to instantiate objects, because, as we’ll soon see, abstract classes are
incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes,
from which you can instantiate objects.
Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method
consists of a method signature, but no method body. Abstract method would have no
definition, and its signature is followed by a semicolon, not curly braces as follows:
/* File name : Employee.java */
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
public String toString() {
return name +" "+ address +" "+ number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still
has three fields, seven methods, and one constructor. Now if you would try as follows:
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
/* Following is not allowed and would raise error */
Employee e =new Employee("George W.","Houston, TX",43);
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
Extending Abstract Class:
We can extend Employee class in normal way as follows:
/* File name : Salary.java */
public class Salary extends Employee {
private double salary;//Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+ getName()+" with salary "+ salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >=0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for "+ getName());
return salary/52;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary
object, the Salary object will inherit the three fields and seven methods from
Employee.
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
This would produce the following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference –
Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600.0
Call mailCheck using Employee reference—
Within mailCheck of Salary class
Mailing check to JohnAdams with salary 2400.
4. Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP, occurs when a parent class reference is used to refer to a child class
object. Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
In Java, all Java objects are polymorphic since any object will pass the IS-A test for their
own type and for the class Object. It is important to know that the only possible way to
access an object is through a reference variable. A reference variable can be of only one
type. Once declared, the type of a reference variable cannot be changed. The reference
variable can be reassigned to other objects provided that it is not declared final. The type
of the reference variable would determine the methods that it can invoke on the object. A
reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Let us look at an example.
public interface Vegetarian{
}
public class Animal{
}
public class Deer extends Animal implements Vegetarian{
}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
• A Deer IS-A Animal
• A Deer IS-A Vegetarian
• A Deer IS-A Deer
• A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal:
Deer d =new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap
Example:
public class Employee {
private String name;
private String address;
private int number;
public Employee(String name,String address,int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
public String toString() {
return name +" "+ address +" "+ number;
}
publicString getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
public class Salary extends Employee {
private double salary;//Annual salary
public Salary(String name,String address,int number,double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+ getName() +" with salary "+salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >=0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for "+ getName());
return salary/52;
}
}
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
5. Method overloading
When a class has two or more methods by same name but different parameters, it is known
as method overloading. It is different from overriding. In overriding a method has same
method name, type, number of parameters etc. if number of parameters are same, then type
of parameters should be different.
Lets consider the example shown before for finding minimum numbers of integer type. If,
lets say we want to find minimum number of double type. Then the concept of Overloading
will be introduced to create two or more methods with the same name but different
parameters.
public class ExampleOverloading{
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
}
This would produce the following result:
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given same name
but with different parameters.
6. Inheritance
Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance, the information is made manageable in a hierarchical
order. When we talk about inheritance, the most commonly used keyword would be
extends and implements. These words would determine whether one object IS-A type of
another. By using these keywords, we can make one object acquire the properties of another
object.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
Programmer salary is: 40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has defined a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes
in io package, Server and ServerSocket classes in net packages and so on.
8. Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
• Class extends class
• Class implements interface
• Interface extends interface
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided
in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output: Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
The first sample execution in Fig. 5.1 shows a successful division. In the second execution, the
user enters the value 0 as the denominator. Several lines of information are displayed in
response to this invalid input. This information is known as a stack trace, which includes the
name of the exception (java.lang.ArithmeticException) in a descriptive message that indicates
the problem that occurred and the method-call stack (i.e., the call chain) at the time it occurred.
The stack trace includes the path of execution that led to the exception method by method. This
helps you debug the program. The first line specifies that an ArithmeticException has occurred.
The text after the name of the exception (“/ by zero”) indicates that this exception occurred as
a result of an attempt to divide by zero. Java does not allow division by zero in integer
arithmetic. When this occurs, Java throws an ArithmeticException. ArithmeticExceptions can
arise from a number of different problems in arithmetic, so the extra data (“/ by zero”) provides
more specific information. Java does allow division by zero with floating-point values. Such a
calculation results in the value positive or negative infinity, which is represented in Java as a
floating-point value (but displays as the string Infinity or -Infinity). If 0.0 is divided by 0.0, the
result is NaN (not a number), which is also represented in Java as a floating-point value (but
displays as NaN).
Starting from the last line of the stack trace, we see that the exception was detected in line 22
of method main. Each line of the stack trace contains the class name and method
(DivideByZeroNoExceptionHandling.main) followed by the file name and line number
(DivideByZeroNoExceptionHandling.java:22). Moving up the stack trace, we see that the
exception occurs in line 10, in method quotient. The top row of the call chain indicates the
throw point—the initial point at which the exception occurs. The throw point of this exception
is in line 10 of method quotient.
In the third execution, the user enters the string "hello" as the denominator. Notice again that a
stack trace is displayed. This informs us that an InputMismatchException has occurred
(package java.util). Our prior examples that read numeric values from the user assumed that
the user would input a proper integer value. However, users sometimes make mistakes and
input noninteger values. An InputMismatchException occurs when Scanner method nextInt
receives a string that does not represent a valid integer. Starting from the end of the stack trace,
we see that the exception was detected in line 20 of method main. Moving up the stack trace,
we see that the exception occurred in method nextInt. Notice that in place of the file name and
line number, we’re provided with the text Unknown Source. This means that the so-called
debugging symbols that provide the file name and line number information for that method’s
class were not available to the JVM—this is typically the case for the classes of the Java API.
Many IDEs have access to the Java API source code and will display file names and line
numbers in stack traces.
In the sample executions of Fig. 5.1 when exceptions occur and stack traces are displayed, the
program also exits. This does not always occur in Java—sometimes a program may continue
even though an exception has occurred and a stack trace has been printed. In such cases, the
application may produce unexpected results. For example, a graphical user interface (GUI)
application will often continue executing. The next section demonstrates how to handle these
exceptions.
In Fig. 5.1 both types of exceptions were detected in method main. In the next example, we’ll
see how to handle these exceptions to enable the program to run to normal completion.
5.2 Handling ArithmeticExceptions and InputMismatchExceptions
The application in Fig. 5.2, which is based on Fig. 5.1, uses exception handling to process any
ArithmeticExceptions and InputMistmatchExceptions that arise. The application still prompts
the user for two integers and passes them to method quotient, which calculates the quotient and
returns an int result. This version of the application uses exception handling so that if the user
makes a mistake, the program catches and handles (i.e., deals with) the exception—in this case,
allowing the user to enter the input again.
1 // Fig. 5.2: DivideByZeroWithExceptionHandling.java
2 // Handling ArithmeticExceptions and InputMismatchExceptions.
3 import java.util.InputMismatchException;
4 import java.util.Scanner;
5
6 public class DivideByZeroWithExceptionHandling
7{
8 // demonstrates throwing an exception when a divide-by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14
15 public static void main( String[] args )
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19
20 do
21 {
22 try // read two numbers and calculate quotient
23 {
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,
31 denominator, result );
32 continueLoop = false; // input successful; end looping
33 } // end try
34 catch ( InputMismatchException inputMismatchException )
35 {
36 System.err.printf( "\nException: %s\n",
37 inputMismatchException );
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 "You must enter integers. Please try again.\n" );
41 } // end catch
42 catch ( ArithmeticException arithmeticException )
43 {
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println(
46 "Zero is an invalid denominator. Please try again.\n" );
47 } // end catch
48 } while ( continueLoop ); // end do...while
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling
Fig. 5.2 | Handling ArithmeticExceptions and InputMismatchExceptions.
The first sample execution in Fig. 5.2 is a successful one that does not encounter any problems.
In the second execution the user enters a zero denominator, and an ArithmeticException
exception occurs. In the third execution the user enters the string "hello" as the denominator,
and an InputMismatchException occurs. For each exception, the user is informed of the mistake
and asked to try again, then is prompted for two new integers. In each sample execution, the
program runs successfully to completion.
Class InputMismatchException is imported in line 3. Class ArithmeticException does not need
to be imported because it’s in package java.lang. Line 18 creates the boolean variable
continueLoop, which is true if the user has not yet entered valid input. Lines 20–48 repeatedly
ask users for input until a valid input is received.
5.2.1 Enclosing Code in a try Block
Lines 22–33 contain a try block, which encloses the code that might throw an exception and
the code that should not execute if an exception occurs (i.e., if an exception occurs, the
remaining code in the try block will be skipped). A try block consists of the keyword try
followed by a block of code enclosed in curly braces. [Note: The term “try block” sometimes
refers only to the block of code that follows the try keyword (not including the try keyword
itself). For simplicity, we use the term “try block” to refer to the block of code that follows the
try keyword, as well as the try keyword]. The statements that read the integers from the
keyboard (lines 25 and 27) each use method nextInt to read an int value. Method nextInt throws
an InputMismatchException if the value read in is not an integer.
The division that can cause an ArithmeticException is not performed in the try block. Rather,
the call to method quotient (line 29) invokes the code that attempts the division (line 12); the
JVM throws an ArithmeticException object when the denominator is zero.
5.2.2 Catching Exceptions
The try block in this example is followed by two catch blocks—one that handles an
InputMismatchException (lines 34–41) and one that handles an ArithmeticException (lines 42–
47). A catch block (also called a catch clause or exception handler) catches (i.e., receives) and
handles an exception. A catch block begins with the keyword catch and is followed by a
parameter in parentheses (called the exception parameter, discussed shortly) and a block of
code enclosed in curly braces. [Note: The term “catch clause” is sometimes used to refer to the
keyword catch followed by a block of code, whereas the term “catch block” refers to only the
block of code following the catch keyword, but not including it. For simplicity, we use the term
“catch block” to refer to the block of code following the catch keyword, as well as the keyword
itself].
At least one catch block or a finally block must immediately follow the try block. Each catch
block specifies in parentheses an exception parameter that identifies the exception type the
handler can process. When an exception occurs in a try block, the catch block that executes is
the first one whose type matches the type of the exception that occurred (i.e., the type in the
catch block matches the thrown exception type exactly or is a superclass of it). The exception
parameter’s name enables the catch block to interact with a caught exception object—e.g., to
implicitly invoke the caught exception’s toString method (as in lines 37 and 44), which displays
basic information about the exception. Notice that we use the System.err (standard error
stream) object to output error messages. By default, System.err’s print methods, like those of
System.out, display data to the command prompt.
Line 38 of the first catch block calls Scanner method nextLine. Because an
InputMismatchException occurred, the call to method nextInt never successfully read in the
user’s data—so we read that input with a call to method nextLine. We do not do anything with
the input at this point, because we know that it’s invalid. Each catch block displays an error
message and asks the user to try again. After either catch block terminates, the user is prompted
for input.
An uncaught exception is one for which there are no matching catch blocks. You saw uncaught
exceptions in the second and third outputs of Fig. 5.1. Recall that when exceptions occurred in
that example, the application terminated early (after displaying the exception’s stack trace).
This does not always occur as a result of uncaught exceptions. Java uses a “multithreaded”
model of program execution—each thread is a parallel activity. One program can have many
threads. If a program has only one thread, an uncaught exception will cause the program to
terminate. If a program has multiple threads, an uncaught exception will terminate only the
thread where the exception occurred. In such programs, however, certain threads may rely on
others, and if one thread terminates due to an uncaught exception, there may be adverse effects
to the rest of the program.
5.2.3 Termination Model of Exception Handling
If an exception occurs in a try block (such as an InputMismatchException being thrown as a
result of the code at line 25 of Fig. 5.2), the try block terminates immediately and program
control transfers to the first of the following catch blocks in which the exception parameter’s
type matches the thrown exception’s type. In Fig. 5.2, the first catch block catches
InputMismatchExceptions (which occur if invalid input is entered) and the second catch block
catches ArithmeticExceptions (which occur if an attempt is made to divide by zero). After the
exception is handled, program control does not return to the throw point, because the try block
has expired (and its local variables have been lost). Rather, control resumes after the last catch
block. This is known as the termination model of exception handling. Some languages use the
resumption model of exception handling, in which, after an exception is handled, control
resumes just after the throw point.
Notice that we name our exception parameters (inputMismatchException and
arithmeticException) based on their type. Java programmers often simply use the letter e as the
name of their exception parameters.
After executing a catch block, this program’s flow of control proceeds to the first statement
after the last catch block (line 48 in this case). The condition in the do…while statement is true
(variable continueLoop contains its initial value of true), so control returns to the beginning of
the loop and the user is once again prompted for input. This control statement will loop until
valid input is entered. At that point, program control reaches line 32, which assigns false to
variable continueLoop. The try block then terminates. If no exceptions are thrown in the try
block, the catch blocks are skipped and control continues with the first statement after the catch
blocks. Now the condition for the do…while loop is false, and method main ends.
The try block and its corresponding catch and/or finally blocks form a try statement. Do not
confuse the terms “try block” and “try statement”—the latter includes the try block as well as
the following catch blocks and/or finally block.
As with any other block of code, when a try block terminates, local variables declared in the
block go out of scope and are no longer accessible; thus, the local variables of a try block are
not accessible in the corresponding catch blocks. When a catch block terminates, local variables
declared within the catch block (including the exception parameter of that catch block) also go
out of scope and are destroyed. Any remaining catch blocks in the try statement are ignored,
and execution resumes at the first line of code after the try…catch sequence—this will be a
finally block, if one is present.
5.2.4 Using the throws Clause
Now let’s examine method quotient (Fig. 5.2, lines 9–13). The portion of the method
declaration located at line 10 is known as a throws clause. It specifies the exceptions the method
throws. This clause appears after the method’s parameter list and before the method’s body. It
contains a comma-separated list of the exceptions that the method will throw if various
problems occur. Such exceptions may be thrown by statements in the method’s body or by
methods called from the body. A method can throw exceptions of the classes listed in its throws
clause or of their subclasses. We’ve added the throws clause to this application to indicate to
the rest of the program that this method may throw an ArithmeticException. Clients of method
quotient are thus informed that the method may throw an ArithmeticException.
When line 12 executes, if the denominator is zero, the JVM throws an ArithmeticException
object. This object will be caught by the catch block at lines 42–47, which displays basic
information about the exception by implicitly invoking the exception’s toString method, then
asks the user to try again.
If the denominator is not zero, method quotient performs the division and returns the result to
the point of invocation of method quotient in the try block (line 29). Lines 30–31 display the
result of the calculation and line 32 sets continueLoop to false. In this case, the try block
completes successfully, so the program skips the catch blocks and fails the condition at line 48,
and method main completes execution normally.
When quotient throws an ArithmeticException, quotient terminates and does not return a value,
and quotient’s local variables go out of scope (and are destroyed). If quotient contained local
variables that were references to objects and there were no other references to those objects,
the objects would be marked for garbage collection. Also, when an exception occurs, the try
block from which quotient was called terminates before lines 30–32 can execute. Here, too, if
local variables were created in the try block prior to the exception’s being thrown, these
variables would go out of scope.
If an InputMismatchException is generated by lines 25 or 27, the try block terminates and
execution continues with the catch block at lines 34–41. In this case, method quotient is not
called. Then method main continues after the last catch block (line 48).
5.3 When to use Exception Handling
Exception handling is designed to process synchronous errors, which occur when a statement
executes. Common examples:
• are out-of-range array indices
• arithmetic overflow (i.e., a value outside the representable range of values)
• division by zero
• invalid method parameters
• thread interruption and
• unsuccessful memory allocation (due to lack of memory).
Exception handling is not designed to process problems associated with asynchronous events
(e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which
occur in parallel with, and independent of, the program’s flow of control.
5.4 Java Exception Hierarchy
All Java exception classes inherit directly or indirectly from class Exception, forming an
inheritance hierarchy. You can extend this hierarchy with your own exception classes.
Figure 5.3 shows a small portion of the inheritance hierarchy for class Throwable (a subclass
of Object), which is the superclass of class Exception. Only Throwable objects can be used
with the exception-handling mechanism. Class Throwable has two subclasses: Exception and
Error. Class Exception and its subclasses—for instance, RuntimeException (package java.lang)
and IOException (package java.io)—represent exceptional situations that can occur in a Java
program and that can be caught by the application. Class Error and its subclasses represent
abnormal situations that happen in the JVM. Most Errors happen infrequently and should not
be caught by applications—it’s usually not possible for applications to recover from Errors.
Fig. 5.3 | Portion of class Throwable’s inheritance hierarchy.
Java catch block is used to handle the Exception. It must be used after the try block only. You
can use multiple catch block with a single try.
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule 3: For each try block there can be zero or more catch blocks, but only one finally block.
Figure 5.4 demonstrates that the finally block executes even if an exception is not thrown in
the corresponding try block. The program contains static methods main (lines 6–18),
throwException (lines 21–44) and doesNotThrowException (lines 47–64). Methods
throwException and doesNotThrowException are declared static, so main can call them
directly without instantiating a UsingExceptions object.
1 // Fig. 5.4: UsingExceptions.java
2 // try...catch...finally exception handling mechanism.
3
4 public class UsingExceptions
5{
6 public static void main( String[] args )
7 {
8 try
9 {
10 throwException(); // call method throwException
11 } // end try
12 catch ( Exception exception ) // exception thrown by throwException
13 {
14 System.err.println( "Exception handled in main" );
15 } // end catch
16
17 doesNotThrowException();
18 } // end main
19
20 // demonstrate try...catch...finally
21 public static void throwException() throws Exception
22 {
23 try // throw an exception and immediately catch it
24 {
25 System.out.println( "Method throwException" );
26 throw new Exception(); // generate exception
27 } // end try
28 catch ( Exception exception ) // catch exception thrown in try
29 {
30 System.err.println(
31 "Exception handled in method throwException" );
32 throw exception; // rethrow for further processing
33
34 // code here would not be reached; would cause compilation errors
35
36 } // end catch
37 finally // executes regardless of what occurs in try...catch
38 {
39 System.err.println( "Finally executed in throwException" );
40 } // end finally
41
42 // code here would not be reached; would cause compilation errors
43
44 } // end method throwException
45
46 // demonstrate finally when no exception occurs
47 public static void doesNotThrowException()
48 {
49 try // try block does not throw an exception
50 {
51 System.out.println( "Method doesNotThrowException" );
52 } // end try
53 catch ( Exception exception ) // does not execute
54 {
55 System.err.println( exception );
56 } // end catch
57 finally // executes regardless of what occurs in try...catch
58 {
59 System.err.println(
60 "Finally executed in doesNotThrowException" );
61 } // end finally
62
63 System.out.println( "End of method doesNotThrowException" );
64 } // end method doesNotThrowException
65 } // end class UsingExceptions
System.out and System.err are streams—sequences of bytes. While System.out (known as the
standard output stream) displays a program’s output, System.err (known as the standard error
stream) displays a program’s errors. Output from these streams can be redirected (i.e., sent to
somewhere other than the command prompt, such as to a file). Using two different streams
enables you to easily separate error messages from other output. For instance, data output from
System.err could be sent to a log file, while data output from System.out can be displayed on
the screen.
Java throw exception
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception. We will see custom exceptions
later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error”);
//java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing checkup before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared?
Ans) checked exception only, because:
• unchecked Exception: under your control so correct your code.
• error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
1. Checked Exception can be propagated (forwarded in call stack).
2. It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error"); //checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
There are two cases:
1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
Case2: You declare the exception
1. A) In case you declare the exception, if exception does not occur, the code will be
executed fine.
2. B) In case you declare the exception if exception occurs, an exception will be thrown
at runtime because throws does not handle the exception.
A) Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{ //declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output: device operation performed
normal flow...
Example 2
1 //InitArray.java
2 // Initializing the elements of an array with an array initializer.
3 public class InitArray
4{
5 public static void main( String[] args )
6 {
7 // initializer list specifies the value for each element
8 int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
9 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
10 // output each array element's value
11 for ( int counter = 0; counter < array.length; counter++ )
12 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
13 } // end main
14 } // end class InitArray
Output:
Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Fig. 6.2 | Two-dimensional array with three rows and four columns.
Two-Dimensional Arrays with Rows of Different Lengths:
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
Creating Two-Dimensional Arrays with Array-Creation Expressions:
int[][] b = new int[ 3 ][ 4 ];
A multidimensional array in which each row has a different number of columns can be created
as follows:
int[][] b = new int[ 2 ][ ]; // create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
Two-Dimensional Array Example: Displaying Element Values
Example:
1 //InitArray.java
2 // Initializing two-dimensional arrays.
3 public class InitArray
4{
5 // create and output two-dimensional arrays
6 public static void main( String[] args )
7 {
8 int[][] array1 = { { 1, 2, 3 }, { 4, 5, 6 } };
9 int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
10 System.out.println( "\nValues in array2 by row are" );
11 outputArray( array2 ); // displays array2 by row
12 } // end main
13 // output rows and columns of a two-dimensional array
14 public static void outputArray( )
15 {
16 System.out.println( "Values in array1 by row are" );
17 outputArray( array1 ); // displays array1 by row
18 System.out.println( "\nValues in array2 by row are" );
19 outputArray( array2 ); // displays array2 by row
20 } // end main
21 // output rows and columns of a two-dimensional array
22 public static void outputArray( )
21 {
22 // loop through array's rows
23 for ( int row = 0; row < array.length; row++ )
24 {
25 // loop through columns of current row
26 for ( int column = 0; column < array[ row ].length; column++ )
27 System.out.printf( "%d ", array[ row ][ column ] );
28
29 System.out.println(); // start new line of output
30 } // end outer for
31 } // end method outputArray
32 } // end class InitArray
Output:
Values in array1 by row are
1 2 3
4 5 6
Values in array2 by row are
1 2
3
4 5 6
7.0 INPUT/OUTPUT
The input/output class in Java allow us to make our programs more interactive by getting some
input from the user. The methods of getting input include the following:
1. Scanner class
i. Add this at the top of your code:
import java.util.Scanner;
ii. Add this statement:
Scanner st = new Scanner(System.in);
iii. Declare a temporary variable to get the input, and invoke the nextInt(),
nextDouble(), methods as the case may be to get input from the keyboard.
int a = st.nextInt();
2. BufferedReader class
i. Add this at the top of your code:
import java.io.*;
ii. Add this statement:
BufferedReader br = new BufferedReader(new InputStreamReader( System.in) );
iii. Declare a temporary String variable to get the input, and invoke the readLine()
method to get input from the keyboard. You have to type it inside a try-catch block.
try{
String temp = br.readLine();
}catch( IOException e ){
System.out.println(“Error in getting input”);
}
3. JOptionPane
Another way to get input from the user is by using the JOptionPane class which is found in
the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.
Example:
import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name;
name = JOptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
}
}
This will output:
8.0 LABORATORY EXERCISES IN AN OOP LANGUAGE
1. Write a java program that can accept two matrices of any length of rows and columns
and perform arithmetic operations on them. The program should include a decision
menu that gives the user the chance to determine the number and type of arithmetic
operation (addition, subtraction and multiplication) to perform. [Hint: Use the switch
statement].
2. Write an application that reads array of integer numbers and perform different
operations on them. [Hint: addition, min, max, range, mode, median, mean, variance,
standard deviation, sorting, print even and odd numbers, etc.]
3. Define a Square class with the length of its side as an instance variable. Include an
appropriate constructor method and methods to enlarge an instance as well as compute
its area.
4. Using the Square class in Question 1, create ten randomly sized squares and find the
sum of their areas. (The method Math.random() returns a random number between 0.0
and 1.0 each time it is invoked).
5. Add the functionality for a Square object to draw itself via ASCII characters. For
example, a Square of length 4 can be drawn as:
****
* *
* *
****
Or:
XXXX
X++X
X++X
XXXX
The System.out.print() and System.out.println() methods may be useful.
6. Find a number with nine digits d1d2d3,…, d9 such that the sub-string number d1, …,
dn is divisible by n, 1<=n<=9. Note that each of the digits may be used once.
7. Design a simple calculator in Java using any relevant OOP features.
8. Write an application that reads five integers and determines and prints the largest and
smallest integers in the group. Use only the OOP techniques you learned in this course.
9. Write an application that reads two integers, determines whether the first is a multiple
of the second and prints the result. [Hint: Use the remainder operator.]
10. Explain why a class might provide a set method and a get method for an instance
variable.
11. Create a class called Employee that includes three instance variables—a first name
(type String), a last name (type String) and a monthly salary (double). Provide a
constructor that initializes the three instance variables. Provide a set and a get method
for each instance variable. If the monthly salary is not positive, do not set its value.
Write a test application named EmployeeTest that demonstrates class Employee’s
capabilities. Create two Employee objects and display each object’s yearly salary. Then
give each Employee a 10% raise and display each Employee’s yearly salary again.
12. Create a class called Date that includes three instance variables—a month (type int), a
day (type int) and a year (type int). Provide a constructor that initializes the three
instance variables and assumes that the values provided are correct. Provide a set and a
get method for each instance variable. Provide a method displayDate that displays the
month, day and year separated by forward slashes (/). Write a test application named
DateTest that demonstrates class Date’s capabilities.
13. 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
getInvoiceAmount 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.
14. Explain what happens when a Java program attempts to divide one integer by another.
What happens to the fractional part of the calculation? How can you avoid that
outcome?
15. Develop a Java application that determines the gross pay for each of three employees.
The company pays straight time for the first 40 hours worked by each employee and
time and a half for all hours worked in excess of 40. You’re given a list of the
employees, their number of hours worked last week and their hourly rates. Your
program should input this information for each employee, then determine and display
the employee’s gross pay. Use class Scanner to input the data.
16. Write an application that prompts the user to enter the size of the side of a square, then
displays a hollow square of that size made of asterisks. Your program should work for
squares of all side lengths between 1 and 20.
17. A palindrome is a sequence of characters that reads the same backward as forward. For
example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554
and 11611. Write an application that reads in a five-digit integer and determines
whether it’s a palindrome. If the number is not five digits long, display an error message
and allow the user to enter a new value.
18. Write an application that demonstrates drawing rectangles and ovals, using the
Graphics methods drawRect and drawOval, respectively. Your program graphical
interface should include option menu that require the user to input 1 to draw rectangles
and 2 to draw ovals.
19. A right triangle can have sides whose lengths are all integers. The set of three integer
values for the lengths of the sides of a right triangle is called a Pythagorean triple. The
lengths of the three sides must satisfy the relationship that the sum of the squares of two
of the sides is equal to the square of the hypotenuse. Write an application that displays
a table of the Pythagorean triples for side1, side2 and the hypotenuse, all no larger than
500. Use a triple-nested for loop that tries all possibilities. This method is an example
of “brute-force” computing. You’ll learn in more advanced computer science courses
that for many interesting problems there’s no known algorithmic approach other than
using sheer brute force.
20. Write a method isMultiple that determines, for a pair of integers, whether the second
integer is a multiple of the first. The method should take two integer arguments and
return true if the second is a multiple of the first and false otherwise. [Hint: Use the
remainder operator]. Incorporate this method into an application that inputs a series of
pairs of integers (one pair at a time) and determines whether the second value in each
pair is a multiple of the first.
21. Write a method isEven that uses the remainder operator (%) to determine whether an
integer is even. The method should take an integer argument and return true if the
integer is even and false otherwise. Incorporate this method into an application that
inputs a sequence of integers (one at a time) and determines whether each is even or
odd.
22. Use a one-dimensional array to solve the following problem: Write an application that
inputs five numbers, each between 10 and 100, inclusive. As each number is read,
display it only if it’s not a duplicate of a number already read. Provide for the “worst
case,” in which all five numbers are different. Use the smallest possible array to solve
this problem. Display the complete set of unique values input after the user enters each
new value.
23. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram,
Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Create and
use a Point class to represent the points in each shape. Make the hierarchy as deep (i.e.,
as many levels) as possible. Specify the instance variables and methods for each class.
The private instance variables of Quadrilateral should be the x-y coordinate pairs for
the four endpoints of the Quadrilateral. Write a program that instantiates objects of your
classes and outputs each object’s area (except Quadrilateral).