MCSL 025 Section 4 Java Programming Lab
MCSL 025 Section 4 Java Programming Lab
Page No.
44 44 45 46 51 52 55 56
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 compile and interpret Java programs in DOS and editplus;. writes Java programs using sequential, conditional and iterative statements; handle arrays of fixed and variable size; creating classes and objects using Java; implementing constructors and constructor overloading;
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.
45
Lab Manual
Compiler
BYTECODE
Windows
Linux
Mac
Now let us see how you will run your Java programs
Instead it gives you some strange message about a Bad Command. Whats wrong? Can you guess? You must be thinking that you did not install JDK correctly in your system but this is not correct answer. The machine says Bad command because it recognizes the commands javac or java. So you simply need to tell DOS that these commands live in Javas JDK directory and whenever it doesnt recognise a command like javac, it should also check the Javas JDK directory for a possible interpretation of this command. This problem can be solved in two ways, one by using DOS prompt, and another by using My Computer on your window screen. 46
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 wont understand the JDKs 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 doesnt 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 youll 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 In XP/2000/ME machines PATH and CLASSPATH can be set using My Computer. The process is given as follows: 1. 2. 3. 4. Right click on "My Computer" and Click on Properties. Click on the Advanced tab. Click on the "Environment Variables" button near the bottom. A dialog box comes up with two boxes: In the bottom box, look for "Path" and highlight that line. Then click on "Edit" .A small dialog box appears. In the second text field for the value, at the END of the line, add a semicolon then the path to where your java.exe file is. For example path is like:C:\jdk1.3.\bin Click "OK." Now, in the top box, click on the "New" button. In the first field, enter "classpath" as one word. For the value in the second field, enter a single period.
5. 6. 7.
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. Setting for Compilation of Java Programs 5. In front of Menu text: write Compile
48
6. 7. 8. 9. 10.
In front of Command: browse and select C:\jdk1.3.0_01\bin\javac.exe or the directory where javac.exe file is located. (As shown in Figure 5) In front of Argument: select $(FileName) In front of Initial directory: select $(FileDir) Select Capture output box. Select Save open files box.
11.
12. 13. 14. 15. 16.
In front of Menu text: write Run (as shown in Figure 6 given below) In front of Command: browse and select C:\jdk1.3.0_01\bin\java.exe or the Directory where java.exe file is located. In front of Argument: select $(FileNameNoExt) In front of Initial directory: Leave black Select Capture output box. Select Save open files box.
49
Lab Manual
Setting for running Java Applet Programs 17. 18. 19. 20. 22. In front of Menu text: write AppletViewer (as shown in Figure 7 given below) In front of Command: browse and select C:\jdk1.3.0_01\bin\appletviewer.exe or the Directory where appletviewer.exe file is located. In front of Argument: select $(FileName) In front of Initial directory: Leave black Select Save open files box.
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
1. 2. 3.
Write your program Welcome_Application.java in EditPlus as demonstrated in Figure 8. Compile using ctrl+1 button Run using ctrl+2 button
In case of Applet first you write applet as shown in Figure 9. 1. 2. Compile using ctrl+1 button similar to the previous way. Run it using ctrl+3 button as shown in Figure 10 but take care you are applying ctr+3 on appropriate HTML file or not.
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. Session 2: Statements and array Exercise1: Write a program in Java to find AB where A is a matrix of 33 and B is a matrix of 34. 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) Session 3: Class and Objects Exercise 1: Write a program in Java with class Rectangle with the data fields width, length, area and colour. The length, width and area are of double type and colour is of string type .The methods are set_ length () , set_width (), set_ colour(), and find_ area (). Create two object of Rectangle and compare their area and colour. If area and 52
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. Session 4: Inheritance and polymorphism Exercise 1: Write a Java program to show that private member of a super class cannot be accessed from derived classes. 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 3: Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay of every worker. A Daily Worker is paid on the basis of the number of days s/he works. The Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program to calculate the pay of workers. You are expected to use the concept of polymorphism to write this program. 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. Session 5: Package and Interface Exercise 1: Write a program to make a package Balance in which has Account class with Display_Balance method in it. Import Balance package in another program to access Display_Balance method of Account class. Exercise 2: Write a program in Java to show the usefulness of Interfaces as a place to keep constant value of the program. 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). Session 6: Exception Handling Exercise 1: Write a program in Java to display the names and roll numbers of students. Initialize respective array variables for 10 students. Handle ArrayIndexOutOfBoundsExeption, so that any such problem doesnt cause illegal termination of program.
53
Lab Manual
Exercise 2: Write a Java program to enable the user to handle any chance of divide by zero exception. Exercise 3: Create an exception class, which throws an exception if operand is nonnumeric in calculating modules. (Use command line arguments). 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 2: Write a program to launch 10 threads. Each thread increments a counter variable. Run the program with synchronization. Exercise 3: Write a program for generating 2 threads, one for printing even numbers and the other for printing odd numbers. Exercise 4: Write a Java program using thread synchronization in multithreading (You can take some objects visible on screen for real time effect). Session 8: Reading, Writing and String handling in Java Exercise 1: Writ a program in Java to create a String object. Initialize this object with your name. Find the length of your name using the appropriate String method. Find whether the character a is in your name or not; if yes find the number of times a appears in your name. Print locations of occurrences of a .Try the same for different String objects. Exercise 2: Write a program in Java for String handling which performs the following: i) ii) iii) Checks the capacity of StringBuffer objects. Reverses the contents of a string given on console and converts the resultant string in upper case. 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. Exercise 6: Write a Java program to copy a file into another file. Session 9: Applets and its applications Exercise 1: Write a Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good. Exercise 2: Create an applet which displays a rectangle/string with specified colour & coordinate passed as parameter from the HTML file. 54
Exercise 3: Create an applet which will display the calendar of a given date. Exercise 4: Write a program to store students detail using Card Layout. 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. Session 10: Networking and other advanced feature and JAVA Exercise 1: Write a Java program to find the numeric address of the following web sites i. ii. iii. iv. www.ignou.ac.in www.indiatimes.com www.rediff.com www.apple.com
In addition to this, find the Internet Address of your local host. 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. Exercise 3: Write a program to test Socket functionality for appropriate hostname and port number. Exercise 4: Write a Java program to connect to a database created in MSACCESS/SQLSERVER/ORACLE using JDBC concept. Perform basic operations of Selection, Insertion and Deletion on the database.
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
56