Lab Experiments - Second Year - 2018-2019

Experiment 1: Introduction to Java Applets and Applications

  • Objectives:
    • Introduce Java's two kinds of programs: applications and applets.
    • Walkthrough the cycle of editing, compiling, debugging, and executing an application.
    • Use the NetBeans IDE to create and execute a Java program.
  • Prerequisites:
    • Java j2se6.0 (or later) compiler.
    • A Java-aware browser (Mozilla, Opera, Avant, or IE).
  • Introduction to NetBeans:
    • NetBeans is a free, open-source Integrated Development Environment (IDE) for software developers.
    • This tutorial aims to provide a simple walkthrough from opening NetBeans to compiling a simple Java application.

Part 1: Create a Java application

  • Create a Java application that displays “Hello World!” at the command prompt using a simple text editor.
  • Steps:
    1. Open Notepad (Start, Programs, Accessories, Notepad) or any other text editor and type the following code exactly as it appears:
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
2.  Save your file with the name `HelloWorld.java` on drive `C:\Temp` or any other suitable drive.
3.  Open a DOS command window (Start, Run, cmd).
4.  Change the directory to `C:\Temp` (or whatever drive you chose in step #2).
5.  Compile your program by typing `javac HelloWorld.java`.
6.  If the compilation goes well, the system should respond within a few seconds with another prompt (and no errors!). Check your directory for the new file named `HelloWorld.class`. This is the bytecode that the JVM will use to execute the program. (Note that it is about four times the size of your source code.)
7.  Execute the program by typing `java HelloWorld`.
  • Troubleshooting:
    • Syntax errors: You did not type the code exactly as specified. Check your code and pay attention to every character—this includes lower/upper case, punctuation, etc.
    • File errors: The file name containing the code must be the same as the class name with java extension, namely, HelloWorld.java (Java is case sensitive—pay attention to capital letters). Make sure that the file HelloWorld.class shows up in drive C:\Temp after the compilation.
    • Path errors: If the operating system cannot execute javac it could be that the OS does not know where it is installed (or the JDK was not installed correctly). You might need to modify your system PATH variable to include C:\ProgramFiles\Java\jdk1.6.0_06\bin entry (or other version), assuming JDK was installed on the C drive. You can verify the PATH by typing path at the DOS prompt and you can add the C:\Program Files\Java\jdk1.6.0_06\bin to PATH by typing at the command prompt set path=C:\Program Files\Java\jdk1.6.0_06\bin;%path%

Part 2: Create a new Java application

  • Start NetBeans, After starting NetBeans the interface should look similar to Figure 1.3.
  • Creating a new Java application
    • NetBeans does not currently allow the compilation of a single Java file, what this means is every application (even if it is a single Java file) needs to be part of a project. Create a new project by clicking the “New Project” icon () or by pressing ctrl + shift + N.
    • In the following dialog you are required to provide a name for your application (or accept the default name). The name that has been entered is “MyApplication”. You also have the option of letting NetBeans create the main method (the program’s entry point) in this class for you as well.
    • Click “Finish” when complete. Your application should load with the Main class as shown in Figure 1.5.
  • The leftmost panel of NetBeans displays your current project along with its source files. Additional source files created will be a part of the “myapplication” package (more on packages later).
  • Adding a new source (Class) file
    • It is possible to add more source files to the project as necessary; to add a new source file right click on the package name “MyApplication” then “new->Java Class”.
  • In the dialog that comes up enter the name of your Java Class (keep in mind the convention of class names beginning with an uppercase letter). The name of the new class entered is “Box”.
  • The code for this is below. Figure 1.8 a Box object can be created in the main class.
public class Box {

    double width;
    double height;
    double depth;

    public Box(double width, double height, double depth) {
        this.width = width;
        this.height = height;
        this.depth = depth;
    }

    double volume() {
        return width * height * depth;
    }
}
  • Now back in our Main class we can create a Box object and display its volume.
  • Running your application
public class Main {

    public static void main(String[] args) {

        Box myBox = new Box(10, 10, 10);
        System.out.println("Volume: " + myBox.volume());

    }

}
  • Providing that the source code is free from syntax errors, the application is now ready to be launched . Run your application by clicking the “Run Main Project Icon” () or by pressing “F6”. Observe the bottom panel of NetBeans for the programs output.
  • If you see the output similar to above then everything ran successfully, and that brings us to the end of this tutorial/introduction to NetBeans. This IDE has many options, feel free to experiment to see what you can discover so you can spend more time programming and less time typing (there is a difference, think about it).

Part 3: Create a new Java applet using a simple text editor

  • Problem Statement V: Create a Java applet using a simple text editor that adds two integers (you could keep adding more than two) and is viewed with the applet viewer.
  • Open Notepad or any other text editor (Start, Programs, Accessories, Notepad) and type the following code exactly as it appears below (pay attention to uppercase/lowercase, punctuation, etc. and don’t worry at this stage what it all means):
import java.applet.*;
import java.awt.*;

public class Addition extends Applet {

    int num1, num2, sum;
    String str;

    public void init() {
        num1 = 10;
        num2 = 20;
        sum = num1 + num2;
        str = "The sum is: " + sum;
        setBackground(Color.white);
    }

    public void paint(Graphics g) {
        g.drawString(str, 20, 30);
    }
}
  • Save your file with the name Addition.java on drive C:\Temp.
  • Open a DOS command window (Start, Programs, and Command Prompt).
  • Change the directory to C:\Temp.
  • Compile your program by typing javac Addition.java
  • If the compilation goes well, the system should respond within a few seconds with another prompt (and no errors!). Check your directory for the new file names Addition.class. This is the byte code that the JVM will use to execute the program.
  • Create the HMTL file in Notepad that contains the Addition.class applet Figure 1.11, and call it Addition.html:
<html>
<head>
<title>Addition Applet</title>
</head>
<body>
<applet code="Addition.class" width="300" height="200">
</applet>
</body>
</html>
  • View the applet with applet viewer Figure 1.12: at the DOS prompt type appletviewer Addition.html.

Part 4: Create a new Java applet

  • Create a Java applet that displays “Welcome to Java Programming!” using the NetBeans IDE.
  • Create a java source file named Welcome.java and save it in a folder named Lab 1 in C:\Temp\Lab 1.
import java.applet.Applet;
import java.awt.Graphics;

public class Welcome extends Applet {

    public void paint(Graphics g) {
        g.drawString("Welcome to Java Programming!", 25, 50);
    }
}
  • Start the NetBeans IDE: Start, Programs, NetBeans 6.8, and NetBeans IDE (you should also have a shortcut on the desktop).
  • Create a new project named Welcome Applet (select New->New Project, then select Java in General Category and Java Project with Existing Sources in the Projects category).
  • Click on Next, Figure 1.14, and name the project Welcome Applet and select location for project folder (C:\Temp\Lab 1 will do for now). Make sure the Set as Main Project check box is not selected (we will with other projects). Click on Next.
  • Click on Add Folder, Figure 1.16, and specify the folder where your source file Welcome.java is located (for me, it’s in C:\Temp\Lab 1).
  • Leave this at default. Just click Finish.
  • Press Shift-F6 to run file (you have created a Main for this project, so you can’t run it as a main project).
  • Here is the content of the html file that NetBeans generates for you. (Note the tag):
<html>
    <head>
        <title>Welcome Applet</title>
    </head>
    <body>
        <applet code="Welcome.class" width="300" height="200">
        </applet>
    </body>
</html>

Part 5: Create a new Java GUI Application

  • Create a Java GUI application using NetBeans that provides The user usage of Ohm’s Law formula. In electrical circuits, Ohm's law Figure 1.19, states that the current through a conductor between two points is directly proportional to the potential difference or voltage across the two points, and inversely proportional to the resistance between them, provided that the temperature remains constant.
  • The mathematical equation that describes this relationship is as shown in Figure 1.19.
  • V=IRV = IR
    • where $V$ is the potential difference measured across the resistance in units of volts;
    • $I$ is the current through the resistance in units of amperes and
    • $R$ is the resistance of the conductor in units of ohms. More specifically, Ohm's law states that the R in this relation is constant, independent of the current.
  • Start the NetBeans IDE: Start, Programs, NetBeans 6.8, NetBeans IDE (you should also have a shortcut on the desktop).
  • Create a Java application project and name it Ohm’s Law.
  • Select File ->New Project.
  • In the New Project dialog Figure 1.20, choose Java from Categories and Java Application from Projects.
  • Name the project Ohm’s Law, as shown in Figure 1.21. Select C:\Temp for project location (or any other location you want—you can copy the entire project folder to any other location you want). Uncheck Create Main Class check box. Click on Finish.
  • NetBeans creates several folders and files for you (a build.xml and manifest.mf file). You want to place the source file for your main class in the src folder. So open the Source Package, highlight the , right-mouse on it, select New and JFrame form as shown in Figure 1.22.
  • Name the Class Name OhmsLaw (note: no apostrophe or space in the name—it must be a valid Java identifier). Click on Finish. Java creates the source file names OhmsLaw.java and a GUI file OhmsLaw.form.
  • Build the form with controls from the Pallet so that it looks somewhat like Figure 1.24.:
  • You will need to bring a title JLabel from Swing Controls from the Palette. The JLabel has an icon of Ohm’s formula (a .png image to be provided).
  • The GUI contains a number of other JLabels, JTextFields, a JPanel that contains 4 JButtons. There are a number of different naming conventions for naming controls. For example indicative name of the control followed by the type of control. Such as, currentJTextField.
  • Name all controls as indicated in the following screen capture: Note that the GUI contains a JPanel named control JPanel which has a Grid Layout with 2 rows and 2 columns and which contains the 4 JButtons. The Print JButton has been disabled (uncheck the enabled property) for later implementation.
  • Double-click on the Calculate JButtons—this should take you in the Source code calculateJButtonActionPerformed method. Delete the comment line and type the following code:
  • Double-click on the Clear button and add the following code:
  • Double-click on the Quit button and add the following code:
  • Run the application by selecting Run->Run Main Project (F6) and check your results with the following:

Experiment 2: A First Utility Class

  • Objective: Learn how to define your own classes, with instance and class data members and instance methods.
  • Create a directory called exp02. All work for this lab and the assignment that follows should be saved in this directory.

To Complete Exp02

  • This is an individual lab. You may ask the lab tutor for help and you may consult with your neighbor if you are having difficulties.
  • In this lab, you will create two files, Rectangle.java and RectangleTest.java, that should be stored on your memory device. When done, copy the code and paste it into the file Exp02.txt followed by the output of the final run of the program.
  • When you have finished this lab, hand in a printed copy of your Exp02.txt document. This will be the grade for the lab.

Utility Class Basics

  • Review of terminology
    • Driver classes: Classes that contain a main method and drive a program.
    • Utility classes: Predefined classes utilized by programs and other classes (e.g., javax.swing.JFrame, java.lang.String, java.util.Date, java.util.Scanner, and java.text.DecimalFormat).
    • Class: A template that describes an object's data values and methods.
    • Members: Data and methods of a class.
    • Instance variables: Variable data members that belong to an object (each object has its own version).
    • Class variables: Data members that belong to the class (only one version shared by all objects).
    • Instance methods: Methods invoked on an object.
    • Class methods: Methods invoked on the class name.

The Rectangle Class

  • Define a Rectangle object for calculating area and perimeter.
  • The class should define data member’s height and width.
  • Since each Rectangle object stores its own values for these variables, height and width are instance variables.
  • The methods are the method's that determine the area and perimeter of a Rectangle object and are, therefore, instance methods.
  • The Rectangle class contains only instance variables and instance methods.

Class definition

  • Defining instance variables
class Rectangle {
    private double width;
    private double height;
}
  • Writing a method
    • Calculating and returning the area of a rectangle.
public class Rectangle() {
}
  • The body of a method consists of statements that are executed when the method is invoked. The statements that make up the body of the area method must calculate the area and return the area.

Testing the utility class

  • In order to use a Rectangle object, we must write a program with two classes - the utility class Rectangle and a driver class RectangleTest that will be used to test our code.
  • A program that declares and instantiates a Rectangle object
    • Rectangle myRect = new Rectangle();
  • can invoke the area method using the statement
    • double myArea = myRect.area();
  • which assigns to myArea the value returned by the area method.
  • Currently, you can access the values of width and height directly by joining the variable to the name of the object using the dot operator. Add the following statements to the end of the main method.
    • System.out.println("Width is " + myRect.width);
    • System.out.println("Height is " + myRect.height);
  • Modify the program by adding these statements at an appropriate place in the main method so that the area of myRect is no longer 0.
    • myRect.width = 2.0;
    • myRect.height = 3.3;

Access Modifier: private

  • Being able to directly access the instance variables of an object (Rectangle) from an outside class (RectangleTest) is considered to be an inappropriate practice in object-oriented languages. To prevent this, the instance variables of a class should be modified by the access modifier private.
  • The principle of making the data members of a class private and controlling access to the private data through the public methods is called encapsulation. Basically, this principle states that the integrity of an object is maintained by making the instance variables private,
  • private double width, height;
  • and, thereby, not allowing the user of the object to directly access the data, as in
    • `System.out.println(