Вы находитесь на странице: 1из 83

LAB-1005: Java Programming Intro I

sun.com My Sun | Worldwide Sites

LAB-1005: Java Programming Basics I


Expected duration: 360 minutes

Lab exercises:

● Things to check before you start the lab


● Chapter 3 (Class #1, Jan. 16th homework)
❍ Exercise 3.1: Write, compile, and run Hello Java program (20 minutes)

❍ Exercise 3.2: Write, compile, and run Hello Java program using NetBeans (15 minutes)

● Chapter 4 (Class #1, Jan. 16th homework)


❍ Exercise 4.1: Declaring, initializing, printing variables (15 minutes)

❍ Exercise 4.2: Declaring, initializing, printing variables using NetBeans (15 minutes)

❍ Exercise 4.3: Conditional operator (15 minutes)

❍ Exercise 4.4: Building and running AverageNumber sample program (15 minutes)

❍ Exercise 4.5: Building and running GreatestValue sample program (20 minutes)

● Chapter 5 (work in progress)


❍ Exercise 5.1: Getting input from keyboard via BuferedReader class (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)

● Chapter 6 (work in progress)


❍ Exercise 6.1: For Loop (15 minutes)

● Chapter 7 (work in progress)


❍ Exercise 7.1: Array (10 minutes)

● Chapter 9 (work in progress)


❍ Exercise 9.1: Pass by value (15 minutes)

❍ Exercise 9.2: Pass by reference (15 minutes)

❍ Exercise 9.3: Comparing objects (15 minutes)

● Chapter 10 (work in progress)


❍ Exercise 10.1: Create your own class (30 minutes)

❍ Exercise 10.2: Overloading (15 minutes)

❍ Exercise 10.3: Packaging (30 minutes)

● Chapter 11 (work in progress)


❍ Exercise 11.1: Inheritance - Constructor (20 minutes)

❍ Exercise 11.2: Inheritance - Overriding (20 minutes)

❍ Exercise 11.3: Polymorphism (30 minutes)

❍ Exercise 11.4: Abstract class (20 minutes)

❍ Exercise 11.5: Interfaces (30 minutes)

● Chapter 12 (work in progress)


❍ Exercise 12.1: Exception handling (15 minutes)

http://www.javapassion.com/javaintro1/javabasics1/ (1 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Other Online Resources:

● The Java Tutorial from Sun Developer Network


● Downloadable Java tutorials
● java.sun.com
● J2SE SDK 5.0 Javadoc

Hardware and OS requirement:

● 256MB memory minimum (512MB recommended)


● 125MB disk space

OS you can use:

● Windows, Solaris, Linux, Mac OS X

Software needed for the lab:

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.

● Download and install JDK 5.0


❍ For Windows, select "Windows Offline Installation, Multi-language" to download it. Once downloaded, double-click the file to install it.

■ 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 Linux, select "Linux 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

❍ Please download "NetBeans IDE 5.0 RC 1 Installer"

❍ 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

or install the final version when it is available.


❍ During installation of NetBeans IDE, select J2SE 5.0 as your default Java platform among the available JDK versions.

● Download J2SE SDK 5.0 Documentation


❍ This is to enable context-sensitive JavaDoc support when using NetBeans IDE

❍ You can store it in any location of your file system

● Text editor of your choice


❍ There are some exercises you will do in this course using command line tools and text editor (instead of using NetBeans).

❍ For text editor, you can use any text editor of your choice including the ones mentioned below.

■ JEdit

■ You can download either Java-based installer or Windows installer/Mac OS X package

■ 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

command line to start the installation like following:


http://www.javapassion.com/javaintro1/javabasics1/ (2 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

■ 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

just type "jedit <file-name>".


■ TextPad (Windows only)
■ metapad (Windows only)
■ vi
■ emacs
■ notepad (Windows only)

NetBeans Lab Project Files:

● 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)

What is and how to submit homework:

● Each exercise below will contain Homework and How to submit homework sections.

Exercise 0: Things to check before you start the lab

● Install software as described in Software needed for the lab above.


● Once you installed J2SE SDK, please check if it is installed correctly
❍ Make sure the installation has set %JAVA_HOME% (Windows) or $JAVA_HOME (Solaris/Linux) environment variable to the installation directory of J2SE

1.5.0_06 (or later version).


■ Type "echo %JAVA_HOME%" (Windows) or "echo $JAVA_HOME" (Solaris/Linux) in a terminal window. You should see the following:

■ C:\Program Files\Java\jdk1.5.0_06 (Windows)

■ /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.)

You should see something like following


■ java version "1.5.0_06"

Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)

http://www.javapassion.com/javaintro1/javabasics1/ (3 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)


Trouble-shooting: If you don't see the above, the %JAVA_HOME%\bin is not in your path. You can set the PATH environment variable by following

the instruction below (under Windows)


■ Right click on "My Computer", select properties, and then go to the "advanced" tab.

■ 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

http://www.javapassion.com/javaintro1/javabasics1/ (4 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class Hello {

/**
* My first Java program
*/
public static void main( String[] args ){

// Print the string "Hello world" on screen


System.out.println("Hello world");

}
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.

● C:\myjavaprograms>javac -verbose Hello.java


[parsing started Hello.java]
[parsing completed 31ms]
[search path for source files: [C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip]]
[search path for class files: [C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar,C:\Program Files\Java\jdk1.5.0_06\jre\lib\jsse.jar, C:\Program Files\Java
\jdk1.5.0_06\jre\lib\jce.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\charsets.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\dnsns.jar, C:\Program Files

http://www.javapassion.com/javaintro1/javabasics1/ (5 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

\Java\jdk1.5.0_06\jre\lib\ext\localedata.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\sunjce_provider.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext


\sunpkcs11.jar, C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip]]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/Object.class)]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/String.class)]
[checking Hello]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/System.class)]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/PrintStream.class)]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/FilterOutputStream.class)]
[loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/OutputStream.class)]
[wrote Hello.class]
[total 266ms]

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

-target <release> Generate class files for specific VM version


-version Version information
-help Print a synopsis of standard options
-X Print a synopsis of nonstandard options
-J<flag> Pass <flag> directly to the runtime system

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

the java command as Java interpreter.

● java Hello

You should see either of the following results.

● 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.

● C:\myjavaprograms>java -classpath . Hello


Hello world
● C:\myjavaprograms>java -cp . Hello
Hello world
http://www.javapassion.com/javaintro1/javabasics1/ (7 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

Experimentation 6.3: Try to set the classpath with full directory path, C:\myjavaprograms in this example. It should work as well.

● C:\myjavaprograms>java -classpath C:\myjavaprograms Hello


Hello world
● C:\myjavaprograms>java -cp C:\myjavaprograms Hello
Hello world

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.

1. In the directories you specify with -classpath or -cp option.


2. In the directories that are specified in the CLASSPATH environment variable (If you have not specified the -classpath or -cp option)
3. In the currently directory (If you have not specified the -classpath or -cp option and the environment variable CLASSPATH is not set)

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.

● C:\myjavaprograms>move Hello.class .. (move the Hello.class to parent directory)


C:\myjavaprograms>java -classpath .. Hello (run the program using the classpath set to the parent directory)
Hello world
C:\myjavaprograms>java -classpath C:\ Hello (same as above, you the classpath explicitly)
Hello world
C:\myjavaprograms>java -classpath . Hello (this should fail because you no longer have Hello.class in the current directory)
Exception in thread "main" java.lang.NoClassDefFoundError: Hello

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

http://www.javapassion.com/javaintro1/javabasics1/ (8 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

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

● "This is my first Java program" (instead of "Hello world")

2. Please play around with the classpath settings with -classpath or -cp option and CLASSPATH environment variable.

What and how to submit:

1. Email modified Hello.java file as an attachment to javaintro1homework@sun.com with subject line as HWExercise3.1. (Please make sure you use the correct
subject line.) No need to make it a zip file.

return to the top

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

http://www.javapassion.com/javaintro1/javabasics1/ (9 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

JVM.

Steps to follow:

1. Start the NetBeans IDE.

● 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)

http://www.javapassion.com/javaintro1/javabasics1/ (10 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure-3.2-a: Create a new NetBeans project

❍ 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.)

http://www.javapassion.com/javaintro1/javabasics1/ (11 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

3. Modify the IDE generated Hello.java

● 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

http://www.javapassion.com/javaintro1/javabasics1/ (12 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

4. Run Hello program

● Right click Hello project node and select Run Project from the contextual menu. ((Figure-3.2-d below)

Figure-3.2-d: Run Hello Program


http://www.javapassion.com/javaintro1/javabasics1/ (13 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

● Note that the Output window displays the result (Figure-3.2-e below)

Figure-3.2-e: Output of running Hello program

Homework:

1. Create a new NetBeans project called "MyOwnHelloWorld" from scratch.


http://www.javapassion.com/javaintro1/javabasics1/ (14 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

2. The program should display the following text when it runs.

● This is my own NetBeans project, and I am damn proud of it.

What and how to submit:

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

❍ Select Start / All Programs / Accessories / Paint

❍ Ctrl+V to paste into Paint.

❍ Use the border selection tool (dashed line box in upper left corner), select the portion of the image you want to keep

❍ File / New, then Ctrl+V

❍ File / Save As - pull down "Save As Type" to be GIF or JPG, then save

2. Email it as an attachment to javaintro1homework@sun.com with subject line as HWExercise3.2.

return to the top

Exercise 4.1: Declaring, Initializing, Printing Variables (15 minutes)

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:

1. Create OutputVariable.java using your editor of choice as shown in Code-4.1-a below.

● cd \myjavaprograms
● jedit OutputVariable.java

http://www.javapassion.com/javaintro1/javabasics1/ (15 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class OutputVariable {

public static void main( String[] args ){

// Variable value is int primitive type and it is initialized to 10


int value = 10;

// Variable x is char primitive type and it is initialized to 'A'


char x;
x = 'A';

// Display the value of variable "value" on the standard output device


System.out.println( value );

// Display the value of variable "x" on the standard output device


System.out.println( "The value of x=" + x );

}
Code-4.1-a: VariableSamples.java

2. Compile and run the code

● javac OutputVariable.java
● java -classpath . OutputVariable

3. Verify that the result is as following

● C:\myjavaprograms>java OutputVariable
10
The value of x=A

Homework:

1. Modify OutputVariable.java as following and compile and run the code

● Define another primitive type as following


❍ double grade = 11;

● Print out the value of variable "grade" using the following statement.
❍ System.out.println( "The value of grade =" + grade );

What and how to submit:

1. Email modified OutputVariable.java file as an attachment to javaintro1homework@sun.com with subject line as HWExercise4.1.

return to the top


http://www.javapassion.com/javaintro1/javabasics1/ (16 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

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

2. Create a new NetBeans project and OutputVariable main class.

● 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.

3. Modify the IDE generated OutputVariable.java

● 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.

4. Run OutputVariable program

● Right click OutputVariable project node and select Run Project from the contextual menu.
● Note that the Output window displays the result

Homework:

1. Do the homework of Exercise 4.1 above using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise4.2.

http://www.javapassion.com/javaintro1/javabasics1/ (17 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Exercise 4.3: Conditional Operator (15 minutes)


Introduction:

In this exercise, you are going to write a Java program which uses conditional operators.

Steps to follow:

1. Create ConditionalOperator.java using your editor of choice

● cd \myjavaprograms
● jedit ConditionalOperator.java

public class ConditionalOperator {

public static void main( String[] args ){

String status = "";


int grade = 80;

//get status of the student


status = (grade >= 60)?"Passed":"Fail";

//print status
System.out.println( status );
}

}
Code-4.3-a: ConditionalOperator.java

2. Compile and run the code

● javac ConditionalOperator.java
● java -classpath . ConditionalOperator

3. Verify that the result is as following

● 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

http://www.javapassion.com/javaintro1/javabasics1/ (18 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● int salary = 100000;


● Print "You are rich!" if the salary is over 50000. Print "You are poor!" otherwise.

2. Do the homework both using command line tools and using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise4.3.

return to the top

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:

1. Start NetBeans (if you have not done so.)


2. Open an existing AverageNumber sample NetBeans project.

● Select File from menu bar.


● Select Open Project (Crtl+SHift+O).

http://www.javapassion.com/javaintro1/javabasics1/ (19 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure-X: Open an existing project

● 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.

http://www.javapassion.com/javaintro1/javabasics1/ (20 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure-X: Open AverageNumberProject

● Expand AverageNumberProject project node.


● Expand Source Packages. (The Source Packages node contains all the packages.)
● Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
● Double click AverageNumber.java to open it in the Editor window.

http://www.javapassion.com/javaintro1/javabasics1/ (21 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure-X: Open AverageNUmber.java


http://www.javapassion.com/javaintro1/javabasics1/ (22 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

3. Run the program.

● 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.)

http://www.javapassion.com/javaintro1/javabasics1/ (23 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure-X: Run File

Homework

1. Add another number with the following statement and compute a new average.

● int num4 = 100;

What and how to submit

1. No need to submit this homework

return to the top

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

1. Start NetBeans (if you have not done so.)


2. Open an existing GreatestValue sample NetBeans project.

● Select File from menu bar.


● Select Open Project (Crtl+SHift+O).
● In the Open Project window, browse to C:\NetBeansFiles\Chapter 4\4.3 directory and select GreatestValueProject.
● Click Open Project Folder button.
● Expand GreatestValueProject project node.
● Expand Source Packages. (The Source Packages node contains all the packages.)
● Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
● Double click GreatestValue.java to open it in the Editor window.

3. Run the program.

● 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

What and how to submit

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 javaintro1homework@sun.com with subject line as HWExercise4.5.

return to the top

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;

public class GetInputFromKeyboard {

public static void main( String[] args ){

BufferedReader dataIn = new BufferedReader(new


InputStreamReader( System.in) );

String name = "";


System.out.print("Please Enter Your Name:");
try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!");
}

http://www.javapassion.com/javaintro1/javabasics1/ (25 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

}
Code-5.1.a: GetInputFromKeyboard.java

2. Compile and run the code

● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard

You should have the following interaction. In this example, I typed Sang Shin.

● C:\myjavaprograms>java -classpath . GetInputFromKeyboard


Please Enter Your Name:Sang Shin
Hello 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;

public class GetInputFromKeyboard {

public static void main( String[] args ){

BufferedReader dataIn = new BufferedReader(new


InputStreamReader( System.in) );

String name = "";


System.out.print("Please Enter Your Name:");
try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!");

String age= "";


System.out.print("Please Enter Your Age:");
try{
age = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!" + " " + "Your age is " + age);

}
http://www.javapassion.com/javaintro1/javabasics1/ (26 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

Code 5.1.b: Display age as well

4. Compile and run the code.

● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard

5. You should have the following interaction.

● C:\myjavaprograms>java -classpath . GetInputFromKeyboard


Please Enter Your Name:Sang Shin
Hello Sang Shin!
Please Enter Your Age:99
Hello Sang Shin! Your age is 99

6. Now suppose you want to add the following logic.

● If the entered age is over 100, display<>


❍ <>Hello <name>! You are old!

● 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

http://www.javapassion.com/javaintro1/javabasics1/ (27 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

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/

Figure 5.1.c: Integer class

7. Scroll down the Integer class to see the parseInt(String s) method. (Figure 5.1.d below)

http://www.javapassion.com/javaintro1/javabasics1/ (28 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.1.d: parseInt(String s) method of Integer class


http://www.javapassion.com/javaintro1/javabasics1/ (29 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

8. Click parseInt(String s) method to see the detailed information. (Figure 5.1.e below)

http://www.javapassion.com/javaintro1/javabasics1/ (30 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.1.e: Detailed information on parseInt(String s) method of Integer class

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;

public class GetInputFromKeyboard {

public static void main( String[] args ){

BufferedReader dataIn = new BufferedReader(new


InputStreamReader( System.in) );

String name = "";


System.out.print("Please Enter Your Name:");
try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!");

String age= "";


System.out.print("Please Enter Your Age:");
try{
age = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!" + " " + "Your age is " + age);

// 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

10. Compile and run the code.

● javac GetInputFromKeyboard.java
● java -classpath . GetInputFromKeyboard

11. You should have the following interaction.

● C:\myjavaprograms>java -classpath . GetInputFromKeyboard


Please Enter Your Name:Sang Shin
Hello Sang Shin!
Please Enter Your Age:10
Hello Sang Shin! Your age is 10
Hello Sang Shin! You are young.

C:\myjavaprograms>java -classpath . GetInputFromKeyboard


Please Enter Your Name:Sang Shin
Hello Sang Shin!
Please Enter Your Age:120
Hello Sang Shin! Your age is 120
Hello Sang Shin! You are old.

Homework:

1. Modify GetInputFromKeyboard.java as following, compile and run the code

● Make the program to ask the following question


❍ Please enter your mother's age:

● 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>!

2. Do the homework either at the command line or using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise5.1.

return to the top

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

1. Start NetBeans (if you have not done so.)


2. Open an existing LastThreeWords sample NetBeans project.

● Select File from menu bar.


● Select Open Project (Crtl+SHift+O).
● In the Open Project window, browse to C:\NetBeansFiles\Chapter 5\5.1 directory and select LastThreeWordsProject.
● Click Open Project Folder button.
● Expand LastThreeWordsProject project node.
● Expand Source Packages. (The Source Packages node contains all the packages.)
● Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
● Double click LastThreeWords.java to open it in the Editor window.

3. Run the program.

● 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)

http://www.javapassion.com/javaintro1/javabasics1/ (33 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.a: Enter value to the Input field

● 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)

http://www.javapassion.com/javaintro1/javabasics1/ (34 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.b: Result of running the application

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

any class in a context sensitive manner.

● Select Tools from the top-level menu bar.


● Select Java Platform Manager. (Figure 5.2.c below)

http://www.javapassion.com/javaintro1/javabasics1/ (36 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.c: Select Java Platform Manager

● In the Java Platform Manager dialog box, select Javadoc tab.


● Click Add ZIP/Folder button. (Figure 5.2.d below)

http://www.javapassion.com/javaintro1/javabasics1/ (37 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)

Figure 5.2.e: Add jdk-1_5_0-doc.zip

● In the Java Platform Manager dialog box, click Close button. (Figire 5.2.f below)

http://www.javapassion.com/javaintro1/javabasics1/ (38 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.f: Close the Java Platform Manager

5. Display Java document of the BufferedReader class in a context-sensitive manner.

● Move your cursor to any position of the "BufferedReader" string.


● Right click and choose Show Javadoc (Alt+F1) or click Alt+F1 key combination. (Figure 5.2.g below)

http://www.javapassion.com/javaintro1/javabasics1/ (39 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.g: Display Java document of the BufferedReader class

● 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

http://www.javapassion.com/javaintro1/javabasics1/ (41 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Figure 5.2.h: Java document of BufferedReader class

● 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.

● Click through the hyper links in the page.

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.

What and how to submit:

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 javaintro1homework@sun.com 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:

1. Create GetInputFromKeyboardJOptionPane.java as shown in Code-5.2 below.

http://www.javapassion.com/javaintro1/javabasics1/ (42 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● cd \myjavaprograms
● jedit GetInputFromKeyboardJOptionPane.java

import javax.swing.JOptionPane;

public class GetInputFromKeyboardJOptionPane {

public static void main( String[] args ){


String name = "";
name=JOptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
}
}
Code-5.3: GetInputFromKeyboardJOptionPane.java

2. Compile and run the code

● javac GetInputFromKeyboardJOptionPane.java
● java -classpath . GetInputFromKeyboardJOptionPane
❍ Enter your name

❍ CTRL/C to close the application

Homework:

1. Modify GetInputFromKeyboardJOptionPane.java as following, compile and run the code

● Make the program to ask the following question


❍ Please enter your age

● Display the entered age as following


❍ If the age is over 100, display

<>Hello <name>, You are old!


❍ Otherwise

<>Hello <name>, You are young!

2. Do the homework both at the command line or using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise5.3.

return to the top

http://www.javapassion.com/javaintro1/javabasics1/ (43 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Exercise 6.1: For Loop (20 minutes)

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:

1. Create ForLoop.java using your editor of choice as shown in Code-6.1 below.

● cd \myjavaprograms
● jedit ForLoop.java

public class ForLoop {

public static void main( String[] args ){

String names []={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};


String searchName ="Yza";
boolean foundName =false;

for (int i=0;i<names.length;i++){


if (names [i ].equals(searchName )){
foundName =true;
break;
}
}

if (foundName )
System.out.println(searchName +" is found!");
else
System.out.println(searchName +" is not found.");

}
Code-6.1: ForLoop.java

2. Compile and run the code

● 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

3. Verify that the result is as following

● C:\myjavaprograms>java ForLoop
Yza is found!

Homework:

1. Modify ForLoop.java as following, compile and run the code

● Change the code to use while loop (instead of for loop)

2. Do the homework both at the command line or using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise6.1.

return to the top

Exercise 7.1: Array (10 minutes)

Steps to follow:

1. Create ArraySample.java.

● cd \myjavaprograms
● jedit ArraySample.java

public class ArraySample {

public static void main( String[] args ){

int[] ages = new int[100];

for( int i=0; i<ages.length; i++ ){


System.out.print( ages[i] );
}

}
Code-7.1: ArraySample.java

http://www.javapassion.com/javaintro1/javabasics1/ (45 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

2. Compile and run the code

● javac ArraySample.java
● java -classpath . ArraySample

3. Verify the result is as following

● C:\myjavaprograms>java ArraySample
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000

Homework:

1. Modify ArraySample.java as following, compile and run the code

● 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

2. Do the homework both at the command line or using NetBeans.

What and how to submit:

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 javaintro1homework@sun.com with subject line as HWExercise7.1.

return to the top

Exercise 9.1: Pass By Value (15 minutes)

Steps to follow:

1. Create .java using your editor of choice

● cd \myjavaprograms
● jedit TestPassByValue.java

http://www.javapassion.com/javaintro1/javabasics1/ (46 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class TestPassByValue {

public static void main(String[] args){

int i = 10;

//print the value of i


System.out.println(i);

//Call method test


//and pass i to method test
test( i );

// print the value of i. i not changed


System.out.println(i);

public static void test(int j){


// change value of parameter i
j = 33;
}

}
Code-19: TestPassByValue.java

2. Compile and run the code

● javac TestPassByValue.java
● java -classpath . TestPassByValue

3. Verify the result is as following

● C:\myjavaprograms>java TestPassByValue
10
10

return to the top

Exercise 9.2: Pass By Reference (10 minutes)

Steps to follow:

1. Create TestPassByReference.java using your editor of choice

● 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 class TestPassByReference {

public static void main(String[] args){

//create an array of integers


int [] ages = {10, 11, 12};

//print array values


for (int i=0; i<ages.length; i++ ){
System.out.println(ages[i]);
}

//call test and pass references to array


test(ages);

//print array values again


for (int i=0; i<ages.length; i++ ){
System.out.println(ages[i]);
}

}
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

2. Compile and run the code

● javac TestPassByReference.java
● java TestPassByReference

3. Verify the result is as following

● 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

return to the top

Exercise 9.3: Comparing Objects (15 minutes)

Steps to follow:

1. Create EqualsTest.java using your editor of choice

● 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

2. Compile and run the code

● javac EqualsTest.java
● java -classpath . EqualsTest

3. Verify the result is as following.

● 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

Same value? true

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

5. Compile and run the code

● javac EqualsTestInteger.java
● java EqualsTestInteger

return to the top

Exercise 10.1: Create Your Own Class (30 minutes)

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:

1. Create StudentRecord.java using your editor of choice

● 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

public class StudentRecord {

// 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

http://www.javapassion.com/javaintro1/javabasics1/ (51 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

2. Create StudentRecordExample.java using your editor of choice

● cd \myjavaprograms
● jedit StudentRecordExample.java

public class StudentRecordExample{


public static void main(String [] args ){

//create three objects for Student record


StudentRecord annaRecord =new StudentRecord();
StudentRecord beahRecord =new StudentRecord();
StudentRecord crisRecord =new StudentRecord();

//set the name of the students


annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");

//print anna's name


System.out.println(annaRecord.getName());

//print number of students


System.out.println("Count="+StudentRecord.getStudentCount());
}
}
Code-12.2: StudentRecordExample.java

3. Compile and run the code

● javac *.java (or javac StudentRecord.java StudentRecordExample.java)


● java -classpath . StudentRecordExample

4. Verify the result

● C:\myjavaprograms1>java StudentRecordExample
Anna
Count=0

Steps to follow if you are using NetBeans

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

http://www.javapassion.com/javaintro1/javabasics1/ (52 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

2. Create a new NetBeans project and StudentRecordExample main class

❍ 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

■ For Create Main Class field, change it to studentrecordexample.StudentRecordExample (from studentrecordexample.Main)

■ Click Finish

Figure-12.3: New Java Application

3. Modify the NetBeans generated code

http://www.javapassion.com/javaintro1/javabasics1/ (53 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● 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

5. Modify the NetBeans generated code

● 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.

6. Run StudentRecordExample application

● Right click StudentRecordExample.java node under Hello->Source Packages->studentrecordexample and select Run File (Shift+F6)
● Note that the Output window displays the result

Your own exercise:

1. Modify StudentRecord.java as following

❍ Add setMathGrade(double grade) method


❍ Add setEnglishGrade(double grade) method
❍ Add setScienceGrade(double grade) method
❍ Add static method called increaseStudentCount(), this method increase the static variable studentCount by 1

2.. Modify StudentRecordExample.java as following

● Create another StudentRecord object, call it myOwnRecord


● Call setName() method of the myOwnRecord object passing "myOwn" as the value to set
● Display the name of the myOwnRecord object

● Set Math grade of myOwnRecord object


● Set English grade of myOwnRecord object
● Set Science grade of myOwnRecord object
● Display the average grade of myOwnRecord

3. Run StudentRecordExample application

4. Solution is provided in Solution to Exercise 12

http://www.javapassion.com/javaintro1/javabasics1/ (54 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● Make sure you add packge statement at the top

return to the top

Exercise 10.2: Overloading (15 minutes)

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.

● Add two overloaded print(..) methods.

public class StudentRecord {

...

public void print(String name ){


System.out.println("Name:"+name);
}

public void print(String name, double averageGrade){


System.out.print("Name:"+name+" ");
System.out.println("Average
Grade:"+averageGrade);
}

}
Code-13.1: StudentRecord.java

2.Create StudentRecordExample2.java as following

● cd \myjavaprograms
● jedit StudentRecordExample2.java

http://www.javapassion.com/javaintro1/javabasics1/ (55 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class StudentRecordExample2{


public static void main(String [] args) {
StudentRecord annaRecord =new StudentRecord();

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.

● javac *.java (or javac StudentRecord.java StudentRecordExample2.java)


● java -classpath . StudentRecordExample2

4. Verify the result

● Name:Anna
Name:Anna Average Grade:65.16666666666667

Steps to follow if you are using NetBeans

It is assumed you are using the same NetBeans project you created in Exercise 12.

1. Modify the StudentRecord.java as shown in Code 13-1 above


2. Create StudentRecordExample2.java

● 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

3. Modify the NetBeans generated StudentRecordExample2.java

● 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

http://www.javapassion.com/javaintro1/javabasics1/ (56 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Your own exercise:

1. Modify StudentRecord.java as following

● Add another print() method which takes the following three parameters
❍ name

❍ grade average

❍ student count

2. Modify StudentRecordExmaple2.java as following

● Invoke the newly added print() method

3. Solution is provided in Solution to Exercise 13

return to the top

Exercise 10.3: Packaging (30 minutes)

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

http://www.javapassion.com/javaintro1/javabasics1/ (57 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class StudentRecord {

// 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

http://www.javapassion.com/javaintro1/javabasics1/ (58 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

public class StudentRecordExample{


public static void main(String [] args ){

//create three objects for Student record


StudentRecord annaRecord =new StudentRecord();
StudentRecord beahRecord =new StudentRecord();
StudentRecord crisRecord =new StudentRecord();

//set the name of the students


annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");

//print anna's name


System.out.println(annaRecord.getName());

//print number of students


System.out.println("Count="+StudentRecord.getStudentCount());
}
}
Code-14.2; 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;

public class StudentRecord {

...

}
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;

public class StudentRecordExample{


...
}
Code-28: StudentRecordExample2.java with package statement

3. Compile code.

● del StudentRecord.class

http://www.javapassion.com/javaintro1/javabasics1/ (59 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● 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

● javac studentpackage\StudentRecord.java studentpackage\StudentRecordExample.java


● C:\myjavaprograms>dir studentpackage
Volume in drive C is S3A1256D004
Volume Serial Number is 447E-6EBC

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

07/06/2005 12:39 PM <DIR> .


07/06/2005 12:39 PM <DIR> ..
07/06/2005 12:40 PM 1,499 StudentRecord.class
07/06/2005 12:16 PM 1,425 StudentRecord.java
07/06/2005 12:40 PM 880 StudentRecordExample.class
07/06/2005 12:17 PM 690 StudentRecordExample.java
4 File(s) 4,494 bytes
2 Dir(s) 1,415,856,128 bytes free

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:

● C:\myjavaprograms\studentpackage>java -classpath \myjavaprograms StudentRecordExample


Exception in thread "main" java.lang.NoClassDefFoundError: StudentRecordExample
http://www.javapassion.com/javaintro1/javabasics1/ (61 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

C:\myjavaprograms\studentpackage>java -classpath \myjavaprograms studentpackage.StudentRecordExample


Anna
Count=0

Your own exercise:

1. Create a class called Food under foodpackage.fruitpackage pacakge

● Food.java should have the following package statement at the top


❍ package foodpackage.fruitpackage

● Add a couple of methods of your own

2. Create a class called FoodMain under foodpackage.fruitpackage package

● FoodMain class creates an Food object


● FoodMain class then calls a method of Food object

3. Compile and run the code

4. Solution is available from Solution to Exercise 14

return to the top

Exercise 11.1: Inheritance - Constructor (20 minutes)

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

http://www.javapassion.com/javaintro1/javabasics1/ (62 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package personpackage;

public class Person {

private String name;


private String address;

public Person(){
System.out.println("Inside Person:Constructor");
}

public Person (String name, String address){


System.out.println("Inside Person:Constructor 2 receiving two parameters: " + name + ", " + address);
this.name = name;
this.address = address;
}

public String getName(){


System.out.println("Person: getName()");
return name;
}

public void setName(String s){


name = s;
}

public String getAddress(){


return address;
}

public void setAddress(String s){


address = s;
}
}
Code-15.1: Person.java

2. Write Student.java

● cd \myjavaprograms
● jedit personpackage\Student.java

http://www.javapassion.com/javaintro1/javabasics1/ (63 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package personpackage;

public class Student extends Person {

private String hobby;

public Student(){
System.out.println("Inside Student:
Constructor");
}

public String getHobby(){


return hobby;
}

public void setHobby(String s){


hobby = s;
}
}
Code-15.2: Student.java

3. Write Main.java

● cd \myjavaprograms
● jedit personpackage\Main.java

package personpackage;

public class Main {

public static void main(String [] args )


{
Student student1 =new Student();
}

}
Code-15.3: Main.java

4. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main

5. Verify the result is as following

http://www.javapassion.com/javaintro1/javabasics1/ (64 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● 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 class Student extends Person {

private String hobby;

public Student(){
super("Sang", "1 Dreamland");
System.out.println("Inside Student:
Constructor");
}

public String getHobby(){


return hobby;
}

public void setHobby(String s){


hobby = s;
}
}
Code-15.4: Modified Student.java

7. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main

8. Verify the result is as following

● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor 2 receiving two parameters: Sang, 1 Dreamland
Inside Student:Constructor

Steps to follow if you are using NetBeans

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

http://www.javapassion.com/javaintro1/javabasics1/ (65 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

2. Create a new NetBeans project and Main.java main class

❍ 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

Your own exercise:

1. Write TuftsStudent.java as following

● TuftsStudent class extends Student class


● Write a constructor of the TuftsStudent class as following
❍ public TuftsStudent(){
System.out.println("Inside TuftsStudent:Constructor");
}

2. Modify the Main.java to create an instance of TuftsStudent class as following

● TuftsStudent student2 =new TuftsStudent();


Student student3 =new TuftsStudent();
http://www.javapassion.com/javaintro1/javabasics1/ (66 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

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

4. Solution to this exercise can be found from Solution to Exercise 15

return to the top

Exercise 11.2: Inheritance - Overriding (20 minutes)

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;

public class Main {

public static void main(String [] args ){


Student student1 =new Student();

// 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());
}

http://www.javapassion.com/javaintro1/javabasics1/ (67 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Code-16.1: Modified Main.java

2. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main

3. Verify the result is as following

● 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 class Student extends Person {

private String hobby;

public Student(){
System.out.println("Inside Student:Constructor");
}

public String getHobby(){


return hobby;
}

public void setHobby(String s){


hobby = s;
}

// Override getName() method of the parent class


public String getName(){
System.out.println("Student: getName()");
return "Passionate" + super.getName();
}
}
Code-16.2 Modified Student.java

6. Compile and run the code using a directory structure.


http://www.javapassion.com/javaintro1/javabasics1/ (68 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

● cd \myjavaprograms
● javac personpackage\*.java
● java personpackage.Main

7. Verify the result is as following

● C:\myjavaprograms>java personpackage.Main
Inside Person:Constructor
Inside Student:Constructor
Student: getName()
Person: getName()
Calling getName() method: name is PassionateSang

Steps to follow if you are using NetBeans

It is assumed you are using the same NetBeans project you are using the same NetBeans project you created in Exsercise 15.

1. Modify the Main.java as shown in Code-16.1.


2. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9)
3. Right click Main select Run File
4. Modify the Student.java as shown in Code-16.2.
5. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9)
6. Right click Main select Run File

Your own exercise:

1. In your TuftsStudent class, override getHobby() and setHobby() methods of the Student class as following

● public String getHobby(){


System.out.println("Inside TuftsStudent:getHobby() method");
return "My hobby is " + super.getHobby();
}

public void setHobby(String s){


System.out.println("Inside TuftsStudent:setHobby() method");
super.setHobby(s);
}

2. Change Main.java to invoke setHobby() and getHobby() methods of the newly created TuftsStudent object instances as followoing.

● // set hobbies of student2 and student3


student2.setHobby("swimming");
student3.setHobby("dancing");

// get hobbies of student2 and student3


String hobby2 = student2.getHobby();
http://www.javapassion.com/javaintro1/javabasics1/ (69 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

System.out.println("Hobby of student2 " + hobby2);


String hobby3 = student3.getHobby();
System.out.println("Hobby of student3 " + hobby3);

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

4. Solution to this exercise can be found Solution to Exercise 16

return to the top

Exercise 11.3: Polymorphism (30 minutes)

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

http://www.javapassion.com/javaintro1/javabasics1/ (70 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package polypackage;

public class Person {

private String name;


private String address;

public Person(){
System.out.println("Inside Person:Constructor");
}

public Person (String name, String address){


System.out.println("Inside Person:Constructor 2 receiving two parameters: " + name + ", " + address);
this.name = name;
this.address = address;
}

public String getName(){


System.out.println("Person: getName()");
return name;
}

public void setName(String s){


name = s;
}

public String getAddress(){


return address;
}

public void setAddress(String s){


address = s;
}
}
Code-17.1: Person.java

2. Write Student.java. Student class is a subclass of a Person class.

● cd \myjavaprograms
● jedit polypackage\Student.java

http://www.javapassion.com/javaintro1/javabasics1/ (71 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package polypackage;

public class Student extends Person {

private String hobby;

public Student(){
System.out.println("Inside Student:Constructor");
}

public Student (String name, String address){


super(name, address);
System.out.println("Inside Student:Constructor 2 receiving two parameters: " + name + ", " + address);
}

public String getHobby(){


return hobby;
}

public void setHobby(String s){


hobby = s;
}

// Override getName() method of the parent class


public String getName(){
System.out.println("Student: getName()");
return "Passionate Student " + super.getName();
}
}
Code-17.2: Student.java

3. Write Employee.java. Employee class is subclass of Person class.

● cd \myjavaprograms (if you are not in this directory already)


● jedit polypackage\Employee.java

http://www.javapassion.com/javaintro1/javabasics1/ (72 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package polypackage;

public class Employee extends Person {

private String hobby;

public Employee(){
System.out.println("Inside Employee:Constructor");
}

public Employee(String name, String address){


super(name, address);
System.out.println("Inside Employee:Constructor 2 receiving two parameters: " + name + ", " + address);
}

public String getHobby(){


return hobby;
}

public void setHobby(String s){


hobby = s;
}

// Override getName() method of the parent class


public String getName(){
System.out.println("Employee: getName()");
return "Not so Passionate Employee " + super.getName();
}
}
Code-17.3: Employee.java

4. Write Main.java

● cd \myjavaprograms
● jedit polypackage\Main.java

http://www.javapassion.com/javaintro1/javabasics1/ (73 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package polypackage;

public class Main {


public static void main( String[] args ) {
Person ref;
Student studentObject = new Student("Sang", "1 Dreamland");
Employee employeeObject = new Employee("Young", "2 Dreamland");

ref = studentObject; //Person ref. points to a


// Student object

//getName of Student class is called


String temp1=ref.getName();
System.out.println( temp1 );

ref = employeeObject; //Person ref. points to an


// Employee object

//getName of Employee class is called


String temp2 = ref.getName();
System.out.println( temp2 );
}
}
Code-17.4 Main.java

5. Compile and run the code using a directory structure.

● 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

Steps to follow if you are using NetBeans

http://www.javapassion.com/javaintro1/javabasics1/ (74 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

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

2. Create a new NetBeans project and Main.java main class

❍ 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

http://www.javapassion.com/javaintro1/javabasics1/ (75 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

Your own exercise:

1. Create another class called Teacher.java as following

● Teacher class extends Person class


● Teacher clsss also has the following method
❍ // Override getName() method of the parent class
public String getName(){
System.out.println("Teacher: getName()");
return "Maybe Passionate Teacher" + super.getName();
}

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

4. The solution to this exercise can be found in Solution to Exercise 17

return to the top

Exercise 11.4: Abstract Class (20 minutes)

Introduction:

● If you are new to Abstract Class, please read "Writing Abstract Classes and Methods" section of the Java Progamming Tutorial.

Steps to follow:

http://www.javapassion.com/javaintro1/javabasics1/ (76 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

1. Write abstract class called LivingThing.java

● cd \myjavaprograms
● mkdir abstractexercise
● jedit abstractexercise\LivingThing.java

package abstractexercise;

public abstract class LivingThing {


public void breath(){
System.out.println("Living Thing breathing...");
}

public void eat(){


System.out.println("Living Thing eating...");
}

/**
* 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;

public class Main {


public static void main( String[] args ) {
LivingThing x = new LivingThing();
}
}
Code-18.2: Main.java

3. Compile Livingthing.java and Main.java.

● 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

● C:\myjavaprograms>javac abstractexercise\LivingThing.java abstractexercise\Main.java


abstractexercise\Main.java:5: abstractexercise.LivingThing is abstract; cannot be instantiated
LivingThing x = new LivingThing();
^
1 error

5. Write a concrete class called Human.java that extends the abstract LivingThing class

● cd \myjavaprograms
● jedit abstractexercise\Human.java

package abstractexercise;

public class Human extends LivingThing {

public void walk(){


System.out.println("Human walks...");
}

}
Code-18.3: Human.java

6. Rewrite Main.java.

package abstractexercise;

public class Main {


public static void main( String[] args ) {
Human x = new Human();
x.walk();

LivingThing y = new Human();


y.walk();
}
}
Code-18.4: Main.java

7. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac abstractexercise\*.java
● java abstractexercise.Main

8. Verify the result is as following.

● 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...

Your own exericse:

1. Define another abstract method in the LivingThing.java as following

● public abstract void dance(String dancingStyle);

2. Implement a concrete method in the Human.java that implements the dance() abstract method.

● public void dance(String ds){


System.out.println("Human dances..." + ds);
}

3. Compile and run the code

return to the top

Exercise 11.5: Interfaces (30 minutes)

Introduction:

If you are new to Interfaces, please read "Creating and Using Interfaces" section of the Java Progamming Tutorial.

Steps to follow:

1. Write Relation.java which is an Interface.

● cd \myjavaprograms
● mkdir interfaceexercise
● jedit interfaceexercise\Relation.java

package interfaceexercise;

public interface Relation {


public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Code-19.1: Relation.java

2. Write Main.java.

http://www.javapassion.com/javaintro1/javabasics1/ (79 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

● cd \myjavaprograms
● jedit interfaceexercise\Main.java

package interfaceexercise;

public class Main {


public static void main( String[] args ) {
Relation x = new Relation();
}
}
Code-19.2: Main.java

3. Compile Livingthing.java and Main.java.

● 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.

● C:\myjavaprograms>javac interfaceexercise\Relation.java interfaceexercise\Main.java


interfaceexercise\Main.java:5: interfaceexercise.Relation is abstract; cannot be instantiated
Relation x = new Relation();
^
1 error

5. Write a concrete class that implements Relation.

● cd \myjavaprograms
● jedit interfaceexercise\Line.java

package interfaceexercise;

public class Line implements Relation {


private double x1;
private double x2;
private double y1;
private double y2;

public Line(double x1,double x2,double y1,double y2){


this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public double getLength(){
double length = Math.sqrt( (x2-x1)*(x2-x1) +
http://www.javapassion.com/javaintro1/javabasics1/ (80 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

(y2-y1)*(y2-y1));
return length;
}

public boolean isGreater( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}

public boolean isLess( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}

public boolean isEqual( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}
}
Code-19.3: Line.java

6. Rewrite Main.java.

● cd \myjavaprograms
● jedit interfaceexercise\Main.java

package interfaceexercise;

public class Main {


public static void main( String[] args ) {

Line line1 = new Line(1.0, 2.0, 1.0, 2.0);


Line line2 = new Line(2.0, 3.0, 2.0, 3.0);

boolean b1 = line1.isGreater(line1, line2);


System.out.println("line1 is greater than line2: " + b1);
boolean b2 = line1.isEqual(line1, line2);
System.out.println("line1 is equal with line2: " + b2);

Line line3 = new Line(1.0, 5.0, 1.0, 5.0);


boolean b3 = line3.isEqual(line1, line3);
System.out.println("line1 is equal with line3: " + b3);

System.out.println("Length of line1 is " + line1.getLength());


System.out.println("Length of line2 is " + line2.getLength());
System.out.println("Length of line3 is " + line3.getLength());
http://www.javapassion.com/javaintro1/javabasics1/ (81 of 83)1/17/2006 3:49:08 PM
LAB-1005: Java Programming Intro I

}
}
Code-18.4: Main.java

7. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac interfaceexercise\*.java
● java interfaceexercise.Main

8. Verify the result as following:

● 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

Your own exercise:

1. Define your own package


2. Define your own interface called Beach.java and define the following methods

● String get YourFavoriteBeachSport():

return to the top

Exercise 12.1: Exception Handling (20 minutes)

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

http://www.javapassion.com/javaintro1/javabasics1/ (82 of 83)1/17/2006 3:49:08 PM


LAB-1005: Java Programming Intro I

package exceptionexercise;

public class ExceptionExample {


public static void main( String[] args ){

try{
System.out.println( args[1] );
} catch( ArrayIndexOutOfBoundsException exp ){
System.out.println("Exception caught!");
}
}
}
Code-20.1: ExceptionExample.java

2. Compile and run the code using a directory structure.

● cd \myjavaprograms
● javac exceptionexercise\*.java
● java exceptionexercise.ExceptionExample

3. Verify the result

● C:\myjavaprograms>java exceptionexercise.ExceptionExample
Exception caught!

return to the top

Company Info | Contact | Copyright 2005 Sun Microsystems

http://www.javapassion.com/javaintro1/javabasics1/ (83 of 83)1/17/2006 3:49:08 PM

Вам также может понравиться