14
Programming Refresher - MSc Computing & IT 1 Practical 1: Basic Java Programming Lecturers: Alvaro Miyazawa and Ana Cavalcanti Material Prepared by Rob Alexander The aims of this practical are: To get you up and running with both the command-line Java tools and the Eclipse IDE; To get you comfortable with the very basics of Java. Exercise 1: Hello World New Challenge: Compile and run a minimal Java program from the command line. The aim of this exercise to create, compile and run the simple ‘Hello World’ Java program on Linux or Windows (not both – one is enough), using a text editor and the JDK command-line tools. HelloWorld.java 1.1 Hello World on Linux Task a) Log on to Linux and open a terminal window; b) Create a directory called “PREF” in your home directory and store all the programming exercises there; [hint: mkdir] c) Open an editor (e.g., nedit) and type the code of HelloWorld.java; d) Save the source file as HelloWorld.java into the PREF directory; Be careful with upper and lowercases. e) Go to the command line, move to the directory where the file is saved; [hint: ls, cd] f) Compile your program, by typing: javac HelloWorld.java; If you have done it properly, a file HelloWorld.class should now appear in your directory and the compiler (i.e., the javac command) should not have printed any message (depending on compilers and/or versions a message might appear to say that no errors were found); If you receive an error message check that: /* * The HelloWorld class implements an application that * simply displays "Hello World!" out to the standard * output on the computer, i.e. the monitor */ public class HelloWorld { public static void main(String[ ] args) { System.out.println("Hello World!"); } }

Practical 1: Basic Java Programming - University of …alcc/PREF/practicals/PREF-2016-17... · Programming Refresher - MSc Computing & IT 1 Practical 1: Basic Java Programming Lecturers:

  • Upload
    vanphuc

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

Programming Refresher - MSc Computing & IT

1

Practical 1: Basic Java Programming

Lecturers: Alvaro Miyazawa and Ana CavalcantiMaterial Prepared by Rob Alexander

The aims of this practical are:

To get you up and running with both the command-line Java tools and the Eclipse IDE;

To get you comfortable with the very basics of Java.

Exercise 1: Hello World

New Challenge: Compile and run a minimal Java program from the command line.

The aim of this exercise to create, compile and run the simple ‘Hello World’ Java program on Linux orWindows (not both – one is enough), using a text editor and the JDK command-line tools.

HelloWorld.java

1.1 Hello World on Linux

Task

a) Log on to Linux and open a terminal window;

b) Create a directory called “PREF” in your home directory and store all the programming

exercises there; [hint: mkdir]

c) Open an editor (e.g., nedit) and type the code of HelloWorld.java;

d) Save the source file as HelloWorld.java into the PREF directory;

Be careful with upper and lowercases.

e) Go to the command line, move to the directory where the file is saved; [hint: ls, cd]

f) Compile your program, by typing: javac HelloWorld.java;

If you have done it properly, a file HelloWorld.class should now appear in yourdirectory and the compiler (i.e., the javac command) should not have printed anymessage (depending on compilers and/or versions a message might appear to say thatno errors were found);

If you receive an error message check that:

/** The HelloWorld class implements an application that* simply displays "Hello World!" out to the standard* output on the computer, i.e. the monitor*/

public class HelloWorld {public static void main(String[ ] args) {

System.out.println("Hello World!");}

}

Programming Refresher - MSc Computing & IT

2

o You saved the file with the right name;

o You saved the file in the same directory where you issued the javac command;

o You typed the file exactly as it appears above.

g) After successfully compiling the program, run it by typing: java –cp . HelloWorld

The “-cp .” option helps the java command to find your compiled file;

You should now see “Hello World!” on the screen. If so congratulations! You have now

compiled and run your first program in Linux.

1.2 Hello World on Windows

Task

a) Log on to windows;

b) Create a directory called “PREF” in H: and store all the programming exercises there;

c) Open Notepad and type the code of HelloWorld.java as per page 1;

d) Save the source file as HelloWorld.java into the PREF directory;

Be careful with upper and lowercases.

e) Open a DOS Command Prompt (Start > Run, then type cmd and click OK);

f) From the command line, move to the directory where the file is saved;

g) Compile your program, by typing: javac HelloWorld.java.

At this stage you may get a message like “javac is not recognized as an internal orexternal command […]” this means the Environment has not been set upproperly;

To fix this problem, type:

o path=C:\Program Files\Java\jdk1.7.xxx\bin

o Note jdk1.7.xxx needs to be replaced with the correct path;

o This command will tell the computer how to find the javac command.

Compile the program again by typing the command above.

h) If you receive an error message check that:

You saved the file with the right name;

You saved the file in the same directory where you issued the javac command;

You typed the file exactly as it appears above.

i) After successfully compiling the program, run it by typing: java –cp . HelloWorld

Remember the “-cp .” option helps the java command to find your compiled file;

You should now see “Hello World!” on the screen. If so congratulations! You have now

compiled and run your first program in Windows.

Programming Refresher - MSc Computing & IT

3

Exercise 2: Modifying Hello World

New Challenge: experience for yourself what is and what isn’t a valid Java program.

2.1 Introducing some changes

The best way to understand program code is to experiment by making incremental changes andobserving the result.

Accordingly, you will now make minor changes to your Hello World program and observe whether it canbe compiled and run successfully. In cases where it does not compile or run, please take note of anyerror messages displayed. See if you can relate them to the error you have introduced!

Task

Edit your program code to make the changes below one at a time, such that after eachchange you:

Save as HelloWorld.java;

Recompile source file (try to understand any error messages produced);

Run the class file (if the compile was successful);

Undo the change (so that you’re ready to try the next change).

The Source Code Changes:

a) Change the public keyword to public;

b) Change the class name from HelloWorld to Helloworld, or helloworld;

c) Remove one of the semicolons (;);

d) Remove /* from first line;

e) Change main to mmmain;

f) Modify the program to display your full name instead of “Hello World!“.

You should have noted that modifications (a) to (d) did not compile, as the changes invoked compile-time errors.

Change (e) should compile, but should not run. This is a runtime error (definition: either the programdoes nor run, or if it does it gives an incorrect result). Runtime errors are trickier to pinpoint thancompile-time errors; good design and thorough testing go a long way towards finding them.

Why do you think the Java Interpreter did not like change (e)?

Programming Refresher - MSc Computing & IT

4

2.2 Runtime Arguments

The header of the main method specifies a run time parameter array, i.e. String[ ] args.

public static void main(String[ ] args) {

This parameter array will receive and store any information entered into the command line, whenrequesting the program to run. This information can then be used within the program.

The tasks below will help you understand better the use and implementation of parameter passing.

Task

Before undertaking the tasks below, make sure you revert your Hello World java programback to its original source (as per page 1) and successfully compile it.

a) At the command line, type: java HelloWorld PREF;

Here we are giving some extra information (i.e. the string PREF);

This has no effect on the program’s behaviour, however, because we have

not coded how to use the information.

b) Modify the System.out.println statement such that you replace “Hello

World!” with args[0];

c) Compile it as usual (you should not get any error messages!);

d) Run the program by typing: java HelloWorld PREF;

Now instead of Hello World! you should see PREF displayed.

e) Run the program again by typing: java HelloWorld;

You should see an error message: Exception in thread "main"

java.lang.ArrayIndexOutOfBoundsException: 0 at

HelloWorld.main(HelloWorld.java:12);

This is because we did not send any information to be used by the

parameter;

In programming if you code to use a parameter, then you must make sure

that a corresponding argument is passed.

f) Run the program again by typing: java HelloWorld Hello World

Can you see “Hello World!” on the screen? Why not?

g) Modify your program to display two arguments. [hint: use args[0], args[1]]

Compile it;

Run by typing: java HelloWorld Hello World

The advantage of using arguments is that you can display different messages without having tomodify and recompile the program.

Programming Refresher - MSc Computing & IT

5

Exercise 3: Eclipse for Java

New Challenge: use Eclipse to compile and run the Hello World program

Eclipse for Java is an IDE that allows us to create, compile, run and debug Java programs. As anintroduction, this exercise asks you to create and run the ‘Hello World’ program as a project withinEclipse.

Note you can use Eclipse on Windows, Linux or Mac OX, however, the screenshots within this practicalare of the Windows version.

3.1 Starting Eclipse

Task

a) Start Eclipse for Java.

Before the IDE starts, Eclipse will prompt you to confirm the location of the workspace.

The workspace will be the default save location for Eclipse projects.

Task

a) Browse for your PREF folder;

b) Select the PREF folder to be the workspace;

c) Check the checkbox, to make PREF the default workspace folder;

d) Click OK button.

Programming Refresher - MSc Computing & IT

6

You should now see the Eclipse Start Page.

Now we want to go to the Eclipse Workbench (i.e. the work area of the IDE).

Task

a) Click: The go to workbench icon.

You will now see the Workbench, i.e. the IDE.

Programming Refresher - MSc Computing & IT

7

3.2 Starting a new project

Within Eclipse all work is contained within a project, regardless of whether the project contains a singleclass or multiple sub-projects. Accordingly we need to start a new java project

Task

a) Click: File (menu) > New > Java Project;

b) In the New Java Project dialogue window, type Hello World as the project name;

c) Click: Finish.

Programming Refresher - MSc Computing & IT

8

Hello World should now be listed in the Package Explorer Pane.

3.3 Starting a new class

Within this project we need to add a new class, in order to create a source file.

Task

a) Right Click: The Hello Project;

b) Click: New > Class;

The New Java Class dialogue will be displayed (see page 9).

Programming Refresher - MSc Computing & IT

9

c) Type: HelloWorld as the name of the class;

d) Check the method stub for public static void main(String[] args)

Note in this case we want a main method, so we might as well let Eclipse

auto code the header for us, i.e. method stub;

However in future you may have classes with no main method, so on those

occasions do not check this option.

e) Click: Finish.

Programming Refresher - MSc Computing & IT

10

The IDE will display ‘HelloWorld.java’ in the main panel. The Package Explorer panel will display

an expanded view of our project as well.

Notice that Eclipse in addition to the method stub also auto generates a block comment and an inlinecomment.

The block comment is for use in generating documentation for our class (JavaDoc);

The inline comment is to remind us to type some code into the body of the method.

You can safely delete these comments if you wish.

Many programmers prefer for line numbers to be displayed (especially when reviewing compile errormessages). To display line numbering we have to use the preferences dialogue.

Task

a) Click: Window (menu) > Preferences;

Programming Refresher - MSc Computing & IT

11

b) Expand: General > Editors > Text Editors;

c) Check: The Show line numbers check box;

d) Click: OK.

You should now see line numbering against the statements in the source file. Now we are ready toproceed by completing the source code.

Task

a) Modify the source code of your java file, so it is the same as that listed on page 1;

b) Click: File (menu) > Save All.

This will save all files that are in the project.

Programming Refresher - MSc Computing & IT

12

3.4 Compiling and running in Eclipse

Compiling and Running a Java application in Eclipse are automated under a simple Run command.

If the compile fails, Eclipse will not run the application and instead will report back the compile

errors;

If compile succeeds then Eclipse automatically will run the compiled class.

So let’s now try to compile and run the Hello world application.

Task

a) Click: Run (menu) > Run.

If compile succeeds then a console panel will be displayed beneath the source file:

Note the console panel can also accept command line input, whilst the application is still running.

Programming Refresher - MSc Computing & IT

13

Exercise 4: Swap Two String Variables

New Challenge: understand how variables and values are related.

Write a program that declares and initialises two string variables (to different values) and then swapsthe values of the variables.

To start with: String food = “Bread”String metal = “Steel”

After swap: Value of food is “Steel”

Value of metal is “Bread”

To achieve the swap you will have to use a third string variable (temp). Display the value of all threevariables before and after the swap.

Exercise 5: Simple Maths

New Challenges: use Java’s arithmetic operators; format floating point number output.

Write a program that allows the user to input two numbers and then applies the five arithmeticalcalculations to the two numbers.

In terms of output, display the figures in the form of a calculation. For example, if the inputs are 10 and2.5, then the output should be like:

10 + 2.5 = 12.510 – 2.5 = 7.510 * 2.5 = 2510 / 2.5 = 410 % 2.5 = 0

Do the calculations in the main method, and use a single variable for the results of the calculation.

Exercise 6: Area and Circumference of a Circle

New Challenge: get a constant value from the Java standard library.

Write a program to calculate the circumference and the area of a circle when a radius (in cm) is inputtedas an integer. The formulae you must apply are the following:

circumference = 2 x PI x radius

area = PI x radius2

Make use of PI from Java’s Maths package and output your results to two decimal places. If the radius

is 5cm then the output should look like:

The radius of the circle is 5 cmIts circumference is 31.42 cmAnd its area is 78.54 square cm

Programming Refresher - MSc Computing & IT

14

Exercise 7: Box Volume, perimeter & surface area

New Challenge: display output in a simple tabular form.

Create an application which allows the user to enter the dimensions of a box (as integers) and in returndisplays the volume of the box, the perimeter of the box and the surface area of the box. The formulaeyou should use are:

volume = length x height x width

surface area = (2 x length x height) + (2 x length x width)

+ (2 x width x height)

perimeter = (4 x length) + (4 x height) + (4 x width)

Given the following inputs:

Length = 10

Width = 8

Height = 5

Then your application should calculate the following results:

Volume = 400

Surface Area = 340

Perimeter = 92

Try to format your output display in a tabular layout.

Extra ExerciseIf you’re making good progress and have time to spare, maybe have a go at PREF practical sheet 2.