Change This to the Name of Your Resource

Change This to the Name of Your Resource

Title / Getting started with Java
Description
Keywords / Java, Netbeans
Objectives
Author / Jin Sa
Organisation
Version / Version x
Date / 30 July 2010
Copyright

Introduction

This unit contains a summary of the contents covered in Liang (Sixth edition) part 1: fundamentals of programming.

It is assumed that you have programming experience (although not necessarily in Java). Therefore you should be familiar with basic programming concepts such as data type, control statement, block and documentation style.

The objectives of this unit are:

  • To know Java’s advantages
  • To know the relevant terminologiesAPI, IDE, and JDK
  • To write simple Java programs
  • To know the basic syntax of a Java program and methods
  • To understand the Java runtime environment
  • To know how to group classes into packages
  • To know how to use the Scanner class
  • To know how to create, compile and run Java programs using an IDE

Terminology

Java is a relatively new programming language. It was introduced to the public in 1995. Java has gone various changes since its creation. The most recent Java technology is referred to as Java 2 Platform. It is organised in three groups:

  • Java 2 Platform, Standard Edition (J2SE)
  • Java 2 Platform, Enterprise Edition (J2EE)
  • Java 2 Platform, Micro Edition (J2ME)

We will focus on J2SE. There are many versions of J2SE. For each version of J2SE, Sun releases a Java Development Toolkit (JDK). For J2SE, we have JDK 6.0 or above, also known as JDK 1.6. JDK consists of a set of programs for compiling and executing Java programs. These programs can be invoked at the command line. They do not have a GUI front.

There are a number of Integrated Development Environments (IDE) for JDK. In this module, we will use NetBeans ( NetBeans incorporates the development tools of the JDK into one convenient GUI-based program. Other Java IDEs are also available, for example, Borland JBuilder and IBM Eclipse. In this module we will use NetBeans.

Java’s application programming interface (API) contains predefined classes and interfaces for developing java programs. You can find the latest version of API from

Developing and running Java programs

In this section, we will first illustrate the process of developing and executing a Java program. We will then explain how to do this using NetBeans.

A simple Java program

Java programs can be either written as standalone applications or applets. In this module, we will focus on applications.

The following is a simple Java application program displaying the message “Welcome to Java!”.

//This program prints Welcome to Java!

public class Welcome {

public static void main(String[] args) {

System.out.println("Welcome to Java!");

}

}

Developing and running Java programs using NetBeans

You can develop Java programs without using an IDE. As IDEs are often used in industry, in this module, we will develop our programs using NetBeans, which is an IDE that incorporates the Java compiler, the Java interpreter and a number of other tools together with file and project management for developing and executing Java programs.

In NetBeans, we normally work with projects. For example, you can create a project for all the programs related with this unit, and later on you can create a project for your assignment. When a project is created, we need to tell NetBeans the name of the project and the location for storing all the files.

Student activity2.1:

Following this link a tutorial on how to create a project, a java program and how to compile and run it.

After completing the above activity, you should have a Java program called HelloWordApp. Now let’s try to create your own Java program.

Student activity 2.2:

Create the following Welcome program using NetBeans in a project called OOPjava.

//This program prints Welcome to Java!

public class Welcome {

public static void main(String[] args) {

System.out.println("Welcome to Java!");

}

}

When you create the project, make sure that you select a suitable project location and the correct name for the class, e.g. startjava.Welcome. See the screen shot below as an example.

(Note that the actual “look and feel” of the window may be slightly different from the most current version.)

staratjava is the name of the package and Welcome is the name of the class. We will explain more about these concepts later in this unit. After clicking on Finish, you should see something like the following.

Enter the program code in the “main” method. Compile and run the program.

The “main” method is the method that the Java run time system will first trigger when running a Java application program.

To compile or to run the program, you can either do it from the IDE menu as explained in Student activity 2.1, or you can compile or run a particular file. Move the cursor to the file you want to compile or run, right click the mouse and choose “Compile File” or “Run File” as shown in the screen shot below.

After running the program, you should see something like the following.

Some basic language features

In this unit, we will introduce some basic language features. This module will mainly focus on the object-oriented aspect. If you are unfamiliar with the basic programming concepts such as primitive data types, expressions and control statements, you should read part 1 in Liang or Sun’s tutorial on Java (Language basics

for a more comprehensive and in-depth description.

Packages and the import statement

Everything in Java has to be part of a class. Given any large system, there will be a large number of classes. There are also many pre-defined classes that come with the Java standard class library. In order to be able to manage the large number of classes, packages are used to group classes.

Packages are hierarchical, and you can have packages within packages. For example, java.lang.Math indicates that Math is a class in the package lang and that lang is a package in the package java.

Java expects a one-to-one mapping of the package name and the file system directory structure. For example, if we have a package called “startjava”, we should have a directory called “startjava”. If we use Netbeans, the corresponding directories are automatically created.

Every class in Java belongs to a package. The class is added to the package when it is compiled. To put a class in a package, you need to add the following line as the first non-comment and non-blank statement in the program:

package packagename;

If there is no package statement defined in a class, the class is put in a default unnamed package.

When you created the “Welcome” example using NetBeans, it puts all the “Welcome”programs in a package called “startjava”. You may have noticed the statement “package javastart” at the top of your Welcome program. You can create more than one package in a project. To create a package in a project, you move the cursor over to the name of the project, right click, and select “New” and then “Java Package…” as shown below.

To use a class from a package, there are two ways:

  • One is to use the fully qualified name of the class. For example, the fully qualified name for the Scanner class is java.util.Scanner.
  • The other is to use the “import” statement. For example, to import the Scanner class from the java.util package, you use “import java.util.Scanner;”. You can also import all the classes in a package. For example, “imports java.util.*;”.
  • The import statement tells the compiler where to locate the classes.

Input using Scanner

We now use the “Welcome” example to illustrate how to use Scanner to read from the keyboard. Let’s modify our “Welcome” program by

  • adding the import statement, “import java.util.Scanner;” at the top of the program just below the package name to import the Scanner class;
  • adding the following lines to our main method.

String name="";

Scanner in = new Scanner(System.in);

System.out.println("Enter your name:");

name=in.next();

System.out.println("Welcome to Java!"+name);

In the program above, we have created an object of the Scanner class, called in. This object enables us to read input from the keyboard. If we run the above program now, we will see the following output as shown at the bottom window in the next screenshot. It prompts you with “Enter your name:”, you can enter your name, e.g. Alex, the program will then display “Welcome to Java! Alex”.

Example 1: Calculating total – using loop

We will now define a few simple Java programs so that you can become familiar with some language features.

Let’s add a new class, called Total, to our startjava package. This program reads a number of integers from the keyboard and adds them up until a negative number is read. It then prints out the total.

The program below is fairly self-explanatory. You should pay particular attention to the use of “Scanner” and the “while” loop.

package startjava;

import java.util.Scanner;

//we need to use a scanner, so we import it from //java.util.Scanner

public class Total {

public static void main(String args[]){

Scanner in = new Scanner(System.in);

//create an instance of the Scanner

int n,sum=0;

//n is used to store the number read from the keyboard

//sum is used to keep the current total

n=in.nextInt();

//use the scanner to read an integer from

//the keyboard, and assign it to the variable n.

while (n>=0){

System.out.print(n+" ");

//print out the number n and followed by a space

sum=sum+n;

n=in.nextInt();

//read the next integer from the keyboard

}//while

System.out.println("The total sum is "+sum);

}//main

}//Total

Student activity 2.3:

Implement, compile and run the program and experiment with various different input values.

Modify the program so that it first asks the user to input the total number of integers to be entered. You should use a “for” loop instead of a while loop.

Possible solution can be found here.

Example 2: Option menu – using switch

This example displays a menu of module titles. It then prompts the user to choose one of these modules by selecting a number. The program then prints the title of the module associated with that number.

Here is a possible solution. Pay particular attention to the use of the “switch” statement. After each case statement, we have a “break” statement. The “break” statement moves the control to the end of the switch statement.

package startjava;

import java.util.Scanner;

public class OptionMenu {

public static void main(String [] args){

Scanner in = new Scanner(System.in);

// Display the menu

System.out.println("1\t Java Programming");

System.out.println("2\t Soft Engineering");

System.out.println("3\t Requirement Engineering");

System.out.println("4\t Project Management");

System.out.println("Please enter your choice:");

//Get user's choice

int choice=in.nextInt();

//Display the title of the chosen module

switch (choice) {

case 1: System.out.println("Java Programming");

break;

case 2: System.out.println("Soft Engineering");

break;

case 3: System.out.println("Req Engineering");

break;

case 4: System.out.println("Proj Management");

break;

default: System.out.println("Invalid choice");

}//end of switch

}//end of the main method

}//end of class

If you compile and run this program, here is an output from running the program:

1 Java Programming

2 Soft Engineering

3 Requirement Engineering

4 Project Management

Please enter your choice:

3

Req Engineering

Student activity 2.4:

Modify the OptionMenu example to add more module titles.

Explore the effect of removing one or more of the break statement within the switch block. Summarise the effect in one or two sentences and post your summary to the module forum.

Think of a situation that would be suitable for not having the break statement at the end of a case statement.Write a simple program to capture this situation and post your program to the module forum, together with a brief commentary on why it is suitable not to have the break statement at the end of a case statement.

Example 3: An Example with an array

In this example, the program includes an array of 10 integers. It asks the user to enter a list of 10 student marks; it then calculates and displays the average mark.

Here is a possible solution. You should pay particular attention to declaring, creating and accessingthe array.

package startjava;

import java.util.Scanner;

public class StudentMarks {

public static void main(String [] args){

Scanner in=new Scanner(System.in);

// creates an array of integer to hold the 10 marks.

int [] marks = new int[10];

int sum=0;

//read 10 numbers from the keyboard using a loop

System.out.println("Enter 10 marks:");

for (int i=0;i<10;i++) {

marks[i]=in.nextInt();//assign the mark to the array

//we assume marks will be entered correctly

sum=sum+marks[i];//add mark to the current total

}//end of for

//display all the numbers and prints out the average

System.out.println("The numbers entered are:");

for (int i=0;i<10;i++)

System.out.print(marks[i]+" ");

System.out.println(); //to start a new line

System.out.println("The average mark is: "+ sum/10);

}//end of main

}//end of class

Student activity2.5:

Modify the above program so that it prints the highest markand the lowest mark.

Hint: If you find it difficult to make a start on this. Here is ahint.

A possible solution is here.

The next activity may be slightly harder at this stage for some students. If you cannot do it at this stage, do not worry. I suggest you move onto the next section. You may wish to come back to tackle this activity later on during the course when you become more confident with programming in Java.

(Harder) As well as displaying the highest mark and the lowest mark, display the number of occurrence of each mark.

For example, if the ten marks are: 8, 21, 40, 40, 56, 65, 65, 70, 72, 92. The output should be:
highest=92
lowest=8
Occurrences:
8 is 1
21 is 1
40 is 2
56 is 1
65 is 2
70 is 1
72 is 1
92 is 1

A possible solution is here.

Example 4: An example with a method

Let’s now rewrite the StudentMarks program so that it defines and uses three methods: enter the marks, sum the marks and print the marks.

StudentMarks2 presents a possible solution. The focus of this example is the use of methods. In this example, we have introduced the concepts of attributes and static members. These concepts will be explained in detail later in unit 7 “Classes and objects”.

package startjava;

import java.util.Scanner;

public class StudentMarks2 {

// declare two attributes to store the 10 marks and to

// create an instance of Scanner to read from the keyboard.

static int [] marks = new int[10];

static Scanner in=new Scanner(System.in);

public static void main(String [] args){

enterMarks(); // invoke the enterMarks method

int sum=sumMarks(); //invoke the sumMarks method.

//This method returns a value. We assign the value to a local variable

//printMarks(); //invoke the printMarks method

System.out.println(); //to start a new line

System.out.println("The average mark is: "+ sum/10);

}//end of main

//The following define three methods

/* The enterMarks method uses a for loop to enter 10 marks.

* During each iteration of the loop,

* we use in (an instance of Scanner)

* to read an integer from the keyboard. */

static void enterMarks() {

System.out.println("Enter 10 marks:");

for (int i=0;i<10;i++) {

marks[i]=in.nextInt();//assign the mark to the array

//we assume marks will be entered correctly

}//end of for

}//enterMarks

/* The sumMarks method uses a for loop to

add up the marks in the array. */

static int sumMarks() {

int total=0;

for (int i=0;i<10;i++) {

total=total+marks[i];

}//end of for

return total;

}//sumMarks

}//end of class

Student activities 2.6

Implement and modify the above program to include a printMarks method. It prints out the values on the array of marks.

Hint: An outline of the method can be found here.

Student activities 2.7:

(Slightly hard) Modify the StudentMarks2 example by adding one more method: findOccurrences(…).

A possible solution is here.

In this example, we have three separate methods processing through the array of marks. An alternative solution is to have simply one method that processes through the array once and it returns all the information such as the sum, the highest mark and the lowest mark. However, at the moment, we have not covered how to bundle a collection of information together yet. This will be covered in unit 7 “Classes and Objects”.

Summary

In this unit, we have

  • introduced some well known terminology related to programming in Java
  • explained how to use NetBeans
  • demonstrated how to write simple Java programs using NetBeans
  • introduced the concept of package
  • illustrated how to use the Scanner class for input
  • covered some basic program concepts including array, loop, conditional statement and methods.

Other useful readings:

Introducetion to Java Programming – Comprehensive” by Daniel Liang

Most textbooks on Java will be useful for the contents covered in this unit. The following online materials are also relevant:

Getting started:

Language basics:

Using NetBeans: