Your First Java Program

From CompSciWiki
Revision as of 15:22, 20 March 2007 by Umhieb34 (Talk | contribs)

Jump to: navigation, search

Chapter 2: Your First Java Program

Introduction

In chapter 1, you learned what programming is. This chapter will cover the basics of Java programming and give you enough information to write your first Java program.

Overview

Learn how to write your first Java Program.


Anatomy of a Java Program

Every programming language has its unique syntax and structure. This section will introduce you to the anatomy of a Java program.

Example

This is an example of a Java program:

public class JavaProgram
{
  public static void main(String args[]) 
  {
    System.out.println("This is what a Java program looks like");
  }
}

Classes

The first line is called the class header. A class groups together the components of an object. Don't worry about what an object is right now. Objects will be covered in COMP1020. For now, just think of a class as a container for the rest of your code. After the class header, we write an opening curly brace followed by a closing curly brace. When you create a new program, you will first declare a class. Most of your remaining code will then be contained inside of the two braces.

In the above example, JavaProgram is the name of the class. When you save a Java file it must be named classname.java (where classname is the name of the class). In the example, we would save the file as JavaProgram.java


Methods and the Main Method

A method is a block of code that performs a certain task. To declare a method, we write a method header followed by an opening curly brace and a closed curly brace.

Here is an example of a method. This method performs the task of printing a message to the screen.

public int printMessage(String message)
{
  System.out.println(message);

  return 1;
}

Now, we will explain the components of a method header.

  • Scope: The keyword public allows other classes to call our method. Alternatively, we could have used the keyword private to deny other classes access to our method.
  • Return type: When our method completes it can return data to the caller (the statement that called our method). We must declare the type of data that our method returns. In the printMessage method, we used the keyword int to declare that our method returns data of type integer. If we do not want our method to return anything we can use the keyword void.
  • Name: We must give our method a unique name. The name of the method shown above is printMessage.
  • Parameters: We can pass data to a method. The data that we pass to a method are called parameters. Parameters are declared inside of round brackets. Each parameter must have a type and a name (just like when we declare a variable). If we do not want to have any parameters, we just put a set of round brackets with nothing inside.


The third line of the example is the header of the main method. The main method is a special method in Java. Every Java program must have a main method. The program begins execution in the main method.

The main method must be declared inside of a class. After the header of the main method (and all other Java methods), we write opening and closing curly braces (just like when we define a class).

The meaning of static will be discussed in a later chapter.


Statements

An instruction in Java is called a statement. A statement is a single line of code that performs a task. All statements must end with a semicolon. In the example program, the fifth line is a statement that prints "This is what a Java program looks like" to the screen.


Packages and the import Statement

A package is used to group a set of classes together. When you create a new class it will be placed in the default package. There are times that you will want to use classes that are in a different package. The import statement will allow you to use a class that is in another package.

The general syntax of an import statement is:

import package.class;

where package is the name of the package you want to import, and class is a class within that package.

Example

import javax.swing.JOptionPane;

Here we import the JOptionPane class which is part of the javax.swing package. Now our program will be able to use JOptionPane.


We can specify that we want to include all the classes of a package by using the * symbol as demonstrated below.

import javax.swing.*

This will import all classes from the javax.swing package.

import statements should be placed at the very beginning of the file (above the class header).


Case Sensitivity

Java is a case sensitive programming language. This means that it distinguishes between letters that are typed in upper case and letters that are typed in lower case. For example, if you type Main, this is not the same as typing main.


Naming Guidelines

How you name your classes, variables, and methods is largely a matter of convention. Here we will discuss some of these conventions.


A class name should be a noun that starts with a capital letter. The first letter of each word should also be capitalized.

public class Tetris
public class DayPlanner


A method name should be a verb that indicates what the method does. The first letter of each word (except the first word) should be capitalized.

public void rotate()
public int getCurrentPosition()


A constant name should be a noun with all capital letters, and an underscore should be used between words.

public static final double PI = 3.14159265l;
public static final int MELTING_POINT = 0;


A variable name should be a noun. The first letter of each word (except the first word) should be capitalized.

int day;
String firstName;


Your First Java Program

Now that you know a bit about the anatomy of a Java program, you can write your first program. Below is a simple program called HelloWorld. This program does only one thing. It prints "Hello World!" to the screen. This type of program is commonly used when introducing someone to a programming language.

To run this program, copy the text from the box below and paste it into TextPad. Save the file as "HelloWorld.java". Then compile the program by selecting Compile Java from the Tools menu. Finally, run the program by selecting Run Java Application from the Tools menu.

In the console at the bottom of TextPad, you should see the "Hello World!" message. You have successfully run your first Java program!

public class HelloWorld 
{
  public static void main(String args[]) 
  {
    System.out.println("Hello World!");
  }
}

Comments

We can add comments to our source code for better organization and to help someone else understand what our code does.

Take a look at the example below.

/**
 * PrintTemp
 *
 * This program shows you how to print the contents of a variable
 *
 * COMP 1010
 * Instructor:   Compsci Wiki
 * Assignment:   Assignment 0, question 0
 * @author       Compsci Wiki
 * @version      
 */

public class PrintTemp
{
  public static void main(String args[]) 
  {
    int temp; //declare an variable of type integer

    temp = 25; //store 25 in a variable

    System.out.println("The temperature is currently " + temp + " degrees Celsius."); //print the temperature to the screen
  }
}

We can use // before a single line to indicate that this line is a comment. If we want to include a comment that is longer than one line, we can put /* at the beginning of the comment and */ at the end.

When a program is compiled, the compiler ignores the comments. This means that comments do not affect the program. So, why do we use comments? Comments are only for you and any one else that reads your source code. Imagine someone gives you the source code to a long, complex program which does not contain any comments. If you wanted to understand the code you would have to spend a lot of time going through each line and figuring out what everything does. If this program had comments that explained the purpose of each class, method, and block of code it would make understanding the code a lot easier.


Output Using System.out.

Java uses System.out. for program output. This section will show you how to use System.out.println and System.out.print to print to the screen.

Printing text to the screen

To print text to the screen you can use:

System.out.println("text");

or

System.out.print("text");

Whatever you put inside of the quotes will be printed to the screen. The difference between System.out.println() and System.out.print() is that System.out.println() will print a newline after the text unlike System.out.print() which just prints the text.

Example 1

This program prints the message "Go Bisons!" to the screen.

public class Output1
{
  public static void main(String args[]) 
  {
    System.out.println("Go Bisons!");
  }
}

Example 2

This program prints the message "Go Bisons!" to the screen three times.

public class Output2
{
  public static void main(String args[]) 
  {
    System.out.println("Go Bisons!");
    System.out.println("Go Bisons!");
    System.out.println("Go Bisons!");
  }
}

Output

Go Bisons!
Go Bisons!
Go Bisons!

Example 3

Now, lets compare this program to the one in example 2. This program also prints the message "Go Bisons!" to the screen three times. However, it does not print a new line after each message.

public class Output3
{
  public static void main(String args[]) 
  {
    System.out.print("Go Bisons!");
    System.out.print("Go Bisons!");
    System.out.print("Go Bisons!");
  }
}

Output

Go Bisons!Go Bisons!Go Bisons!

Using Variables with System.out.println()

You can also print the contents of a variable by using System.out.println()

Example 1

public class PrintVariable
{
  public static void main(String args[]) 
  {
    int num;

    num = 5;

    System.out.println(num);
  }
}

Output

5

In this example we create an integer called num and use it to store the number 5. We then print the contents of num by using System.out.println(). Notice that we did not put quotes around num. Variables do not need to be put in quotes. Only a string of text needs to be put inside of quotes.

Example 2

In this example we will show you how to print a string of text and a variable.

public class PrintTemp
{
  public static void main(String args[]) 
  {
    int temp;

    temp = 25;

    System.out.println("The temperature is currently " + temp);
  }
}

Output

The temperature is currently 25

Example 3

We can also put the variable in the middle of a sentence.

public class PrintTemp
{
  public static void main(String args[]) 
  {
    int temp;

    temp = 25;

    System.out.println("The temperature is currently " + temp + " degrees Celsius.");
  }
}

Output

The temperature is currently 25 degrees Celsius.

We use a + sign to join a string of text and a variable.


Input Using JOptionPane

JOptionPane gives you the ability to create dialogs. A dialog is a window that pops up and either displays a message or requests input from a user. This section will show you how to use JOptionPane to get input from a user.

Input Box

Example

In this example we prompt the user to enter their name, store it in a variable (see section on variables), and print their name to the screen using System.out.

import javax.swing.JOptionPane;

public class Input
{
  public static void main(String args[]) 
  {
    String name;
    
    name = JOptionPane.showInputDialog("Enter your name:");

    System.out.println("Hello " + name);
  }
}


We will now describe the important lines in this program.


  • import javax.swing.JOptionPane;

JOptionPane is part of the javax.swing package. To give our class access to JOptionPane we have to use the import statement.


  • name = JOptionPane.showInputDialog("Enter your name:");

The method on the right of the equals sign pops up a dialog with the message "Enter your name:" and an input box for the user to enter their name. Once the user enters their name and hits the OK button, the method returns with the string that was entered in the input box. This string is stored in the name variable.

Input1.png


  • System.out.println("Hello " + name);

Now that we have stored the user's name, we can use System.out.println to print "Hello name", where name is what the user entered in the input box.


Variables and Literals

This article will introduce you to the topic of variables; naming, and syntax will be the main focus.

Introduction

Naming is a fundamental component in programming. In programs, names are used to refer to many sorts of things. In order to properly use these things, we must understand the rules for giving names and the rules to which how we could use these things. That is, a programmer must follow and understand the syntax (the structure, or how it looks) and the semantics (what it means) of the names.


Syntax

According to Java, a name can consist of a sequence of one or more characters. It must begin with a letter or underscore (refers to the character '_') and must be composed of letters, digits, and underscores.

Example 1: A few examples of variable names

X     x     billboard     b13     very_good     helloWorld

No spaces are allowed. Upper case and lower case letters are considered to be different, so hellowWorld, helloworld, HeLlWoRlD are unique names. There are some names which are reserved for special uses in Java, and cannot be used by the programmer which include: class, public, static, if, else, while, catch, and a whole bunch of others.

One thing to note about the naming, is the syntax of words. The basic rule of thumb is the "camel case" format, where the first letter is capitalized for each word used (after the first full word in the variable). A few examples:

Example 2: Camel case format

powerBook		windowsVista		goingBackToCali

Names should be used properly, and have proper meaning (to easily find what they are used for). It makes code that much easier to understand.


Variables

We use variables in two ways: to reference things, and to store values in memory. The reason why it is called a variable is because the object referenced, or value stored can change ('variety'). In order to create the variable, a declaration statement must be made. Such statements look like this:

Example 3:

	int count;
	double pass;
	char name;
	boolean status;

Not the format of the statements. They follow this form, while the brackets in [ = value ] show that this is optional. Also, each line of code must end with a semicolon (any line of code really).

Basic Form: typeName variableName [ = value];

                       int quarters;
                       int dollars = 50;

Assignment statements occur when assigning a value to a variable which has already been declared.

Example 4:

        count = 7;


Literals

A name for a constant value is called a literal. These appear after the equals ( = ) sign. Each literal must match its corresponding data type (see Primitive Data Types.) There are also special literals using the "escape character", backslash( '\' ). In particular, a tab is represented as '\t', a newline is '\n', a single quote character is '\, and the backslash itself '\\'.

For the type boolean, there are two literals: true and false. These values are typed as written here, and occur mostly in conditional expressions (is the statement true or false).


Common Primitive Variables

This article will introduce the idea of primitive variables, and discuss the four commonly used primitives within Java.


Introduction

There are four common primitive variables which are used quite often. These variables are: int, double, char, and boolean.


Primitive Type int

int values are used to represent integers, positive or negative whole numbers. A number without a sign is considered to be positive. Some valid integers are:

Example 1:

       -10987		456		13		-27

We can perform common arithmetic (math) operations such as add, subtract, multiply and divide, on type int data. For example, the expression 13 + 35 has the value of 48.


Primitive Type double

double values are used to represent fractions, or any number using decimals (real numbers). Some valid real numbers are:

Example 2:

       -10.9			.467		78.		-89.8389

Also, exponents can be used using the Java scientific notation. A real number in Java would be:

Example 3:

      1.23e5

where the 'e' represents the exponential power of 10 (it would be 10 to the power of 5, in the above example).


Primitive Type boolean

The boolean data type just has two variables: true and false. We can use this data type to represent conditional values so a program can make particular decisions (if a certain result came out as false, the proper procedure would happen).

Example 4:

       boolean test;

       test = 'false';          //test came out as false


Arithmetic Operators

This article will provide a quick tutorial on how to use arithmetic operators (math operations) in Java. Basic knowledge of algebra would be nice.


Introduction

To solve many programming problems, you will need to use arithmetic operations that manipulate integers and real numbers. Each operator evaluates two operands, which maybe be variables or other expressions. The operators can be used with both integers and real numbers. When the operands are integers, the result is an integer. When the operands are real numbers, a real result is given.

Table of Arithmetic Operators

Operator Meaning Example
+ Addition 6 + 9 is 15.
- Subtraction 19 - 5 is 14.
* Multiplication 6 * 5 is 30.
/ Division 5 / 2 is 2.
% Remainder 5 / 2 is 1.


Data Type of an Arithmetic Operator

One thing to note is the use of both an integer and a real number in a arithmetic operations. If we were to add an integer and a real number together, the result would be a real number.

Example 1:

	int test1 = 9;
	double test2 = 8.7;

	test1 + test2 would equal 17.7.


This would apply to all other operators as well. double would take precedence over the int, so the result will always be a real number. What it basically comes down to is: "The type of the result of an arithmetic operation is double if an operand is type double. If both operands are type int, the result is type int."


Assignment Statements

Normally, an assignment statement such as

x = y+z;

is used to store an arithmetic expression (y + z) in a primitive type variable x. The symbol = is the assignment operator. This statement should be thought as 'x gets the value of y plus z'.

Example 2:

	Form:		variable = expression;
	Example:		y = t -u;


The data types of expression and variable must be the same (or you will get an error when you compile). Using the previous example, we could use a double data type, result, to hold the answer.

Example 3:

	doubel result;
	int test1 = 9;
	double test2 = 8.7;
		
        result = test1 + test2;			//we can then print out this statement, or use it
						//in some other function


Example 4:

In Java you can write assignment statements with the form

sum = sum + item;

where sum appears on both sides of the assignment operator.This is a common programming practice, and instructs the computer to take the current value of sum, then add the value in item, and take this total and store it in sum.


Example 5:

You can also use assignment statements to assign the value of one variable to another variable.

newZ = z;

copies the value of variable z into variable newZ. You can also negate the statement, before assigning it newZ.

newZ = -z;

This instructs the computer to get the value of z, negate it, then assign the negated value to newZ.


Mixed-Type Assignment Statement

When an assignment statement with multiple operators is executed, the expression is first evaluated and then the result is assigned to the variable preceding the assignment operator. Either a type double or in expression maybe be assigned to a type double variable (integer '2', can be changed to '2.0').

Example 6:

	int j = 6;
	int k = 5;
	double l = j + k;			//assigns 11 to l
						//stored as a real number (11.0)

	double x = l +j / k;		//assigns 12.0 to x

Notice how 'j / k' is done first, before the addition. j and k are still both integers, and this statement evaluates to 1. This value is then converted to a double (1.0), and added onto l (11.0).


Expressions with Multiple Operators

Java uses the same rules as algebra, to determine the order of operator evaluation.

Rules for Evaluating Expressions

a. Parentheses rule: All expressions in brackets are evaluated separately. Nested parentheses work from the inside out, with the inner most expressions evaluated first.

b. Operator rule: Operators in the same expression are evaluated in the order determined by their precedence (from highest to lowest).


Operator Precedence
- Highest Precedence
*, /, %
+, -
= Lowest Precedence


Example 7:

	x * y + z / a - c * e + v % q			//can be written clearly as
		
	(x * y) + (z / a) - (c * e) + (v % q)






Review Questions and Exercises

  1. What is the difference between System.out.println and System.out.print?
  2. Where does a Java program begin execution?
  3. Why do escape sequences exist? Can you think of another way to handle these characters?
  4. What would be the result of the following casts?
    1. Given a long data type named value equal to 50: (int)value;
    2. (long)25.7
    3. (long)5.5E16
    4. (float)1.23e240
    5. (int)2500000000L
    6. (double)67890000
    7. (double)600L
  5. What is the length of the following Strings?
    1. "Pretty short String"
    2. "\tTab and\nNewline"
    3. "\\\\slashes!"
  6. There are several syntax errors in the following program. Find the errors, fix them, and then try running the program.
    public Class BrokenProgram
    {
      public static void main(String args[]) 
      {
        int value1;
        int value2;
        int result;
        
        value1 = 25;
        value2 = 5;
    
        result = value1 / value2
     
        System.out.println("When you divide " value1 " by " value2 ", the result is: " result);
      }
    }
    
  7. Write a program that asks the user to
    • enter the price of a drink
    • enter the price of a sandwich
    The program should then
    • sum the cost of these two items
    • add GST and PST to the sum
    • print the total cost with taxes included

Solutions