Faculty of Engineering & Information Technology

Software Engineering Department

Computer Science [2]

Lab 1:

Introduction ; First programs

Software Lab

Instructor: Eng.Omar Al-Nahal

Copyright March , 2010

WWW.PALINFONET.COM

Al-Azhar University – Gaza Faculty of Engineering & IT

Lab 1

Introduction; First Java programs Software Lab

1. Lab Objectives

In this Lab you will learn:

1. Learn how to install the Java SDK and JCreator IDE 2. Get introductory training on the JCreator IDE 3. Learn how to create Java program with JCreator & BlueJ 4. Compile and Run a Java Program

2. Prior to the Laboratory

Before you come to the lab, you should read about simple java programs instructions in the course and solve the homework below. You should also read this laboratory exercise in detail. Note that you must solve the homework.

• Read in book , Chapters 1 & 2 , Sections 1.13, 2.1,2.2,2.3,2.4 • Review the Theoretical Lesson.

3. Learn Java Programming by Examples

The Compilation Process

Figure: From Source Code to Running Program

Java Lab Manual Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 2 Faculty of Engineering & IT

Using the JCreator Integrated Development

What is an IDE? An IDE (Integrated Development Environment) is an application used to aid a in developing computer applications or programs.

JCreator uses the JAVAC compiler developed by Sun Microsystems TM to compile the Java source code into Java Byte code. It is just an editor that provides an easy to use editor and debugger for creating Java source code. In order to create the JAVA byte code you still need to use the Java Compiler developed by Sun Microsystems TM. Using JCreator To use JCreator the program must first be installed on the computer correctly.

Click on the JCreator icon on the desk top ( IF Dialog boxes appear click next and then ok until the IDE environment window appears). You should then have a window that looks like

Click on File then New then File (You will have a window that looks like Error! Reference source not found.)

Figure 2

Java Lab Manual 2 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 3 Faculty of Engineering & IT

For Every File in this class you must (These steps are modified each time you create a new File with names and folders that pertain to each File). Select an Empty File and Click Next

Figure 3

Provide a Location, Source Path, and Output Path. This should be a folder in your E:\ drive. You can change the path for each text box by clicking on the button next to each text box illustrated above. Give the File a Name1 (Here we are using HelloWorld as the File Name) Be sure that Location, Source and Output Path have the same folder as the File Name2.

Click Next then Next then Finish

In order to continue you must complete steps 1 through 3 of the Software Development Method found in your text booki.

Create the first file for your Java program. Click File then New then File (You should have the window shown in Error! Reference source not found.)

Fill in the name of the file in the Name and Click Finish Compile the File -> Click Build and then Compile File

Java Lab Manual 3 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 4 Faculty of Engineering & IT

Run File -> Click Build and then Execute File When you execute the program you will have a window that looks like that in Figure 1

Figure 1

File View Pane Package View Pane Output Pane Edit Window

Output Pane with a typical Error

Output Pane Without an Error

Java Lab Manual 4 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 5 Faculty of Engineering & IT

A Word about the Java Platform

The Java platform consists of the Java application programming interfaces (APIs) and the Java1 virtual machine (JVM). Java APIs are libraries of compiled code that you can use in your programs. They let you add ready-made and customizable functionality to save you programming time. The simple program in this lesson uses a Java API to print a line of text to the console. The console printing capability is provided in the API ready for you to use; you supply the text to be printed.

Java programs are run (or interpreted) by another program called the Java VM. If you are familiar with Visual Basic or another interpreted language, this concept is probably familiar to you. Rather than running directly on the native , the program is interpreted by the Java VM for the native operating system. This means that any computer system with the Java VM installed can run Java programs regardless of the computer system on which the applications were originally developed. For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating system should run equally well without modification on a Sun Ultra workstation with the Solaris operating system, and vice versa. Setting Up Your Computer Before you can write and run the simple Java program in this lesson, you need to install the Java platform on your computer system. The Java platform is available free of charge from the java.sun.com web site. You can choose between the Java® 2 Platform software for Windows 98/2000/XP and 7 or for Solaris. The download page contains the information you need to install and configure the Java platform for writing and running Java programs.

Note: Make sure you have the Java platform installed and configured for your system before you try to write and run the simple program presented next.

Writing a Program The easiest way to write a simple program is with a text editor. So, using the text editor of your choice, create a text file with the following text, and be sure to name the text file ExampleProgram.java. Java programs are case sensitive, so if you type the code in yourself, pay particular attention to the capitalization.

//A Very Simple Example class ExampleProgram { public static void main(String args [ ]){ System.out.println("I'm a Simple Program"); } }

Here is the ExampleProgram.java source code file if you do not want to type the program text in yourself. Compiling the Program A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM. The Java compiler is invoked at the command line on Unix and DOS shell operating systems as follows: javac ExampleProgram.java

Java Lab Manual 5 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 6 Faculty of Engineering & IT

Note: Part of the configuration process for setting up the Java platform is setting the class path. The class path can be set using either the -classpath option with the javac compiler command and java interpreter command, or by setting the CLASSPATH environment variable. You need to set the class path to point to the directory where the ExampleProgram class is so the compiler and interpreter commands can find it. See Java 2 SDK Tools for more information.

Interpreting and Running the Program

Once your program successfully compiles into Java bytecodes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built in such as Netscape or . Interpreting and running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent machine codes so your computer can understand and run the program.

The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows: java ExampleProgram At the command line, you should see: I'm a Simple Program Here is how the entire sequence looks in a terminal window:

Common Compiler and Interpreter Problems If you have trouble compiling or running the simple example in this lesson, refer to the Common Compiler and Interpreter Problems lesson in The Java Tutorial for troubleshooting help.

Code Comments Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file, to comment-out lines of code to isolate the source of a problem for debugging purposes, or to generate API documentation. To these ends, the Java language supports three kinds of comments: double slashes, -style, and doc comments.

Double Slashes Double slashes (//) are used in the C++ programming language, and tell the compiler to treat everything from the slashes to the end of the line as text.

//A Very Simple Example class ExampleProgram { public static void main(String[] args){ System.out.println("I'm a Simple Program"); } }

C-Style Comments Instead of double slashes, you can use C-style comments (/* */) to enclose one or more lines of code to be treated as text. /* These are C-style comments */ class ExampleProgram { public static void main(String args []){ System.out.println("I'm a Simple Program"); } }

Java Lab Manual 6 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 7 Faculty of Engineering & IT

Doc Comments To generate documentation for your program, use the doc comments (/** */) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation. /** This class displays a text string at * the console. */ class ExampleProgram { public static void main(String args []){ System.out.println("I'm a Simple Program"); } }

Class

• Every java program includes at least one class definition. The class is the fundamental component of all Java programs.

• A class definition contains all the variables and methods that make the program work. This is contained in the class body indicated by the opening and closing braces.

Braces

• The left brace ( { ) indicates the beginning of a class body, which contains any variables and methods the class needs.

• The left brace also indicates the beginning of a method body.

• For every left brace that opens a class or method you need a corresponding right brace ( } ) to close the class or method.

• A right brace always closes its nearest left brace. main() method

• This line begins the main() method. This is the line at which the program will begin executing.

String args[]

• Declares a parameter named args, which is an array of String. It represents command-line arguments.

System.out.println

• This line outputs the string “I'm a Simple Program!” followed by a new line on the screen.

Java Lab Manual 7 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 8 Faculty of Engineering & IT

Some common escape sequences.

Escape sequence Description \n Newline. Position the screen cursor at the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the current linedo not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example,

System.out.println( "\"in quotes\"" );

displays

"in quotes"

Displaying multiple lines with method System.out.printf.

1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box. 3 4 public class Welcome4 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.printf( "%s\n%s\n", 10 "Welcome to", "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome4

Welcome to Java Programming!

Java Lab Manual 8 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 9 Faculty of Engineering & IT

Displaying Text in a Dialog Box by using JOptionPane

Although the programs presented in this book thus far display output in the command window, many Java applications use windows or dialog boxes (also called dialogs) to display output.

For example, World Wide Web browsers such as Netscape or Internet Explorer display Web pages in their own windows. E-mail programs allow you to type and read messages in a window. Typically, dialog boxes are windows in which programs display important messages to the user of the program.

Class JOptionPane provides prepackaged dialog boxes that enable programs to display windows containing messages to users—such windows are called message dialogs.

Figure 2.10. Using JOptionPane to display multiple lines in a dialog box. 1 // Fig. 3.17: Dialog1.java 2 // Printing multiple lines in dialog box. 3 import javax.swing.JOptionPane; // import class JOptionPane 4 5 public class Dialog1 6 { 7 public static void main( String args[] ) 8 { 9 // display a dialog with the message 10 JOptionPane.showMessageDialog( null, "Welcome\nto\nJava" ); 11 } // end main 12 } // end class Dialog1

Figure 2.10 displays the string "Welcome\nto\nJava" in a message dialog.

Line 3 indicates that our program uses class JOptionPane from package javax.swing.

This package contains many classes that help Java create graphical user interfaces (GUIs) for applications. GUI components facilitate data entry by a program's user, and formatting or presenting data outputs to the user. In method main, line 10 calls method showMessageDialog of class JOptionPane to display a dialog box containing a message. The method requires two arguments.

The first argument helps the Java application determine where to position the dialog box. When the first argument is null, the dialog box appears in the center of the computer screen. The second argument is the String to display in the dialog box.

Method showMessageDialog is a special method of class JOptionPane called a static method. Such methods often define frequently used tasks that do not explicitly require creating an object. For example, many programs display messages to users in dialog boxes. Rather than require programmers to create code that performs this task, the designers of Java's JOptionPane class declared a static method for this purpose. Now, with a simple method call, all programmers can make a program display a dialog box containing a message. A static method typically is called by using its class name followed by a dot (.)

Java Lab Manual 9 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 10 Faculty of Engineering & IT

4. Activities/Exercises

• Write a program TenHelloWorlds.java that prints "Hello, World" ten times.

• Write an application that displays a checkerboard pattern, as follows:

5. Activities/Homework

• Write an application that displays a box, an oval, an arrow and a diamond using asterisks (*), as follows:

** *** ********** ** * ** ** *** ** ** ** *** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ***** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** ** ** ** ** ** *** ** ** *** *** ** *** ********** * *

• I typed in the following program. It compiles fine, but when I execute it, I get the error java.lang.NoSuchMethodError: main. What am I doing wrong? .

public class Hello { public static void main() { System.out.println("Doesn't execute"); } }

Java Lab Manual 10 Eng.Omar H. Al-Nahal Al-Azhar University – Gaza 11 Faculty of Engineering & IT

6. Web Resources

# The Deitel & Associates home page for Java How to Program, Sixth Edition.

www.deitel.com/books/jHTP6/index.html

# Sun's home page for Java technology. Here you will find downloads, reference guides for developers, community forums, online tutorials and many other valuable Java resources.

www.java.sun.com/j2se The home page for the Java 2 Platform, Standard Edition.

# The home page for JCreatora popular Java IDE. JCreator Lite Edition is available as a free download. A 30-day trial version of JCreator Pro Edition is also available.

www.jcreator.com

# The home page for the BlueJ environmenta tool designed to help teach object-oriented Java to new programmers. BlueJ is available as a free download. www.blueJ.org

# Free Software Online:-

- JDK-V5 Java SE Development Kit

www.palinfonet.com/pin/java/jdkv5.exe

- JCreator – V4 JCreator is a powerful Free IDE for Java

www.palinfonet.com/pin/java/jcpro400.exe

- Java JCreator: Register with the following

Name: mazuki

Serial: MPEXF3-CE2759-WZ9P34-5YFAZW-MQYK1C-89B44V-G30B5E-P8YNJP

# Free Book - Java How to Program, Sixth Edition

www.palinfonet.com/pin/cs3.htm

# Arab Academy for Information Technology

اﻷآﺎدﻳﻤﻴﺔ اﻟﻌﺮﺑﻴﺔ ﻟﺘﻜﻨﻮﻟﻮﺟﻴﺎ اﻟﻤﻌﻠﻮﻣﺎت

www.palinfonet.com

Java Lab Manual 11 Eng.Omar H. Al-Nahal