Java Basics
Java Basics
This handout is a traditional introduction to any language features. You might not be able to comprehend
some of the features fully at this stage but don’t worry, you’ll get to know about these as we move on with the
course
Design Goals of Java
The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at
development of software that can run on different platforms like Windows, Linux and Solaris etc.
Right Language, Right Time
Java came on the scene in 1995 to immediate popularity.
Before that, C and C++ dominated the software development
1. compiled, no robust memory model, no garbage collector causes memory leakages, not great support of
built in libraries
Java brings together a great set of "programmer efficient" features
2. Putting more work on the CPU to make things easier for the programmer.
Java – Buzzwords (Vocabulary)
From the original Sun Java whitepaper: "Java is a simple, object-oriented, distributed, interpreted, robust,
secure, architecture-neutral, portable, high- performance, multi-threaded, and dynamic language."
Here are some original java buzzwords...
Java -- Language + Libraries
Java has two parts...
1. The core language -- variables, arrays, objects
o The Java Virtual Machine (JVM) runs the core language
o The core language is simple enough to run on small devices -- phones, smart cards,
PDAs.
2. The libraries
o Java includes a large collection of standard library classes to provide "off the shelf" code.
(Useful built-in classes that comes with the language to perform basic tasks)
o Example of these classes is String, ArrayList, HashMap, StringTokenizer (to
break string into substrings), Date ...
o Java programmers are more productive in part because they have access to a large set of
standard, well documented library classes.
Simple
Very similar C/C++ syntax, operators, etc.
The core language is simpler than C++ -- no operator overloading, no pointers, and no multiple
Inheritance.
The way a java program deals with memory is much simpler than C or C++.
Object-Oriented
Java is fundamentally based on the OOP notions of classes and objects.
Java uses a formal OOP type system that must be obeyed at compile-time and run-time.
This is helpful for larger projects, where the structure helps keep the various parts consistent. Contrast to
Perl, which has a more anything-goes feel.
Distributed / Network Oriented
Java is network friendly -- both in its portable, threaded nature, and because common networking
operations are built-in to the Java libraries.
Robust / Secure / Safe
• Java is very robust
o Both, vs. unintentional errors and vs. malicious code such as viruses.
o Java has slightly worse performance since it does all this checking. (Or put the other way, C
can be faster since it doesn't check anything.)
• The JVM "verifier" checks the code when it is loaded to verify that it has the correct structure --
that it does not use an uninitialized pointer, or mix int and pointer types. This is one-time "static"
analysis -- checking that the code has the correct structure without running it.
• The JVM also does "dynamic" checking at runtime for certain operations, such as pointer and
array access, to make sure they are touching only the memory they should. You will write code
that runs into
• As a result, many common bugs and security problems (e.g. "buffer overflow") are not possible
in java. The checks also make it easier to find many common bugs easy, since they are caught by
the runtime checker.
• You will generally never write code that fails the verifier, since your compiler is smart enough to
only generate correct code. You will write code that runs into the runtime checks all the time as
you debug -- array out of bounds, null pointer.
• Java also has a runtime Security Manager can check which operations a particular piece of code is
allowed to do. As a result, java can run un-trusted code in a "sandbox" where, for example, it can
draw to the screen but cannot access the local file system.
Portable
"Write Once Run Anywhere", and for the most part this works.
Not even a recompile is required -- a Java executable can work, without change, on any Java enabled
platform.
Support for Web and Enterprise Web Applications
Java provides an extensive support for the development of web and enterprise applications
Servlets, JSP, Applets, JDBC, RMI, EJBs and JSF etc. are some of the Java technologies that can be
used for the above mentioned purposes.
High-performance
The first versions of java were pretty slow.
Java performance has gotten a lot better with aggressive just-in-time-compiler (JIT) techniques.
Java performance is now similar to C -- a little slower in some cases, faster in a few cases. However
memory use and startup time are both worse than C.
Java performance gets better each year as the JVM gets smarter. This works, because making the
JVM smarter does not require any great change to the java language, source code, etc.
Multi-Threaded
Java has a notion of concurrency wired right in to the language itself.
This works out more cleanly than languages where concurrency is bolted on after the fact.
Dynamic
Class and type information is kept around at runtime. This enables runtime loading and
inspection of code in a very flexible way.
Java Compiler Structure
The source code for each class is in a .java file. Compile each class to produce
“.class” file.
Sometimes, multiple .class files are packaged together into a .zip or .jar "archive"
file.
On unix or windows, the java compiler is called "javac". To compile all the .java files in a directory use
"javac *.java".
Bytecode
Java programs (Source code) are compiled into a form called Java bytecodes.
The Java compiler reads Java language source (.java) files, translates the source into
Java bytecodes, and places the bytecodes into class (.class) files.
The compiler generates one class file for each class contained in java source file.
References
Phase 1: Edit
Phase 1 consists of editing a file. This is accomplished with an editor program. The programmer types a
java program using the editor like notepad, and make corrections if necessary.
When the programmer specifies that the file in the editor should be saved, the program is stored on a
secondary
storage device such as a disk. Java program file name ends with a
.java extension.
On Windows platform, notepad is a simple and commonly used editor for the beginners. However java
integrated development environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM’s
Ecllipse have built-in editors that are smoothly integrated into the programming environment.
Phase 2: Compile
In Phase 2, the programmer gives the command javac to compile the program. The java compiler translates
the
java program into bytecodes, which is the language understood by the java interpreter.
To compile a program called Welcome.java, type
javac Welcome.java
at the command window of your system. If the program compiles correctly, a file called Welcome.class is
produced. This is the file containing the bytecodes that will be interpreted during the execution phase.
Phase 3: Loading
In phase 3, the program must first be placed in memory before it can be executed. This is done by the class
loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. The .class file
can be loaded from a disk on your system or over a network (such as your local university or company
network
or even the internet).
Applications (Programs) are loaded into memory and executed using the java interpreter
via the command java. When executing a Java application called Welcome, the command
Java Welcome
Invokes the interpreter for the Welcome application and causes the class loader to load information used in
the Welcome program.
Phase 4: Verify
Before the bytecodes in an application are executed by the java interpreter, they are verified by the bytecode
verifier in
Phase 4. This ensures that the bytecodes for class that are loaded form the internet (referred to as
downloaded classes)
are valid and that they do not violate Java’s security restrictions.
Java enforces strong security because java programs arriving over the network should not be able to cause
damage
to your files and your system (as computer viruses might).
Phase 5: Execute
Finally in phase 5, the computer, under the control of its CPU, interprets the program one bytecode at a time.
Thus performing the actions specified by the program.
Programs may not work on the first try. Each of the preceding phases can fail because of various errors. This
would cause the java program to print an error message. The programmer would return to the edit phase,
make the necessary corrections and proceed through the remaining phases again to determine id the
corrections
work properly.
References:
Java™ How to Program 5th edition by Deitel & Deitel
Sun Java online tutorial: http://java.sun.com/docs/books/tutorial/java/index.html
Installation and Environment Setting
Installation
• Download the latest version j2se5.0 (java 2 standard edition) from http://java.sun.com
or get it from any other source like CD.
Note: j2se also called jdk (java development kit). You can also use the previous versions like jdk 1.4 or
1.3 etc. but it is recommended that you use either jdk1.4 or jdk5.0
• Install j2se5.0 on your system
Note: For the rest of this handout, assume that j2se is installed in C:\Program
Files\Java\jdk1.5.0
Environment Setting
Once you successfully installed the j2se, the next step is environment or path setting. You can
accomplish this in either of two ways.
• Temporary Path Setting
Open the command prompt from Start Æ Programs Æ Accessories Æ Comman
Prompt. The command prompt screen would be opened in front of you.
Write the command on the command prompt according to the following format
path = < java installation directory\bin >
So, according to handout, the command will look like this
path = C:\Program Files\Java\jdk1.5.0\bin
To Test whether path has been set or not, write javac and press ENTER. If the list ofn b
options displayed as shown in the below figure means that you have successfully
completed the steps of path setting.
The above procedure is illustrates in the given below picture.
Note: The issue with the temporary path setting is you have to repeat the above explained procedure
again and again each time you open a new command prompt window. To avoid this overhead, it is better
to set your path permanently
• Permanent Path Setting
In Windows NT (XP, 2000), you can set the permanent environment variable.
Right click on my computer icon click on properties as shown below
A System Properties frame would appeared as shown in the picture
Select the advanced tab followed by clicking the Environment Variable button. The
Environment variables frame would be displayed in front of you
Locate the Path variable in the System or user variables, if it is present there, select it by single
click. Press Edit button. The following dialog box would be appeared.
• Write; C:\Program Files\Java\jdk1.5.0\bin at the end of the value field. Press OK button.
Remember to write semicolon (;) before writing the path for java installation directory as illustrate in
the above figure
• If Path variable does not exist, click the New button. Write variable name
“PATH”, variable value C:\Program Files\Java\jdk1.5.0\bin and press OK button.
• Now open the command prompt and write javac, press enter button. You see the list of options
would be displayed.
• After setting the path permanently, you have no need to set the path for each new opened
command prompt.
References
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is
available just for the use of students of the course Web Design and Development and not for any other
commercial purpose without the consent of author.
First Program in Java
Like any other programming language, the java programming language is used to create applications. So, we
start from building a classical “Hello World” application, which is generally used as the first program for
learning any new language.
HelloWorldApp
1. Open notepad editor from Start Æ ProgarmFiles Æ AccessoriesÆ Notepad.
2. Write the following code into it.
Note: Don’t copy paste the given below code. Probably it gives errors and you can’t able to remove them at
the
beginning stage.
3. To save your program, move to File menu and choose save as option.
4. Save your program as “HelloWorldApp.java” in some directory. Make sure to add double quotes around
class name while saving your program. For this example create a folder known as “examples” in D: drive
Note: Name of file must match the name of the public class in the file (at line 4). Moreover, it is case
sensitive. For example, if your class name is MyClass, than file name must be MyClass. Otherwise the
Java compiler will refuse to compile the program.
For the rest of this handout, we assume that program is saved in D:\examples directory.
HelloWorldApp Described
Lines 1-3
Like in C++, You can add multiple line comments that are ignored by the compiler.
Lines 4
Line 4 declares the class name as HelloWorldApp. In java, every line of code must reside inside class. This is
also the name of our program (HelloWorldApp.java). The compiler creates the HelloWorldApp.class if this
program successfully gets compiled.
Lines 5
Line 5 is where the program execution starts. The java interpreter must find this defined exactly as
given or it will refuse to run the program. (However you can change the name of parameter that is
passed to main. i.e. you can write String[] argv or String[] some Param instead of String[] args)
Other programming languages, notably C++ also use the main( ) declaration as the starting point for
execution. However the main function in C++ is global and reside outside of all classes where as in Java
the main function must reside inside a class. In java there are no global variables or functions. The various
parts of this main function declaration will be covered at the end of this handout.
Lines 6
Again like C++, you can also add single line comment
Lines 7
Line 7 illustrates the method call. The println( ) method is used to print something on the console.
In this example println( ) method takes a string argument and writes it to the standard output i.e. console.
Lines 8-9
Line 8-9 of the program, the two braces, close the method main( ) and the class
HelloWorldApp respectively.
Points to Remember
□ Recompile the class after making any changes
□ Save your program before compilation
□ Only run that class using java command that contains the main method, because program executions
always starts form main
An Idiom Explained
You will see the following line of code often:
– public static void main(String args[]) { …}
• About main()
“main” is the function from which your program starts
Why public?
Since main method is called by the JVM that is why it is kept public so that it is
accessible from outside. Remember private methods are only accessible from within the
class
Why static?
Every Java program starts when the JRE (Java Run Time Environment) calls the
main method of that program. If main is not static then the JRE have to create an
object of the class in which main method is present and call the main method on that
object (In OOP based languages method are called using the name of object if they are
not static). It is made static so that the JRE can call it without creating an object.
Also to ensure that there is only one copy of the main method per class
Why void?
• Indicates that main ( ) does not return anything.
What is String args[] ?
Way of specifying input (often called command-line arguments) at startup of
application. More on it latter
References
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is
available just for the use of students of the course Web Design and Development and not for any other
commercial purpose with out the consent of author.
Learning Basics
Strings
A string is commonly considered to be a sequence of characters stored in memory and accessible as a unit.
Strings in java are represented as objects.
String Concatenation
“+” operator is used to concatenate strings
– System.out.pritln(“Hello” + “World”) will print Hello World on console
String concatenated with any other data type such as int will also convert that datatype to String and
the result will be a concatenated String displayed on console. For example,
– int i = 4;
– int j = 5;
System.out.println (“Hello” + i)
will print Hello 4 on screen
– However
System,.out..println( i+j) ;
will print 9 on the console because both i and j are of type int.
Comparing Strings
For comparing Strings never use == operator, use equals method of String class.
– == operator compares addresses (shallow comparison) while equals compares values (deep
comparison)
E.g string1.equals(string2)
Output
C:\java AnyArgsApp i can pass any number of arguments
Argument:0 value i
Argument:1 value can
Argument:2 value pass
Argument:3 value any
Argument:4 value number
Argument:5 value of
Argument:6 value arguments
Primitives vs Objects
• Everything in Java is an “Object”, as every class by default inherits from class
“Object” , except a few primitive data types, which are there for efficiency reasons.
• Primitive Data Types
Primitive Data types of java
boolean, byte 1 byte
char, short 2 bytes
int, float 4 bytes
long, double 8 bytes
• Primitive data types are generally used for local variables, parameters and instance variables
(properties of an object)
• Primitive datatypes are located on the stack and we can only access their value, while objects are
located on heap and we have a reference to these objects
• Also primitive data types are always passed by value while objects are always passed by reference in
java. There is no C++ like methods
– void someMethod(int &a, int & b ) // not available in java
Stack vs. Heap
Stack and heap are two important memory areas. Primitives are created on the stack while objects are
created on heap. This will be further clarified by looking at the following diagram that is taken from Java
Lab Course.
Wrapper Classes
Each primitive data type has a corresponding object (wrapper class). These wrapper classes provides
additional functionality (conversion, size checking etc.), which a primitive data type cannot provide.
Wrapper Use
You can create an object of Wrapper class using a String or a primitive data type
• Integer num = new Integer(4); or
• Integer num = new Integer(“4”);
Note: num is an object over here not a primitive data type
You can get a primitive data type from a Wrapper using the corresponding value function
• int primNum = num.intValue();
Converting Strings to Numeric Primitive Data Types
To convert a string containing digits to a primitive data type, wrapper classes can help. parseXxx method can
be used to convert a String to the corresponding primitive data type.
String value = “532”;
int d = Integer.parseInt(value);
String value = “3.14e6”;
double d = Double.parseDouble(value);
The following table summarizes the parser methods available to a java programmer.
Defining a Class
// File Test.java
public class Test{
public static void main (String args[]){
int numObjects;
// printing current number of objects i.e 0
numObjs = Student.getCountStudents();
System.out.println(“Students Objects” + numObjects);
// Creating first student object & printing its values
Student s1 = new Student("ali", 15);
System.out.println(“Student: ” + s1.toString());
// printing current number of objects i.e. 1
numObjs = Student.getCountStudents();
System.out.println(“Students Objects” + numObjects);
// Creating second student object & printing its values
Student s2 = new Student("usman", 49);
// implicit call to toString() method
System.out.println(“Student: ” + s2);
// printing current number of objects i.e. 2
numObjs = Student.getCountStudents();
System.out.println(“Students Objects” + numObjects);
// loosing object reference
s1 = null
// requesting JVM to run Garbage collector but there is
// no guarantee that it will run
System.gc();
// printing current number of objects i.e. unpredictable
numObjs = Student.getCountStudents();
System.out.println(“Students Objects” + numObjects);
} //end of main
} //end of class
The compilation and execution of the above program is given below. Note that output may be different
one given here because it all depends whether garbage collector reclaims the memory or not. Luckily, in my
case it does.
Reference:
Sun java tutorial: http://java.sun.com/docs/books/tutorial/java
Thinking in java by Bruce Eckle
Beginning Java2 by Ivor Hortan
Example code, their explanations and corresponding execution figures for this handout are taken
from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of
students of the course Web Design and Development and not for any other commercial purpose
without the consent of author.
Inheritance
In general, inheritance is used to implement a “is-a” relationship. Inheritance saves code rewriting for a client
thus promotes reusability.
In java parent or base class is referred as super class while child or derived class is known as sub class.
Comparison with C++
□Java only supports single inheritance. As a result a class can only inherit from one class at one time.
□Keyword extends is used instead of “:” for inheritance.
□All functions are virtual by default
□All java classes inherit from Object class (more on it later).
□To explicitly call the super class constructor, use super keyword. It’s important to remember that call to super
class constructor must be first line.
□Keyword super is also used to call overridden methods.
The Teacher class extends from Employee class. Therefore Teacher class is a subclass of
Employee. The teacher class has an additional attribute i.e. qualification.
class Teacher extends Employee{
private String qual;
//default constructor
public Teacher () {
//implicit call to superclass default construct
qual = "";
}
//parameterized constructor
public Teacher(int i, String n, String q){
//call to superclass param const must be first line
super(i,n);
qual = q;
}
//setter
public void setQual (String qual){
this.qual = qual;
}
//getter
public String getQual(){
return qual;
}
//overriding display method of Employee class
public void display(){
System.out.println("in teacher's display method");
super.display(); //call to superclass display method
System.out.println("Teacher qualification:" + qual);
}
//overriding toString method of Employee class
public String toString() {
System.out.println("in teacher's toString method");
String emp = super.toString();
return emp +" qualification:" + qual;
}
}//end class
Objects of Employee & Teacher class are created inside main method in Test class. Later calls are made to
display
and toString method using these objects.
class Test{
public static void main (String args[]){
System.out.println("making object of employee");
Employee e = new Employee(89, "khurram ahmad");
System.out.println("making object of teacher");
Teacher t = new Teacher (91, "ali raza", "phd");
e.display(); //call to Employee class display method
t.display(); //call to Teacher class display method
// calling employee class toString method explicitly
System.out.println("Employee: " +e.toString());
// calling teacher class toString implicitly
System.out.println("Teacher: " + t);
} //end of main
}//end class
Output
Output
Type Casting
In computer science, type conversion or typecasting refers to changing an entity of one datatype into
another.
Type casting can be categorized into two types
1. Up-casting
Converting a smaller data type into bigger one
Implicit – we don’t have to do something special
No loss of information
Examples of
— Primitives
int a = 10;
double b = a;
— Classes
Employee e = new Teacher( );
2. Down-casting
Converting a bigger data type into smaller one
Explicit – need to mention
Possible loss of information
Examples of
— Primitives
double a = 7.65;
int b = (int) a;
— Classes
Employee e = new Teacher( ); // up-casting
Teacher t = (Teacher) e; // down-casting
References:
Java tutorial: http://java.sun.com/docs/books/tutorial/java/javaOO/
Stanford University
Example code, their explanations and corresponding figures for handout 5-1,5-2 are taken from the
book JAVA A Lab Course by Umair Javed. This material is available just for the use of
students of the course Web Design and Development and not for any other commercial purpose
without the consent of author.
Collections
A collection represents group of objects know as its elements. Java has a built-in support for collections.
Collection classes are similar to STL in C++. An advantage of a collection over an array is that you don’t
need to
know the eventual size of the collection in order to add objects to it. The java.util package provides a set of
collection classes that helps a programmer in number of ways.
Collections Design
All classes almost provides same methods like get(), size(), isEmpty() etc. These methods will return the
object
stored in it, number of objects stored and whether collection contains an object or not respectively.
Java collections are capable of storing any kind of objects. Collections store references to objects. This is
similar to
using a void* in C. therefore down casting is required to get the actual type. For example, if string in stored in
a
collection then to get it back, we write
String element = (String)arraylist.get(i);
Collection messages
Some basic messages (methods) are:
Constructor
— creates a collection with no elements
int size()
— returns the number of elements in a collection
boolean add(Object)
— adds a new element in the collection
— returns true if the element is added successfully false otherwise
boolean isEmpty()
— returns true if this collection contains no element false otherwise
boolean contains(Object)
— returns true if this collection contains the specified element by using iterative search
boolean remove(Object)
— removes a single instance of the specified element from this collection, if it is present
ArrayList
It’s like a resizable array. ArrayList actually comes as a replacement the old “Vector” collection. As we add or
remove elements into or from it, it grows or shrinks over time.
Useful Methods
add (Object)
— With the help of this method, any object can be added into ArrayList because
Object is the super class of all classes.
— Objects going to add will implicitly up-cast.
Object get(int index)
— Returns the element at the specified position in the list
— index ranges from 0 to size()-1
— must cast to appropriate type
remove (int index)
— Removes the element at the specified position in this list.
— Shifts any subsequent elements to the left (subtracts one from their indices).
int size( )
Example Code: Using ArrayList class
We’ll store Student objects in the ArrayList. We are using the same student class which we built in previous
lectures/handouts.
We’ll add three student objects and later prints all the student objects after retrieving them from ArrayList.
Let’s look at the code
iport java.util.*;
public class ArrayListTest {
public static void main(String[] args) {
// creating arrayList object by calling constructor
ArrayList al= new ArrayList();
// creating three Student objects
Student s1 = new Student (“ali” , 1);
Student s2 = new Student (“saad” , 2);
Student s3 = new Student (“raza” , 3);
// adding elements (Student objects) into arralylist al.add(s1);
al.add(s2);
al.add(s3);
HashMap
Store elements in the form of key- value pair form. A key is associated with each object that is stored. This
allows fast retrieval of that object. Keys are unique.
Useful Methods
put(Object key, Object Value)
— Keys & Values are stored in the form of objects (implicit upcasting is performed).
— Associates the specified value with the specified key in this map.
— If the map p reviously contained a mapping for this key, the old value is replaced.
Object get(Object key)
— Returns the value to which the specified key is mapped in this identity hash map, or null if the
map contains no mapping for this key.
— Must downcast to appropriate type when used
int size( )
Example Code: using HashMap class
In this example code, we’ll store Student objects as values and their rollnos in the form of strings as keys.
Same
Student class is used. The code is;
iport java.util.*;
public class HashMapTest {
public static void main(String[] args) {
// creating HashMap object
HashMap h= new HashMap();
// creating Student objects
Student s1 = new Student (“ali” , 1); Student s2 = new Student (“saad” ,
2); Student s3 = new Student (“raza” , 6);
// adding elements (Student objects) where roll nos
// are stored as keys and student objects as values
h.add(“one” , s1); h.add(“two” , s2);
h.add(“six”, s3);
// checking whether hashmap is empty or not boolean b = h.isEmpty ();
if (b = = true) {
System.out.println(“hashmap is empty”);
} else {
int size = h.size();
System.out.println(“hashmap size: ” + size);
}
// retrieving student object against rollno two and
// performing downcasting
Student s = (Student) h.get(“two”);
// calling student’s class print method s.print();
} // end main
} // end class
Output
Address Book
Warning: It is strongly advised that you type the code given in this example yourself. Do not copy/paste it;
most probably you will get unexpected errors that you have never seen. Some bugs are deliberately
introduced as well to avoid copy- pasting. TAs will not cooperate with you in debugging such
errorsʄ.
Problem
We want to build an address book that is capable of storing name, address & phone number of a person.
Address book provides functionality in the form of a JOptionPane based menu. The feature list includes
□ Add – to add a new person record
□ Delete – to delete an existing person record by name
□ Search – to search a person record by name
□ Exit – to exit from application
The Address book should also support persistence for person records
Approach for Solving Problem
Building a small address book generally involves 3 steps. Let us briefly discuss each step and write a solution
code
for each step
Step1 – Make PersonInfo class
First of all you need to store your desired information for each person. For this you can create a userdefined
data type (i.e. a class). Make a class PersonInfo with name, address and phone number as its
attributes.
Write a parameterized constructor for this class.
Write print method in Person class that displays one person record on a message dialog box.
}
}
} // end class
The addperson method first takes input for name, address and phone number and than construct a
PersonInfo
object by using the recently taken input values. Then the newly constructed object is added to the arraylist –
persons.
The searchPerson & deletePerson methods are using the same methodology i.e. first they search the
required record
by name and than prints his/her detail or delete the record permanently from the ArrayList.
Both the methods are taking string argument, by using this they can perform their search or delete operation.
We used for loop for iterating the whole ArrayList. By using the size method of ArrayList, we can control our
loop as ArrayList indexes range starts from 0 to one less than size.
Notice that, inside loop we retrieve each PersonInfo object by using down casting operation. After that we
compare each PersonInfo object’s name by the one passed to these methods using equal method since Strings
are always being compared using equal method.
Inside if block of searchPerson, print method is called using PersonInfo object that will display person
information
on GUI. On the other hand, inside if block of deletePerson method, remove method of ArrayList class is
called that is used to delete record from persons i.e. ArrayList.
Step3 – Make Test class (driver program)
This class will contain a main method and an object of AddressBook class.
Build GUI based menu by using switch selection structure
Call appropriate methods of AddressBook class
The code for Test class is
import javax.swing.*;
class Test {
Public static void main (String args[]) {
AddressBook ab = new AddressBook();
String input, s;
int ch;
while (true) {
input = JOptionPane.showInputDialog(“Enter 1 to add ” +
“\n Enter 2 to Search \n Enter 3 to Delete“ +
“\n Enter 4 to Exit”);
ch = Integer.parseInt(input);
switch (ch) {
case 1:
ab.addPerson();
break;
case 2:
s = JOptionPane.showInputDialog(
“Enter name to search ”);
ab.searchPerson(s);
break;
case 3:
s = JOptionPane.showInputDialog(
“Enter name to delete ”);
ab.deletePerson(s);
break;
case 4:
System.exit(0);
}
}//end while
}//end main
}
Note that we use infinite while loop that would never end or stop given that our program should only exit
when
user enters 4 i.e. exit option.
Compile & Execute
Compile all three classes and run Test class. Bravo, you successfully completed the all basic three steps.
Enjoy!ʄ.