Your First Java Program

From CompSciWiki
Revision as of 15:19, 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.

Contents

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)



Advanced String Topics

This section covers more advanced String topics, which are not necessary to using Strings, but are necessary for fully understanding how they are handled in Java. These topics include mutability, special String characters, and escape sequences.

Mutability

Java Strings are known as immutable, meaning you cannot change the characters that are contained within a particular String. This means that when you append something to a String, or attempt to modify the contents of a String, a new String is returned and the original is unaffected. However, this does not mean that you cannot change a variable to hold a different String altogether.

Special Characters

Strings can contain characters that have special meaning to the Java compiler, which are called 'escape sequences'. Escape sequences are characters that programmers would like to use, but either do not occur on a standard keyboard, or have no single-character on-screen representation. Escape sequences are preceded by a backslash, and are considered together as a single character. For example, the escape sequence \t is interpreted by the computer as a tab.

The following table lists all of Java's common escape sequences:

Escape sequence Meaning
\b Backspace
\t Horizontal tab
\n Line feed* (a new line)
\f Form feed
\r Carriage return*
\" Double quote
\' Single quote
\\ Backslash

For example, given the meanings above, the following String would be a list of names that occur on separate lines: "Bob Dylan\nAndrew Jackson\nJohn MacDonald"

  • "Carriage return" and "line feed" are archaic terms from the days of manual typewriters, when a line feed would literally be a new line being moved underneath the cursor, and a carriage return would be the physical moving of the carriage to the far end of the machine.

Increment and Decrement Operators

This section will teach you about the increment and decrement operators, how to use them, the distinction between pre/post-increment and pre/post-decrement, and about special cases to watch out for.

What Increment and Decrement Operators Are

The increment and decrement operators increase or decrease the value of a Your_First_Java_Program#Introduction_3 by 1. These two operators are ++ and --, respectively. One would use an increment or decrement operator to concisely add or substract 1 from a variable.

Usage

There are two ways to use these operators, either on their own line along with a variable, or as part of a larger expression. Using them as part of a larger expression is more difficult because the operators may change the value before or after the expression is evaluated, depending on their placement.

Basic Usage

We can use these operators by simply placing them before or after the variable to modify. If the operator is placed before a variable, it is known as a preincrement or predecrement, and if the operator is placed after a variable, it is known as a postincrement or postdecrement.

The following code snippet demonstrates the difference between these four operators:

  int number = 5;

  ++number; // preincrement, the variable 'number' would be 6 as a result
  number++; // postincrement, the variable 'number' would be 6 as a result
  --number; // predecrement, number = 4
  number--; // postdecrement, number = 4

These increment and decrement expressions are really shorthand for:

  number = number + 1; // longer way of writing number++ or ++number
  number = number - 1; // longer way of writing number-- or --number

Note that the regular rules for arithmetic in Java apply here, so be careful not to unintentionally increment or decrement outside the value of a variable to outside of its range.

Within an Expression

These increment and decrement operators can occur as part of a larger expression as well. One might write the operator this way for conciseness, that is, to avoid writing the increment or decrement on its own line. In this case, the meaning of the expression actually changes depending on whether the operator is placed before or after a variable name. Until you are comfortable using these operators, you should not attempt to use them as part of larger expressions.

When a preincrement is done, the variable is changed before it is used in the expression. Oppositely, when a postincrement is done the variable is changed after the expression is evaluated.

The following example illustrates the difference between pre- and post- increment.

  int number = 3;
  int value = (++number) * 2; 
  // value = 8, number = 4

  int number = 3;
  int value = (number++) * 2; 
  //value = 6, number = 4  

As you can see, whether or not the modified value of number is used as part of the expression in which it occurs depends on which side of the variable the ++, and likewise --, occur.

Precautions

Note that some expressions have unclear meaning, such as number = number++ or number = ++number. Does the variable number receive its incremented value, or is number incremented after the assignment has taken place? It is best to avoid assignment to a varaible when that variable is incremented or decremented as part of the assignment's expression.

Casting

This section will introduce you to the concept of Casting, and explain when and why it is done. In addition, there is a reference table that explains what happens when we cast between the different primative types.

Introduction to Casting

When we are working with different primative types in Java, it may be necessary to convert between them while the program is running. Casting occurs within an expression, and has the effect of converting one type of data to another. So the act of casting to a particular type is to convert an existing variable or value to that type. What this conversion entails depends on the type of data being cast. For instance, casting a primitive floating point value (type float) to an integer value (type int) means that the decimal portion of the float will be lost, because it cannot be represented by the int. As a general rule, casting will always try to preserve as much of the data as possible.

Explicit Casting

An explicit cast occurs when you write out the type to be cast to as part of an expression. Explicit casts are easy to notice, because they use the following form:

 float floatingPoint = 30.5;
 int integerValue = (int)floatingPoint;

As you can see, the type being cast to occurs in brackets before the data that is being cast. In the above example, the float floatingPoint is cast to type int, and is assigned to the variable integerValue. As mentioned, this has the effect of assigning 30 to integerValue, because int variables cannot represent the decimal portion, .5.

Implicit Casting

An implicit cast, also known as coercion, is caused when a value must be converted to a different type for some reason. Such reasons may include:

  • Assignment of a variable of one type to a variable of another, compatible type
  • Conversion required as part of an expression

The following example code demonstrates two causes of an implicit cast:

  float result = 50.0f + 5;
  double doubleResult = result;

First, the integer 5 is implicitly cast to type float so it can be added to 50.0f, and then assigned to result. Second, the float result is assigned to doubleResult, and is implicitly cast to type double.

Casting Between Primative Types

Since each of the primative types represent different information, it is necessary to describe these types in more detail, including the possible values each can contain, and the effects of casting between these values.

The below table gives the maximum and minimum possible values of the different primative types. This is important information to have on hand, because if you cast to a type with a value outside the type's range, the result will be meaningless.

type minimum maximum
int -2147483648 (-231) 2147483647 (231 - 1)
long -9223372036854775808L (-263) 9223372036854775807L (263 - 1)
double 4.9E-324 (4.9x10-324) 1.7976931348623157E308 (1.7976931348623157x10308)
float 1.4E-45f (1.4x10-45) 3.4028235E38f (3.4028235x1038)

Note that the first value given in the minimum/maximum columns is how the value would appear in your code, and the second bracketed value is the actual value.

Given the above information, the following table describes the effects of casting between the different primative types. The legend below the table explains each case.

from\to int long float double
int OK OK 2 OK
long 1 OK 2 2
float 3 3 OK OK
double 3 3 1 OK

OK: All information is preserved in the cast.

1: There is a loss of information because the type being cast to cannot represent the full range of values of the original type. For example, a long can hold a much higher value than a int, so if a longis cast to type int and is holding a value an int cannot, the result will be meaningless.

2: Information may be lost since the type being cast to has less significant digits than the type being cast from.

3: Fractional values represented by floats or doubles is lost when casting to an integer type. Also, the range of values a float or double can represent is much larger than that of an int or long, so if value lies within this larger range, the result of the cast will be meaningless.

Named Constants

This article will teach you about named constants, including what they are, how to use them, and when to use them.

What Named Constants Are

Named Constants (also known as final variables or as just constants) are like variables, except once they have a value assigned to them, they cannot be changed. Like regular variables, they can be used as part of an expression.

Named Constant Conventions

By convention, named constants are declared just as a regular variable would be, except:

  • The keyword final must occur before the type
  • The name of the constant should be all upper-case letters
  • They must have a value assigned to them immediately upon declaration

Example of Usage

The program below demonstrates the use of named constants:

public class Test
{
  public static final double TAX_RATE = 0.13;
  public static final int PRICE = 10;

  public static void main(String[] args)
  {
    int total = PRICE + PRICE * TAX_RATE;
  }
}

This program contains two named constants: TAX_RATE and PRICE. Note the capitalized name, use of the final keyword before the type, and the immediate assignment of 0.13 and 10, respectively. Also note that the constants must be declared outside of a method, but within a class body.

When to Use Named Constants

Named constants should be used as replacements for any unchanging values that occur in the code. They can also be used to represent the result of an expression containing other named constants. This lets you assign a meaningful name to values that never change.

Using Named Constants To Improve Meaning

When you find yourself typing the same value over and over again, consider using a named constant in place of all occurances of that value. So, in all places where the value would occur, the name can be used instead. This has the positive effects of making your code self explanatory where named constants are used, and reducing the number of changes you have to make to one if the value changes.

For example, the following code calculates tax on three items:

 double total1 = 10.00 * (0.07 + 0.06);
 double total2 = 1.50 * (0.07);
 double total3 = 750.00 * 0.06;

Unless you are familar with the prices of the items above, PST, and GST, the code is fairly meaningless. Also, if either tax rate changes, you will have to change it in two places. Consider introducting named constants to help explain what is going on in the calculation and to help others understand the code:

  public static final double UMBRELLA_PRICE = 10.00;
  public static final double BREAD_PRICE    = 1.50;
  public static final double LAPTOP_PRICE   = 750.00;
  public static final double MANITOBA_PST   = 0.07;
  public static final double GST            = 0.07;

  ...

  double total1 = UMBRELLA_PRICE * (MANITOBA_PST + GST);
  double total2 = BREAD_PRICE * MANITOBA_PST;
  double total3 = LAPTOP_PRICE * GST;

Now it is obvious what the items are and which taxes apply to them.

Declaring Constants as a Product of Other Named Constants

Along with simple values, we can assign more complex expressions to a named constant as well. For example, to create a constant that is the product of two others, simply do the following:

 public static final double TAX_RATE = 0.13;
 public static final int PRICE = 10;
 public static final double TOTAL = PRICE * TAX_RATE;

PRICE and TAX_RATE are available for use in expressions that occur below their declaration, so they can be used to calculate TOTAL.


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