Section 4 Java Programming Lab: Structure Page No
Section 4 Java Programming Lab: Structure Page No
4.0 INTRODUCTION
Only at the age of ten, Java became master of programming languages. Its interesting
success has made Java the fastest growing programming language ever. It is a
bouquet of different programming flowers, having peculiar smells, merging the
beauty of all programming languages. You must work with this language to enrich
your skill set and to become an expert programmer.
In this section, a brief introduction to Java is given to understand the strength of the
language you are going to work with. However, if you want to know something in
detail you can always see the corresponding course (MCS-024). We have already
explained the solution of some obvious problems that you may encounter in the first
session while compiling and interpreting your first java program. We have also
explained the compilation and interpretation of example programs using of freely
available software called editplus.
In the end, session wise problems are defined. These problems you should complete
properly before moving to another session. During this section you should learn how
to design and develop good quality of Java applications/ applets rather than simple
scribbling of code.
To successfully complete this section, the learner should adhere to the following:
• Before attending the lab session, the learner must have already written
algorithms and programs in his/her lab record. This activity should be treated as
home work that is to be done before attending the lab session.
• The learner must have already thoroughly studied the corresponding units of
the course material (MCS-024) before attempting to write algorithms and
programs for the programming problems given in a particular lab session.
• Ensure that you include comments in your program. This is a practice which
will enable others to understand your program and enable you to understand the
program written by you after a long time.
• Ensure that the lab record includes algorithms, programs, I/O and complexity
(both time and space) of each program.
4.1 OBJECTIVES
After going through this lab section you will be able to:
44
Java Programming
Lab
• solving problems using Inheritance and Polymorphism;
• create your own package and interface;
• handling exceptions arising in programs;
• use of multithreading in programs;
• work on strings;
• use GUI components in your programs;
• implement Sockets; and
• connect databases with your programs.
Platform Independent: Java programs can run on any machine and operating system
that support Java Virtual Machine as we are showing in Figure 1 where we have
shown that a program after compiling converts into a byte code which is able to
execute on any platform Windows/Linux/Macintosh.
Secure: The design of Java has multiple layers of security which ensure proper
access to private data and control over access to disk files.
You will cover major topics of Java Programming in this lab section during problem
solving including programming structures, methods objects, inheritance, exception
handling, multithreading, AWT, I/O, and applets. Because you know C programming
language, it will be easier for you to learn Java programming. It is very important to
keep in mind the object-oriented features during problem solving.
Java is also known as a Modern high-level language due to its characteristics: Simple,
Architecture neutral, Object oriented, Portable, Distributed, High performance,
Interpreted, Multithreaded, Robust, Dynamic, and Secure. The Java programming
language is unusual in the sense that a Java program is both compiled and interpreted
as shown in Figure 1.
45
Lab Manual
Compiler
BYTECODE
Windows
Mac
Linux
Now let us see how you will run your Java programs…
PATH Setting
If PATH setting is not proper then whenever you try to compile any program on your
DOS prompt as shown in Figure 2, it does not compile your TestProg program.
46
Java Programming
Lab
Type path at your DOS prompt as demonstrated in Figure 3, you will get a PATH
statement like
PATH=C:WINNT\...;C:\ProgramFiles\.....
Here the dots represent all kinds of directory names. This is a list of all the places
DOS looks when it is trying to find out what a particular command means. If your
JDK directory is not on this list, your DOS won’t understand the JDK’s commands.
So you need to add it to the list. You can do this by typing.
set path=c:\jdkwhateverItIs\bin;%path%
Whatever is the version of JDK, the above command adds your JDK directory to the
rest of the existing path. If you have put your JDK directory somewhere else, alter the
directory name in the command above appropriately to match the actual location. If
there is any spaces in the command above (except between set and path), path will
not be set properly. Now try to run the Java commands again.
If it still doesn’t work, move your *.java files into the JDK directory and you should
be able to work there (or in the bin subdirectory of the JDK directory).
Here is the problem again because you’ll need to reset your path every time you turn
your machine back on and want to work on the Java programs again. But there is a
way to fix it permanently. You need to alter (edit) your autoexec.bat file, which is in
your main C:\directory. It is suggested to copy this file first to a back up version,
then do the required modifications as told here.
C:\copy autoexec.bat autoexecBACK.bat
This is the file that has all the important settings for making your PC run the way you
want it. One of the settings it makes is the PATH.
Now edit the autoexec.bat file and find the line that sets the path. Add your version
of the "set path=C:/jdk.2...." command (the one you used earlier) after the line that
sets the rest of the path in the autoexec.bat file. Now save the file. Then the next
time you open a DOS window (it maybe required to restart your machine), the PATH
should be set correctly. If you made an error in editing autoexec.bat, things might
not work quite right now. In this case, just copy your back up version of
autoexecBACK.bat back into autoexec.bat and try the whole process again.
CLASSPATH Setting
You may also need to set the CLASSPATH variable, which contains all of the
directories on your machine where the Java compiler and the Java run-time
environment are to search for any files it needs, e.g., if you compile or run the Java
47
Lab Manual
class TestProg.java, the compiler needs to know that directory. Your autoexec.bat
file or control settings also determine where the javac compiler looks for the Java
code files. For example, if you are writing your code in the directory
c:\jdk1.2\naveen, you would add the following line to your autoexec.bat file:
CLASSPATH: c:\jdk1.2\naveen
You can list (separated by ;) as many directories as possible in your classpath. One
important thing about "." is that it means that javac will always look in the current
directory for the files it needs. For example, to list the current directory, the naveen
directory, and the diskette drive as places where javac should look, you would have
the following classpath:
CLASSPATH: .;c:\jdk1.2\naveen;a:\
This environmental variable can be set the same way as the PATH above. But there
is one shortcut to avoid the CLASSPATH setting. The javac or Java command has an
option that is (classpath option) that allows you to manually configure the classpath
during compilation/execution. For example, to specify that the compiler must look in
the current directory (that is, the "." directory) for the file TestProg.java when
compiling it, you would use the command:
javac -classpath . TestProg.java
This is all you have to do for setting PATH and CLASSPATH. Now you can compile
and run your applications and applets without any problem of PATH and
CLASSPATH. PATH and CLASSPATH setting need to be done only if you are
willing to run programs on DOS prompt. If you write Java programs in some specific
editors like EditPlus, JBbuilderfor etc. then these settings discussed above are editor
dependent.
Now we will learn how EditPlus can be set for Java Programming. EditPlus is
distributed as Shareware. You can freely download and try it for 30 days from
http://www.editplus.com/download.html.
1. Open EditPlus and you will see the window similar to the Figure 4.
2. Select Tools–>Configure User Tools .You will find a dialog Window in which
you have to select a Group Name.
3. Select Group1 as Group Name you can select any.
4. Click on Add Tool >> button and select Program.
48
Java Programming
Lab
11. In front of Menu text: write Run (as shown in Figure 6 given below)
12. In front of Command: browse and select C:\jdk1.3.0_01\bin\java.exe or the
Directory where java.exe file is located.
13. In front of Argument: select $(FileNameNoExt)
14. In front of Initial directory: Leave black
15. Select Capture output box.
16. Select Save open files box.
49
Lab Manual
Now you will find that three more items Compile, Run, and AppletViewer are added
to the Tools menu of EditPlus. For Compile ctrl+1, for Run ctrl+2, and for
AppletViewer ctrl+3 can be used.
EditPlus is set to be used for Java Programming. Let us take one application and one
applet Program running using EditPlus.
50
Java Programming
Lab
1. Write your program Welcome_Application.java in EditPlus as demonstrated in
Figure 8.
2. Compile using ctrl+1 button
3. Run using ctrl+2 button
51
Lab Manual
Exercise 3: Write a program in Java to explain the use of break and continue
statements.
Exercise 4: Write a program in Java to find the average of marks you obtained in
your 10+2 class.
Exercise1: Write a program in Java to find A×B where A is a matrix of 3×3 and B is
a matrix of 3×4. Take the values in matrixes A and B from the user.
Exercise 2: Write a program in Java to compute the sum of the digits of a given
integer. Remember, your integer should not be less than the five digits. (e.g., if input
is 23451 then sum of the digits of 23451will be 15)
52
Java Programming
Lab
color both are the same for the objects then display “Matching Rectangles”,
otherwise display “Non matching Rectangle”.
Exercise 2: Create a class Account with two overloaded constructors. The first
constructor is used for initializing, the name of account holder, the account number
and the initial amount in the account. The second constructor is used for initializing
the name of the account holder, the account number, the addresses, the type of
account and the current balance. The Account class is having methods Deposit (),
Withdraw (), and Get_Balance(). Make the necessary assumption for data members
and return types of the methods. Create objects of Account class and use them.
Exercise 3: Write a program in Java to create a stack class of variable size with
push() and pop () methods. Create two objects of stack with 10 data items in both.
Compare the top elements of both stack and print the comparison result.
Exercise 2: Write a program in Java to create a Player class. Inherit the classes
Cricket _Player, Football _Player and Hockey_ Player from Player class.
Exercise 4: Consider the trunk calls of a telephone exchange. A trunk call can be
ordinary, urgent or lightning. The charges depend on the duration and the type of the
call. Writ a program using the concept of polymorphism in Java to calculate the
charges.
Exercise 3: Create an Interface having two methods division and modules. Create a
class, which overrides these methods.
Exercise 4: Write a program in Java which implements interface Student which has
two methods Display_Grade and Atrendance for PG_Students and UG_Students
(PG_Students and UG_Students are two different classes for Post Graduate and
Under Graduate students respectively).
53
Lab Manual
Exercise 2: Write a Java program to enable the user to handle any chance of divide
by zero exception.
Exercise 4: On a single track two vehicles are running. As vehicles are going in same
direction there is no problem. If the vehicles are running in different direction there is
a chance of collision. To avoid collisions write a Java program using exception
handling. You are free to make necessary assumptions.
Session 7: Multithreading
Exercise 1: Write a Java program to create five threads with different priorities. Send
two threads of the highest priority to sleep state. Check the aliveness of the threads
and mark which thread is long lasting.
Exercise 3: Write a program for generating 2 threads, one for printing even numbers
and the other for printing odd numbers.
Exercise 2: Write a program in Java for String handling which performs the
following:
i) Checks the capacity of StringBuffer objects.
ii) Reverses the contents of a string given on console and converts the resultant
string in upper case.
iii) Reads a string from console and appends it to the resultant string of ii.
Exercise 3: Write a program for searching strings for the first occurrence of a
character or substring and for the last occurrence of a character or substring.
Exercise 4: Write a program in Java to read a statement from console, convert it into
upper case and again print on console.
Exercise 5: Write a program in Java, which takes the name of a file from user, read
the contents of the file and display it on the console.
54
Java Programming
Lab
Exercise 3: Create an applet which will display the calendar of a given date.
Exercise 5: Write a Java Applet program, which provides a text area with horizontal
and vertical scrollbars. Type some lines of text in the text area and use scrollbars for
movements in the text area. Read a word in a text field and find whether the word is
in the content of the text area or not.
Exercise 2: Create an applet which takes name and age as parameters and display the
message “<name> is <age> year old.”. Print the URL of the class file.
4.6 SUMMARY
In the beginning of the section we aimed to provide you a first step assistance to Java
programming. In this section, we discussed the basics and importance of working
with Java. Though some of these topics you have already studied in your course
material of MCS-024, working on something and simply studying have many
differences. In the beginning of this section we laid emphasis on the most
fundamental concepts and mechanisms provided by Java language. How you will
start working on Java (starting from downloading jdk) this section provided you
interactive guidance so you can start working on Java. We showed you how you can
start compiling and executing your program using freely downloadable software
known as editplus or DOS with the help of a suitable example. More stress has been
laid on the compiling and executing of the first program and related troubleshooting.
This enables better utilization of lab hours and learners will feel motivated to work
with software without getting trapped in the problem (at least not in the beginning).
Further, in this section the learner had ten sessions including programming problems
which s/he should complete in lab. More stress has been laid on programming using
multithreading, strings, inheritance, exception handling and applets as it is regarded
as a very special skill. It is very important to attend the lab sessions after doing the
necessary homework.
You must have completed all your lab sessions successfully. You should take
printouts of all your lab exercises with the output of program. (It is better to make a
file for all your lab exercises.) If you had executed programs successfully in lab
without sufficient preparation, as indicated in the beginning, then it is very important
to assess the efficiency (space and time complexities) of the program.
55
Lab Manual
Books on Java
1. Java: An Introduction to Computer Science and Programming by Walter
Savitch.
2. Problem Solving with Java by Elliot B. Koffman and Ursula Wolz.
3. Introduction to Programming Using Java: An Object-Oriented Approach by
David M. Arnow and Gerald Weiss.
4. David M. Arnow and Gerald Weiss, Introduction to Programming Using Java:
An Object-Oriented Approach, Addison-Wesley.
5. Ken Arnold, James Gosling, and David Holmes, The Java Programming
Language (Third Edition), Addison-Wesley.
6. Judith Bishop, Java Gently: Programming Principles Explained (Third Edition),
Addison-Wesley.
Tutorials on web
http://java.sun.com/docs/books/tutorial/index.html
http://www.ibiblio.org/javafaq/javatutorial.html
http://herzberg.ca.sandia.gov/JavaCourse/
http://www.sunncity.com/Tutorial_Java/partOne/start.html
http://scitec.uwichill.edu.bb/cmp/online/CS24L/java/jdkintro.htm
56