Lab-Java Programming Intro I
Lab-Java Programming Intro I
Lab-Java Programming Intro I
Lab exercises:
❍ Exercise 3.2: Write, compile, and run Hello Java program using NetBeans (15 minutes)
❍ Exercise 4.2: Declaring, initializing, printing variables using NetBeans (15 minutes)
❍ Exercise 4.4: Building and running AverageNumber sample program (15 minutes)
❍ Exercise 4.5: Building and running GreatestValue sample program (20 minutes)
❍ Exercise 5.2: Building and running LastThreeWorlds sample programming (20 minutes)
❍ Exercise 5.3: Getting input from keyboard via JOptionPane class (20 minutes)
Please download and install the following set of software. If you have any questions on installation, please feel free to send them to the email alias mentioned
below.
■ As a default, it will install the JDK 5.0 under C:\Program Files\Java\jdk1.5.0_06. This is the directory you want to set your %JAVA_HOME%
environment variable.
❍ For Solaris X86, select "Solaris x86 self-extracting file"
❍ For Mac OS X, please go to "Java for Mac OS X" page and select download J2SE 5.0.
● Download and install NetBeans IDE 5.0 RC 1 (Release Candidate 1) - some of the initial exercises in this lab are done at the command line (so that you get
exposed to what is going on underneath) while others are done with NetBeans IDE.
❍ After choosing an Operating System and Localization Language, click next button
❍ NetBeans IDE 5.0 final release will be released at the end of Jan. of 2006. You are welcome to use NetBeans IDE Beta 2 for the rest of the course
❍ For text editor, you can use any text editor of your choice including the ones mentioned below.
■ JEdit
■ If you downloaded Java-based installer (jedit42install.jar), just double-click the file to start the installation. Or you can just type it at the
■ C:\>jedit42install.jar
As a default, it will install it under C:\Program Files\jEdit 4.2 directory (under Windows). Have directory in your path so that you can
■
● Download NetBeansFiles.zip if you are using NetBeans 5.0 beta or RC1, NetBeansFiles41.zip if you are using NetBeans 4.1 or Sun Java Studio Enterprise
8.
❍ This file contains various sample applications that are ready to be built as NetBeans projects.
❍ In order to build and run, you will open a NetBeans project of each sample application. The detailed instruction on how to do this will be explained
later.
● Unzip it in a directory of your choice, like c:\ in this example, either using unzip utility like WinZip under Windows platform or using "jar" utility that comes with
J2SE SDK as shown below.
❍ C:\>jar xvf NetBeansFiles.zip (or java xvf NetBeansFiles41.zip)
● Each exercise below will contain Homework and How to submit homework sections.
■ /usr/jdk/jdk1.5.0_06 (Solaris/Linux)
■ Trouble-shooting: Instead of seeing the value of %JAVA_HOME% or $JAVA_HOME environment variable as shown above, if you see the following,
it means the environment variable has not been set. (Also under Windows, you have to open a new terminal window to see the change, The existing
terminal windows do not see the change.) Please set the environment variable following the appropriate instruction of your operating system or open
a new terminal window and try it again if you are running Windows and you have set the environment variable through control panel.
■ %JAVA_HOME%
❍ Make sure the installation has placed %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Solaris/Linux) in the "path" environment variable.
■ After you set the environment variable, type "java -version" in a terminal window. (By terminal window, I mean DOS window for Windows platform.)
■ Once there, click on "Environmental Variables" at the bottom of the window. Look in the part that says "System Variables" and find
the "Path" variable.
■ Select it and click edit, and append your java bin directory ("%JAVA_HOME%\bin") to the path. Then click "ok".
■ You have to open a new terminal window to have this path to take effect.
● Download and unzip NetBeans Lab Project Files as described in the NetBeans Lab Project Files above.
❍ Once you unzipped NetBeans Lab Project Files, it should create NetBeansFiles directory.
Exercise 3.1: Write, Compile, and Run Hello Java Program (20 minutes)
Introduction:
The goal of this exercise is to let you experience a complete development cycle - writing, compiling, and running a simplest possible Java program - using
command line tools. If you have done any programming in the past using different programming languages such as C or C++, this is not that much different from it.
(There is a slight difference, however. In Java, the compiler javac compiles the Java source code into what is called bytecode which can be run on any Java
compliant platform, thus provides the portability of the Java programs. The bytecode is the same thing as Java class file, which is represented by *.class file
notation.)
You will also get some exposure to the concept of the classpath. The classpath is the most basic but essential concept you will need to understand - it is basically
a location where *.class files reside. If the classpath is not set up correctly, you will experience the infamous "java.lang.NoClassDefFoundError: <name of the class
file>" exception.
Steps to follow:
1. mkdir c:\myjavaprograms (to create a directory of your choice - this is the directory where you are going to write Java programs)
2. cd \myjavaprograms (this directory becomes the current directory)
3. Write Hello.java using your editor of choice (in this example, I am using jedit) as shown in Code-3.1-a below. You can cut and paste the code from the Code-
3.1-a but I encourage you to write the code line by line yourself manually just to experience some compile errors.
● jedit Hello.java
/**
* My first Java program
*/
public static void main( String[] args ){
}
Code-3.1-a: Hello.java
4. Compile Hello.java using javac compiler. The javac compiler comes with J2SE SDK you've download. It resides in %JAVA_HOME%\bin (Windows) or
$JAVA_HOME/bin (Solaris/Linux) directory. The result of compilation will be the creation of Hello.class file.
● javac Hello.java
Trouble-shooting 4.1: If you experience the following error condition, it means the %JAVA_HOME%\bin for Windows platform or $JAVA_HOME/bin for Solaris/Linux
platform is not set in your path. You can try C:\Program Files\Java\jdk1.5.0_06\bin\javac Hello.java (for Windows) if you want to proceed without setting the
path.
● C:\myjavaprograms>javac Hello.java
'javac' is not recognized as an internal or external command,
operable program or batch file.
Trouble-shooting 4.2: If your Hello.java program contains a problem such as a typo or missing semi-colon after each statement, you will experience compile errors
like an example compile error below (I misspelled it - it should have been System.out.println("Hello world"); instead of Syste.out.println("Hello world");.
● C:\myjavaprograms>javac Hello.java
Hello.java:9: package Syste does not exist
Syste.out.println("Hello world");
^
1 error
Experimentation 4.3: Try "javac -verbose Hello.java" to see what is happening when you run javac. You really don't need to understand what is happening
underneath at this point, however, except that it reads Hello.java file and then created Hello.class at the end.
Experimentation 4.4: Try "javac -help" to see what options you can specify when you compile Java code using javac compiler. You don't need to understand every
option right now but the important options are "-classpath <path>", "-cp <path>", "-sourcepath <path>", "-d <directory>". Please feel free to play around with these
options. Among these four, "-classpath <path>", "-cp <path>" are more important to understand. By the way, "-classpath <path>", "-cp <path>" are the same thing.
● C:\myjavaprograms>javac -help
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
-g:{lines,vars,source} Generate only some debugging info
-nowarn Generate no warnings
-verbose Output messages about what the compiler is doing
-deprecation Output source locations where deprecated APIs are used
-classpath <path> Specify where to find user class files
-cp <path> Specify where to find user class files
-sourcepath <path> Specify where to find input source files
-bootclasspath <path> Override location of bootstrap class files
-extdirs <dirs> Override location of installed extensions
-endorseddirs <dirs> Override location of endorsed standards path
-d <directory> Specify where to place generated class files
-encoding <encoding> Specify character encoding used by source files
-source <release> Provide source compatibility with specified release
5. Make sure Hello.class file has been created. The Hello.class file contains bytecode representation of the Hello class.
● dir Hello.class
6. Run the Hello program using java command. The java command starts the Java Virtual Machine and runs the Hello program in this example. A Java program
can be made of multiple Java classes and and a set of libraries. In this example, the Hello program just contains a single class called Hello.class. You can regard
http://www.javapassion.com/javaintro1/javabasics1/ (6 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● java Hello
● C:\myjavaprograms>java Hello
Hello world
or
● C:\myjavaprograms>java Hello
Exception in thread "main" java.lang.NoClassDefFoundError: Hello
Trouble-shooting 6.1: If you experience the "Exception in thread "main" java.lang.NoClassDefFoundError: Hello" exception as shown above, it is highly likely
because you are using predefined or wrong (at least for running this program) CLASSPATH environment variable. You can find out whether CLASSPATH
environment variable is set or not as following - in the example below, the CLASSPATH is set to C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip, which is a
collection of many built-in Java classes. (You can type jar tvf "C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip" at the command line to see what Java
classes make up the zip file.)
● C:\myjavaprograms>set CLASSPATH
CLASSPATH=C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip
The "Exception in thread "main" java.lang.NoClassDefFoundError: Hello" means that the Java interpreter, java, could not find the Hello.class file in the
classpath. (Please be warned this will be the most frequently encountered error condition you will be experiencing the first time you learn Java programming using
command line tools such as javac and java. The NetBeans IDE handles all this for you.)
One way to solve the problem is unsetting the CLASSPATH environment variable for now as described below and run the Hello program again as following. (In
this case, the classpath is the current directory which contains the Hello.class file. I will explain how Java interpreter finds which classpath to use shortly.)
● C:\myjavaprograms>java Hello
Exception in thread "main" java.lang.NoClassDefFoundError: Hello
● C:\myjavaprograms>set CLASSPATH=
● C:\myjavaprograms>set CLASSPATH
Environment variable CLASSPATH not defined
● C:\myjavaprograms>java Hello
Hello world
Experimentation 6.2: You can also explicitly specify the classpath by using -classpath and -cp option. Try "java -classpath . Hello" and "java -cp . Hello" as
shown below. (There is a dot . between -classpath and Hello and -cp and Hello.) It should work as following. What you did is basically specifying that the current
directory, which is represented by the dot ., is the classpath you want to use.
Experimentation 6.3: Try to set the classpath with full directory path, C:\myjavaprograms in this example. It should work as well.
Important 6.4: The "-classpath <path>" or "-cp <path>" option specifies the location where the class files (in this example, we have only a single class file called
Hello.class) reside. When you don't specify the classpath option, the Java interpreter tries to find the class files in the directories specified in the CLASSPATH
environment variables or in a current directory. In fact, the Java interpreter tries to find the class files in the following order.
Online resource: For more detailed description on classpath, please see "Setting the class path" from java.sun.com.
Experimentation 6.5: Try "java -classpath .. Hello" to see if it still works. (Instead of single dot ., you specify double dots .. between -classpath and Hello. The
double dot .. specifies a parent directory, C:\ in this example while single dot . specifies the current directory, c:\myjavaprograms in this example.) It should fail as
following. It is because you set the classpath to a parent directory, C:\, which does not contain Hello.class file.
● C:\myjavaprograms>java -classpath .. Hello (this should fail because you are the parent directory C:\ as classpath here)
Exception in thread "main" java.lang.NoClassDefFoundError: Hello
Now try to copy the Hello.class file to the parent directory and try the above command again. You should see the following result. Try to think why this works.
Important 6.6: As is mentioned above, you can set system wide classpath via CLASSPATH environment variable. This classpath gets applied system-widely
meaning it gets applied to all Java programs running on that platform. Of course, you can override it via -classpath or -cp option when you run a particular program.
Experimentation 6.7: Try to set the environment variable CLASSPATH first to the directory that contains Hello.class file and then run the program as following. It
should work.
● C:\myjavaprograms>set CLASSPATH=c:\myjavaprograms
C:\myjavaprograms>java Hello (since you have not specified -classpath or -cp option, directories specified in the CLASSPATH environment variable are
used as classpath)
Hello world
Experimentation 6.8: Try to set the environment variable CLASSPATH to a bogus directory and then run the program as following:
● C:\myjavaprograms>set CLASSPATH=c:\tmp (set the CLASSPATH environment variable to a bogus directory, c:\tmp)
C:\myjavaprograms>java Hello (should fail since the c:\tmp directory does not contain Hello.class file)
Exception in thread "main" java.lang.NoClassDefFoundError: Hello
C:\myjavaprograms>java -cp . Hello (now you are overriding the CLASSPATH with your own classpath)
Hello world
Experimentation 6.9: Try to set the environment variable CLASSPATH to a set of directories and then run the program as following:
● C:\myjavaprograms>set CLASSPATH=c:\tmp;c:\myjavaprograms
C:\myjavaprograms>java Hello
Hello world
Important 6.10: As you've seen above, you can set the environment variable CLASSPATH to a set of directories. For Windows, you use semi-colon ; while on
Solaris/Linux platform, you use colon : as a delimiter. You can also specify multiple directories when you specify -classpath or -cp option as following:
● C:\myjavaprograms>java -classpath c:\tmp Hello (this should fail since c:\tmp does not contain Hello.class file)
Exception in thread "main" java.lang.NoClassDefFoundError: Hello
C:\myjavaprograms>java -classpath c:\tmp;c:\myjavaprograms Hello (the classpath is set to two directories c:\tmp and c:\myjavaprograms - they will be
searched in sequence)
Hello world
C:\myjavaprograms>java -classpath c:\tmp;. Hello
Hello world
Homework:
1. Modify, compile, and run the Hello program so that it prints the following
2. Please play around with the classpath settings with -classpath or -cp option and CLASSPATH environment variable.
1. Email modified Hello.java file as an attachment to [email protected] with subject line as HWExercise3.1. (Please make sure you use the correct
subject line.) No need to make it a zip file.
Exercise 3.2: Write, Compile, and Run Hello Java Program using NetBeans (15 minutes)
Introduction
In this exercise, you are going to build the same application you built in Exercise 3.1 using NetBeans IDE. You are going to use the built-in editor, compiler, and
JVM.
Steps to follow:
● Windows: Start > All Programs > NetBeans 5.0 Beta > NetBeans IDE or click NetBeans IDE desktop icon
● Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
2. Create a new NetBeans project and Hello main class. By main class, I mean a class that contains the main(..) method.
❍ Select File from the menu bar and select New Project.
❍ Under Choose Project pane, select General under Categories: and Java Application under Projects: (Figure-3.2-a below)
❍ Click Next.
❍ Under Name and Location pane, (Figure-3.2-b below)
■ For Project Name field, fill it with Hello.
■ For Create Main Class field, change it to hello.Hello (from hello.Main). The hello part of the hello.Hello is a package name and Hello part of the
hello.Hello is the class name. In this case, the Hello class belongs to hello package. We are going to learn the concept of package later on but for
now you can think of a package as a container of Java classes.
■ Click Finish.
Figure-3.2-b: Enter project name and create Hello class under hello package
Note that the IDE generated Hello.java code gets displayed in the source editor. Also the Hello.java source code is generated under the hello directory. Under
Java programming environment, the package structure matches the directory structure. (We will learn more on this later on.)
● Replace the code of Hello class of IDE generated Hello.java code in the source editor with the one of Code-11 above while leaving the package statement
at the top of the file. (Figure-3.2-c below)
Figure-3.2-c: Hello.java
● Right click Hello project node and select Run Project from the contextual menu. ((Figure-3.2-d below)
● Note that the Output window displays the result (Figure-3.2-e below)
Homework:
1. Screen-capture of the NetBeans that contains the output. Name the file as HWExercise3.2.gif or HWExercise3.2.jpg.
● Under Windows, you can do the screen capture by taking steps below
❍ Shift+PrtSc - puts the screen image to the clipboard
❍ Use the border selection tool (dashed line box in upper left corner), select the portion of the image you want to keep
❍ File / Save As - pull down "Save As Type" to be GIF or JPG, then save
Introduction:
In this exercise, you are going to learn how to declare, initialize a variable. You also learn how to modify and display a value of a variable.
Steps to follow:
● cd \myjavaprograms
● jedit OutputVariable.java
}
Code-4.1-a: VariableSamples.java
● javac OutputVariable.java
● java -classpath . OutputVariable
● C:\myjavaprograms>java OutputVariable
10
The value of x=A
Homework:
● Print out the value of variable "grade" using the following statement.
❍ System.out.println( "The value of grade =" + grade );
1. Email modified OutputVariable.java file as an attachment to [email protected] with subject line as HWExercise4.1.
Exercise 4.2: Rebuilding the above program using NetBeans (15 minutes)
Introduction:
In this exercise, you are going to rebuild the same application you built in Exercise 4.1 using NetBeans. The steps you need to follow are pretty much the same
ones as in Exercise 3.2.
Steps to follow:
1. Start the NetBeans IDE (if you have not done so yet.)
● Windows: Start > All Programs > NetBeans 5.0 Beta > NetBeans IDE or click NetBeans IDE desktop icon
● Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
● Select File from the menu bar and select New Project.
● Under Choose Project pane, select General under Categories: and Java Application under Projects:
❍ Click Next.
❍ Under Name and Location pane,
■ For Project Name field, fill it with OutputVariable.
■ For Create Main Class field, change it to outputvariable.OutputVariable (from outputvariable.Main). The outputvariable part of the
outputvariable.OutputVariable is a package name and OutputVariable part of the outputvariable.OutputVariable is the class name. In this case,
the OutputVariable class belongs to outputvariable package.
■ Click Finish.
● Replace IDE generated OutputVariable.java code in the source editor with the one of Code-4.1-a above while leaving the package statement at the top of
the file.
● Right click OutputVariable project node and select Run Project from the contextual menu.
● Note that the Output window displays the result
Homework:
1. Screen-capture of the NetBeans that contains the output. Name the file as HWExercise4.2.gif or HWExercise4.2.jpg.
2. Email it to [email protected] with subject line as HWExercise4.2.
In this exercise, you are going to write a Java program which uses conditional operators.
Steps to follow:
● cd \myjavaprograms
● jedit ConditionalOperator.java
//print status
System.out.println( status );
}
}
Code-4.3-a: ConditionalOperator.java
● javac ConditionalOperator.java
● java -classpath . ConditionalOperator
● C:\myjavaprograms>java ConditionalOperator
Passed
Homework:
1. Modify ConditionalOperator.java as adding the following lines of code at the appropriate place, compile and run the code
2. Do the homework both using command line tools and using NetBeans.
1. Modified ConditionalOperator.java and screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise4.3.gif or
HWExercise4.3.jpg.
2. Email the above files as attachments to [email protected] with subject line as HWExercise4.3.
Exercise 4.4: Building and running AverageNumber sample program (15 minutes)
Introduction
In this exercise, you are going to build and run a sample Java program called AverageNumber using NetBeans. The sample program can be built and run as
NetBeans project. So you are going to open an existing NetBeans project rather than creating a new project.
Steps to follow:
● In the Open Project window, browse to C:\NetBeansFiles\Chapter 4\4.2 directory and select AverageNumberProject. (The small bookmark on the
AverageNumberProject file folder indicates that this directory contains NetBeans project meta files and ready to be opened as NetBeans project.)
● Click Open Project Folder button.
● Right click AverageNumber.java node and select Run File (Shift+F6). Since the source file contains the main(..) method, you can do this. You should see
the result in the Output window. (Or you can right click the AverageNumberProject project node and then select Run Project.)
Homework
1. Add another number with the following statement and compute a new average.
Exercise 4.5: Building and running GreatestValue sample program (20 minutes)
Introduction
In this exercise, you are going to build and run a sample Java program called GreatestValue using NetBeans. The sameple program can be built and run as
NetBeans project. So you are going to open an existing NetBeans project rather than creating a new project.
Steps to follow
● Right click GreatestValue.java node and select Run File (Shift+F6). Since the source file contains the main(..) method, you can do this.
Homework
1. Modify GreatestValue.java code so that it displays the greatest number as well as smallest number as well.
http://www.javapassion.com/javaintro1/javabasics1/ (24 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
1. Screen-capture of the NetBeans IDE that contains the output. Name the screen capture file as HWExercise4.5.gif or HWExercise4.5.jpg.
2. Email the above file as attachments to [email protected] with subject line as HWExercise4.5.
Exercise 5.1: Getting Input From Keyboard via BufferedReader (20 minutes)
Introduction:
In this exercise, you are going to build a simple interactive Java application, which gets user entered input data from keyboard. The program will use
BufferedReader class to receive the intput data.
Feel free to use NetBeans to do this work (assuming you are reasonably comfortable using the basic features of NetBeans by now) even though the instruction
below is based on command line.
Steps to follow:
1. Create GetInputFromKeyboard.java using your editor of choice or NetBeans as shown in Code-5.1.a below,
● cd \myjavaprograms
● jedit GetInputFromKeyboard.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
}
Code-5.1.a: GetInputFromKeyboard.java
● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard
You should have the following interaction. In this example, I typed Sang Shin.
3. Modify the GetInputFromKeyboard.java to read Your age as shown in Code 5.1.b below. The code fragment that needs to be added is highlighted in bold font.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
}
http://www.javapassion.com/javaintro1/javabasics1/ (26 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard
● Otherwise
❍ Hello <name>! You are young!
Notice in the previous code, your program received the age in the form of String type. And you cannot compare String type "99" with int type of 100. In other
words, you have to convert the String type of "99" to int type of 99 before you compare it against another int type 100.
Frontally, there is a method called parseInt() in the Integer class for converting String type into int type. Try to see the JavaDoc of Integer class from the
following J2SE 5.0 Javadoc website. (You have t
o scroll down
to see the Integer class in the lower left box.
Click Integer class to display Javadoc information of the class on the right side of the browser. (Figure 5.1.c below)
● http://java.sun.com/j2se/1.5.0/docs/api/
7. Scroll down the Integer class to see the parseInt(String s) method. (Figure 5.1.d below)
8. Click parseInt(String s) method to see the detailed information. (Figure 5.1.e below)
9. Modify the GetInputFromKeyboard.java to read Your age as shown in Code 5.1.c below. The code fragment that needs to be added is highlighted in bold font.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
// Convert the String type of age variable to int primitive type ageint.
int ageint = Integer.parseInt(age);
if (ageint > 100){
System.out.println("Hello " + name +"!" + " " + "You are old.");
}
else{
System.out.println("Hello " + name +"!" + " " + "You are young.");
}
}
http://www.javapassion.com/javaintro1/javabasics1/ (31 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
}
Figure
● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard
Homework:
● Display added value of your age and your mother's age as following:
❍ The added value of your age and your mother's age is <whatever number>!
1. Modified GetInputFromKeyboard.java (if you are doing the work using command line tool) or screen-capture of the NetBeans that contains the output (if you are
using NetBeans). Name the screen capture file as HWExercise5.1.gif or HWExercise5.1.jpg.
2. Email it to [email protected] with subject line as HWExercise5.1.
Exercise 5.2: Building and running LastThreeWords sample program (20 minutes)
http://www.javapassion.com/javaintro1/javabasics1/ (32 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
Introduction:
In this exercise, you are going to build and run a sample Java program called LastThreeWords using NetBeans. The sameple program can be built and run as
NetBeans project. So you are going to open an existing NetBeans project rather than creating a new project.
You will also install Java document zip file of J2SE SDK 5.0 to the NetBeans, which will enable context sensitive display of Javadoc of any standard Java class.
Steps to follow
● Right click LastThreeWords.java node and select Run File (Shift+F6). Since the source file contains the main(..) method, you can do this to run the
program.
● You should see Input field being displayed at the bottom of the IDE. Enter your first name and press Enter key. (Figure 5.2.a below)
● Enter your last name and press Enter key. Enter "Happy" and press Enter key.
● You should see the following result. (Figure 5.2.b below)
4. Install Java document zip file of J2SE SDK 5.0 with NetBeans. Once Java document zip file is installed, you should be able to display Java documentation of
http://www.javapassion.com/javaintro1/javabasics1/ (35 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
Figure 5.2.d: Get ready to add the Java document zip file
● Browse down to the directory where you have downloaded Java document zip file (jdk-1_5_0-doc.zip) as you did above.
● Select jdk-1_5_0-doc.zip.
● Click Add ZIP/Folder button. (Figure 5.2.e below)
● In the Java Platform Manager dialog box, click Close button. (Figire 5.2.f below)
● The Java document of the BufferedReader class will be displayed in the default browser of your platform. (Figure 5.2.h below)
http://www.javapassion.com/javaintro1/javabasics1/ (40 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● Read the description of the BufferedReader class. (I don't expect you to understand everything about BufferedReader class. Just get a sense of how to
read Java document of a class.)
❍ By the way, you can see Javadoc of all classes from online version of J2SE SDK Javadoc as well.
Homework
1. Try to display the Java document of String class in a context sensitive way.
2. Modify the LastThreeWords project above to use a method of String class so that the words that were entered by a user get displayed in all upper case and in
all lower case.
● Hint: You have to find out which method of a String class you will have to use by looking at the Javadoc of String class either from http://java.sun.com/
j2se/1.5.0/docs/api/ or within NetBeans using context sensitive Javadoc.
1. Modified LastThreeWords.java (if you are doing the work using command line tool) or screen-capture of the NetBeans that contains the output (if you are using
NetBeans). Name the screen capture file as HWExercise5.2.gif or HWExercise5.2.jpg.
2. Email it to [email protected] with subject line as HWExercise5.2.
Exercise 5.3: Getting Input From Keyboard via JOptionPane (20 minutes)
Introduction:
In this exercise, you are going to build the same application you built in Exercise 5.1 but this time using JOptionPane class.
Feel free to use NetBeans to do this work (assuming you are reasonably comfortable using the basic features of NetBeans by now) even though the instruction
below is based on command line.
Steps to follow:
● cd \myjavaprograms
● jedit GetInputFromKeyboardJOptionPane.java
import javax.swing.JOptionPane;
● javac GetInputFromKeyboardJOptionPane.java
● java -classpath . GetInputFromKeyboardJOptionPane
❍ Enter your name
Homework:
1. Modified GetInputFromKeyboard.java or screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise5.3.gif or
HWExercise5.3.jpg.
2. Email it to [email protected] with subject line as HWExercise5.3.
Introduction:
In this exercise, you are going to build the same application in which you are going to exercise both for loop or while loop.
Feel free to use NetBeans to do this work (assuming you are reasonably comfortable using the basic features of NetBeans by now) even though the instruction
below is based on command line.
Steps to follow:
● cd \myjavaprograms
● jedit ForLoop.java
if (foundName )
System.out.println(searchName +" is found!");
else
System.out.println(searchName +" is not found.");
}
Code-6.1: ForLoop.java
● javac ForLoop.java
● java -classpath . ForLoop
http://www.javapassion.com/javaintro1/javabasics1/ (44 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● C:\myjavaprograms>java ForLoop
Yza is found!
Homework:
1. Modified ForLoop.java file or screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise6.1.gif or HWExercise6.1.
jpg.
2. Email it to [email protected] with subject line as HWExercise6.1.
Steps to follow:
1. Create ArraySample.java.
● cd \myjavaprograms
● jedit ArraySample.java
}
Code-7.1: ArraySample.java
● javac ArraySample.java
● java -classpath . ArraySample
● C:\myjavaprograms>java ArraySample
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000
Homework:
● Just before the for loop that prints out the value of each entry of the ages[] array, create another for loop in which a value of 100 is assigned to the first entry
of the array, ages[0], 101 to the next entry of the array, ages[1], and so on
1. Modified ArraySample.java file or screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise7.1.gif or
HWExercise7.1.jpg.
2. Email it to [email protected] with subject line as HWExercise7.1.
Steps to follow:
● cd \myjavaprograms
● jedit TestPassByValue.java
int i = 10;
}
Code-19: TestPassByValue.java
● javac TestPassByValue.java
● java -classpath . TestPassByValue
● C:\myjavaprograms>java TestPassByValue
10
10
Steps to follow:
● cd \myjavaprograms
http://www.javapassion.com/javaintro1/javabasics1/ (47 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● jedit TestPassByReference.java
}
public static void test(int[] arr){
// change values of array
for (int i=0; i<arr.length; i++ ){
arr[i] = i + 50;
}
}
}
Code-23: TestPassByReference..java
● javac TestPassByReference.java
● java TestPassByReference
● C:\myjavaprograms>java TestPassByReference
10
11
12
50
51
http://www.javapassion.com/javaintro1/javabasics1/ (48 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
52
Steps to follow:
● cd \myjavaprograms
● jedit EqualsTest.java
class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
str2 = new String(str1);
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
System.out.println("Same value? " + str1.equals(str2));
}
}
Code-24: EqualsTest.java
● javac EqualsTest.java
● java -classpath . EqualsTest
● C:\myjavaprograms>java EqualsTest
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
http://www.javapassion.com/javaintro1/javabasics1/ (49 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
4. Create EqualsTestInteger.java
● jedit EqualsTestInteger.java
class EqualsTestInteger {
public static void main(String[] arguments) {
Integer integer1, integer2;
integer1 = new Integer(5);
integer2 = new Integer(5);
System.out.println("Integer1: " + integer1);
System.out.println("Integer2: " + integer2);
System.out.println("Same object? " + (integer1 == integer2));
integer1 = integer2;
System.out.println("Integer1: " + integer1);
System.out.println("Integer2: " + integer2);
System.out.println("Same object? " + (integer1 == integer2));
System.out.println("Same value? " + integer1.equals(integer2));
}
}
Code-25: EqualsTestInteger.java
● javac EqualsTestInteger.java
● java EqualsTestInteger
Introduction:
● If you are new to Object-Oriented Programming concept, please read "Object Oriented Programming Concept" section of the Java Programming Tutorial.
● If you are new on how to create a class, please see "Creating Class" section of Java Programmng Tutorial.
Steps to follow:
● cd \myjavaprograms
http://www.javapassion.com/javaintro1/javabasics1/ (50 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
● jedit StudentRecord.java
// instance variables
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
// static variables
private static int studentCount = 0;
/**
*Returns the name of the student
*/
public String getName(){
return name;
}
/**
*Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}
/**
*Computes the average of the english,math and science
*grades
*/
public double getAverage(){
double result =0;
result =(mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
*returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}
}
Code-12.1: StudentRecord.java
● cd \myjavaprograms
● jedit StudentRecordExample.java
● C:\myjavaprograms1>java StudentRecordExample
Anna
Count=0
1. Start the NetBeans IDE (if you have not done so yet)
● Windows: Start > All Programs > NetBeans 5.0 > NetBeans IDE or click NetBeans IDE 5.0 desktop icon
● Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
❍ Select File from the menu bar and select New Project.
❍ Under Choose Project, select General and Java Application
❍ Click Next.
❍ Under Name and Location pane, (Figure-10 below)
■ For Project Name field, fill it with StudentRecordExample
■ Click Finish
● Replace the NetBeans generated StudentRecordExample.java code in the source editor with the one of Code-12.2 above while leaving the package
statement on the top.
4. Write StudentRecord.java
● Right click StudentRecordExample project node and select New->Java Class. The New Java Class window appears.
● Under Name and Location pane,
❍ for Class Name field, type StudentRecord
❍ for Package field, choose studentrecordexample from the drop-down menu (or you can type studentrecordexample)
❍ Click Finish
● Replace the NetBeans generated StudentRecord.java code in the source editor with the one of Code-12.1 above while leaving the package statement on
the top.
● Right click StudentRecordExample.java node under Hello->Source Packages->studentrecordexample and select Run File (Shift+F6)
● Note that the Output window displays the result
Steps to follow:
1. Modify StudentRecord.java as following. The code fragement that needs to be added is highlighted with bold and blue-colored font.
...
}
Code-13.1: StudentRecord.java
● cd \myjavaprograms
● jedit StudentRecordExample2.java
annaRecord.setName("Anna");
annaRecord.setEnglishGrade(95.5);
annaRecord.setScienceGrade(100);
//overloaded methods
annaRecord.print(annaRecord.getName());
annaRecord.print(annaRecord.getName(), annaRecord.getAverage());
}
}
Code-13.2: StudentRecordExample2.java
3. Compile and run the code. If you experience compile errors, fix the compile errors.
● Name:Anna
Name:Anna Average Grade:65.16666666666667
It is assumed you are using the same NetBeans project you created in Exercise 12.
● Right studentrecordexample package node (Not StudentRecordExample project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type StudentRecordExamle2
❍ Click Finish
● Replace the code of the NetBeans generated StudentRecordExample2.java with the one of Code-13.2 above while leaving the package statement at the top
4. Right click studentrecordexample package node (Not StudentRecordExample project node) and select Compile Package (F9)
5. Right click StudentRecordExamle2 and select Run File
● Add another print() method which takes the following three parameters
❍ name
❍ grade average
❍ student count
Please do this exercise at the command line instead of using NetBeans. This is to learn the packaging structure without the help of NetBeans.
Introduction:
● If you are new to Packaging concept, please read "Creating and Managing Packages" section of the Java Progamming Tutorial.
Steps to follow:
0. If have used NetBeans to do the exercise 13 above, please create StudentRecord.java and StudenRecordExample.java as following
● cd \myjavaprograms
● jedit StudentRecord.java
// instance variables
private String name;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
// static variables
private static int studentCount = 0;
/**
*Returns the name of the student
*/
public String getName(){
return name;
}
/**
*Changes the name of the student
*/
public void setName(String temp ){
name =temp;
}
/**
*Computes the average of the english,math and science
*grades
*/
public double getAverage(){
double result =0;
result =(mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
*returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}
}
Code-14.1: StudentRecord.java
● jedit StudentRecordExample.java
1. Modify StudentRecord.java as following to add a package statement. The code fragement that needs to be added is highlighted with bold and blue-colored font.
package studentpackage;
...
}
Code-27: StudentRecord.java with package statement
2. Modify StudentRecordExample.java as following to add a package statement. The code fragement that needs to be added is highlighted with bold and blue-
colored font.
package studentpackage;
3. Compile code.
● del StudentRecord.class
● del StudentRecordExample.class
● javac StudentRecord.java StudentRecordExample.java
4. Run the code. You will experience an NoClassDefFoundError exception. Think about why you are getting this exception for a moment. It is because the java
runtime is trying to find StudentRecordExample.class under studentpackage directory. It is because the StudentRecordExample.java now has a package
statement which says the Java class file resides under studentpackage directory.
● C:\myjavaprograms>java StudentRecordExample
Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample
(wrong name: studentpackage/StudentRecordExample)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
5. Create a new directory called strudentpackage and then move StudentRecord.java and StudentRecordExample.java under it.
● mkdir \myjavaprograms\studentpackage
● move \myjavaprograms\StudentRecordExample.java \myjavaprograms\studentpackage\StudentRecordExample.java
● move \myjavaprograms\StudentRecord.java \myjavaprograms\studentpackage\StudentRecord.java
6. Compile code. You will experience compile errors as following. You get this compile error because you are trying to compile the two Java files that are not
present in the current directory anymore.
● del StudentRecord.class
● del StudentRecordExample.class
● C:\myjavaprograms>javac StudentRecord.java StudentRecordExample.java
error: cannot read: StudentRecord.java
1 error
7. Compile the code using a directory structure. The compilation should succeed. Note that the class files are now created under studentpackage directory not in
the current directory
Directory of C:\myjavaprograms\studentpackage
http://www.javapassion.com/javaintro1/javabasics1/ (60 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
8. Run the code as following. You will experience NoClassDefFoundError because it is trying to find the class in the current directory instead of in the
studentpackage directory.
● C:\myjavaprograms>java StudentRecordExample
Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample
9. Run the code with propert package structure. It should work this time.
● C:\myjavaprograms>java studentpackage.StudentRecordExample
Anna
Count=0
10. Now you thught you should be able to run the application under the studentpackage directory itself so you go into the directory and run the code. And the
following is what you will experience. It is because it is still looking for studentpackage/StudentRecordExample.class in the currently directory and it could not find it.
● C:\myjavaprograms>cd studentpackage
C:\myjavaprograms\studentpackage>java StudentRecordExample
Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample
(wrong name: studentpackage/StudentRecordExample)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
11. Now there is a way you can specify the classpath using -classpath command line option as following:
Introduction:
● If you are new to Inheritance, please read "Managing Inheritance" section of Java Programming Tutorial.
Steps to follow:
1. Write Person.java
● cd \myjavaprograms
● mkdir personpackage
● jedit personpackage\Person.java
package personpackage;
public Person(){
System.out.println("Inside Person:Constructor");
}
2. Write Student.java
● cd \myjavaprograms
● jedit personpackage\Student.java
package personpackage;
public Student(){
System.out.println("Inside Student:
Constructor");
}
3. Write Main.java
● cd \myjavaprograms
● jedit personpackage\Main.java
package personpackage;
}
Code-15.3: Main.java
● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main
● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor
Inside Student:Constructor
6. Modify the Student.java as following. The code fragment that needs to be added is highlighted in bold and blue-colored font.
package personpackage;
public Student(){
super("Sang", "1 Dreamland");
System.out.println("Inside Student:
Constructor");
}
● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main
● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Student:Constructor
1. Start the NetBeans IDE (if you have not done so yet)
● Windows: Start > All Programs > NetBeans 5.0 > NetBeans IDE or click NetBeans IDE 5.0 desktop icon
● Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
❍ Select File from the menu bar and select New Project.
❍ Under Choose Project, select General and Java Application
❍ Click Next.
❍ Under Name and Location pane, (Figure-10 below)
■ For Project Name field, fill it with PersonPackage
■ Click Finish
3. Replace the code in the NetBeans generated Main.java with the code of Code-15.3 above.
4. Create Person.java
● Right personpackage package node (not PersonPackage project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type Person
❍ Click Finish
5. Replaced the code in the NetBeans generated Person.java with the one of Code-15.1 above
6. Create Student.java
● Right personpackage node (not PersonPackage project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type Student
❍ Click Finish
7. Replaced the code in the NetBeans generated Student.java with the one of Code-15.2 above
8. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9)
9. Right click Main select Run File
10.Modify the Student.java as shown in Code-15.4.
11. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9)
12. Right click Main select Run File
3. Compile and run the code. You should see the following:
● Inside Person:Constructor
Inside Student:Constructor
Inside Person:Constructor
Inside Student:Constructor
Inside TuftsStudent:Constructor
Inside Person:Constructor
Inside Student:Constructor
Inside TuftsStudent:Constructor
Introduction:
● If you are new to Overriding, please read "Overriding and Hiding Methods" section of the Java Progammng Tutorial.
Steps to follow:
1. Modify Main.java as following. The code fragment that needs to be added is highlighted in bold and blue-colored font.
● cd \myjavaprograms
● jedit personpackage\Main.java
package personpackage;
// Calling methods defined in Person class, which is a parent class of Student class
student1.setName("Sang");
System.out.println("Calling getName() method: name is " + student1.getName());
}
● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main
● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor
Inside Student:Constructor
Person: getName()
Calling getName() method: name is Sang
5. Modify the Student.java as following. The code fragment that needs to be added is highlighted in bold and blue-colored font.
● cd \myjavaprograms
● jedit personpackage\Student.java
package personpackage;
public Student(){
System.out.println("Inside Student:Constructor");
}
● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main
● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor
Inside Student:Constructor
Student: getName()
Person: getName()
Calling getName() method: name is PassionateSang
It is assumed you are using the same NetBeans project you are using the same NetBeans project you created in Exsercise 15.
1. In your TuftsStudent class, override getHobby() and setHobby() methods of the Student class as following
2. Change Main.java to invoke setHobby() and getHobby() methods of the newly created TuftsStudent object instances as followoing.
3. Compile and run the code. You should see the following result.
● Inside Person:Constructor
Inside Student:Constructor
Inside Person:Constructor
Inside Student:Constructor
Inside TuftsStudent:Constructor
Inside Person:Constructor
Inside Student:Constructor
Inside TuftsStudent:Constructor
Inside TuftsStudent:setHobby() method
Inside TuftsStudent:setHobby() method
Inside TuftsStudent:getHobby() method
Hobby of student2 My hobby is swimming
Inside TuftsStudent:getHobby() method
Hobby of student3 My hobby is dancing
1. Write Person.java. This is the same Person.java as in the previous exercise except the package name. Person class is a parent class of both Student and
Employee classes, which you will write in the subsequent steps.
● cd \myjavaprograms
● mkdir polypackage
● jedit polypackage\Person.java
package polypackage;
public Person(){
System.out.println("Inside Person:Constructor");
}
● cd \myjavaprograms
● jedit polypackage\Student.java
package polypackage;
public Student(){
System.out.println("Inside Student:Constructor");
}
package polypackage;
public Employee(){
System.out.println("Inside Employee:Constructor");
}
4. Write Main.java
● cd \myjavaprograms
● jedit polypackage\Main.java
package polypackage;
● cd \myjavaprograms
● javac polypackage\*.java
● java polypackage.Main
6. Verify the result is as following. Note that depending on what object type the ref variable refers to, Employee type or Student type, proper method gets invoked.
● C:\myjavaprograms>java polypackage.Main
Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Student:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Person:Constructor 2 receiving two parameters: Young, 2 Dreamland
Inside Employee:Constructor 2 receiving two parameters: Young, 2 Dreamland
Student: getName()
Person: getName()
Passionate Student Sang
Employee: getName()
Person: getName()
Not so Passionate Employee Young
1. Start the NetBeans IDE (if you have not done so yet)
● Windows: Start > All Programs > NetBeans 5.0 > NetBeans IDE or click NetBeans IDE 5.0 desktop icon
● Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
❍ Select File from the menu bar and select New Project.
❍ Under Choose Project, select General and Java Application
❍ Click Next.
❍ Under Name and Location pane, (Figure-10 below)
■ For Project Name field, fill it with PolyPackage
■ Click Finish
3. Replace the code in the NetBeans generated Main.java with the code of Code-17.4 above.
4. Create Person.java
● Right polypackage package node (not PolyPackage project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type Person
❍ Click Finish
5. Replaced the code in the NetBeans generated Person.java with the one of Code-17.1 above
6. Create Student.java
● Right polypackage node (not PolyPackage project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type Student
❍ Click Finish
7. Replaced the code in the NetBeans generated Student.java with the one of Code-17.2 above
8. Create Employee.java
● Right polypackage node (not PolyPackage project node) and select New->Java Class
● Under Name and Location pane,
❍ for Class Name field, type Employee
❍ Click Finish
9. Replaced the code in the NetBeans generated Employee.java with the one of Code-17.3 above
10. Right click polypackage package node (not PolyPackage project node) and select Compile Package (F9)
11. Right click Main select Run File
12.Modify the Student.java as shown in Code-15.4.
13. Right click polypackage pacakge node (not PolyPackage project node) and select Compile Package (F9)
14. Right click Main select Run File
2. Modify the Main.java in which, getName() method of the Teacher object gets called
3. Compile and run the code. You should see the following result.
● C:\myjavaprograms>java polypackage.Main
Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Student:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Person:Constructor 2 receiving two parameters: Young, 2 Dreamland
Inside Employee:Constructor 2 receiving two parameters: Young, 2 Dreamland
Inside Person:Constructor 2 receiving two parameters: Wende, 21 New York
Inside Teacher:Constructor 2 receiving two parameters: Wende, 21 New York
Student: getName()
Person: getName()
Passionate Student Sang
Employee: getName()
Person: getName()
Not so Passionate Employee Young
Teacher: getName()
Person: getName()
Maybe Passionate Teacher Wende
Introduction:
● If you are new to Abstract Class, please read "Writing Abstract Classes and Methods" section of the Java Progamming Tutorial.
Steps to follow:
● cd \myjavaprograms
● mkdir abstractexercise
● jedit abstractexercise\LivingThing.java
package abstractexercise;
/**
* abstract method walk
* We want this method to be overridden by subclasses of
* LivingThing
*/
public abstract void walk();
}
Code-18.1: LivingThing.java
2. Write Main.java.
● cd \myjavaprograms
● jedit abstractexercise\Main.java
package abstractexercise;
● cd \myjavaprograms
● javac abstractexercise\LivingThing.java abstractexercise\Main.java
4. Note that you will experience a compile error since you cannot create an object instance from an abstract class.
http://www.javapassion.com/javaintro1/javabasics1/ (77 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
5. Write a concrete class called Human.java that extends the abstract LivingThing class
● cd \myjavaprograms
● jedit abstractexercise\Human.java
package abstractexercise;
}
Code-18.3: Human.java
6. Rewrite Main.java.
package abstractexercise;
● cd \myjavaprograms
● javac abstractexercise\*.java
● java abstractexercise.Main
● C:\myjavaprograms>java abstractexercise.Main
http://www.javapassion.com/javaintro1/javabasics1/ (78 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I
Human walks...
Human walks...
2. Implement a concrete method in the Human.java that implements the dance() abstract method.
Introduction:
If you are new to Interfaces, please read "Creating and Using Interfaces" section of the Java Progamming Tutorial.
Steps to follow:
● cd \myjavaprograms
● mkdir interfaceexercise
● jedit interfaceexercise\Relation.java
package interfaceexercise;
2. Write Main.java.
● cd \myjavaprograms
● jedit interfaceexercise\Main.java
package interfaceexercise;
● cd \myjavaprograms
● javac interfaceexercise\Relation.java interfaceexercise\Main.java
4. Note that you will experience a compile error since you cannot create an object instance from an Interface.
● cd \myjavaprograms
● jedit interfaceexercise\Line.java
package interfaceexercise;
(y2-y1)*(y2-y1));
return length;
}
6. Rewrite Main.java.
● cd \myjavaprograms
● jedit interfaceexercise\Main.java
package interfaceexercise;
}
}
Code-18.4: Main.java
● cd \myjavaprograms
● javac interfaceexercise\*.java
● java interfaceexercise.Main
● C:\myjavaprograms>java interfaceexercise.Main
line1 is greater than line2: false
line1 is equal with line2: true
line1 is equal with line3: false
Length of line1 is 1.4142135623730951
Length of line2 is 1.4142135623730951
Length of line3 is 5.656854249492381
Introduction:
If you are new to Exception handling, please read "Exception Handling Statements" section of the Java Progamming Tutorial.
Steps to follow:
1. Write ExceptionExample.java
● cd \myjavaprograms
● mkdir exceptionexercise
● jedit exceptionexercise\ExceptionExample.java
package exceptionexercise;
try{
System.out.println( args[1] );
} catch( ArrayIndexOutOfBoundsException exp ){
System.out.println("Exception caught!");
}
}
}
Code-20.1: ExceptionExample.java
● cd \myjavaprograms
● javac exceptionexercise\*.java
● java exceptionexercise.ExceptionExample
● C:\myjavaprograms>java exceptionexercise.ExceptionExample
Exception caught!