Download In this part of the lab, you will work with decision

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
IS 389
INTRODUCTORY JAVA LAB
EKEDAHL
In this lab, you will work with the basics of Java in Eclipse. The following list describes what you will learn
in this lab:







Create a new Java Project that implements the all too familiar Hello World program.
Work with data types and arithmetic expressions
Work with decision-making statements
Work with loops
Use Arrays
Read and write data character by character
Read and write data line by line
PART 1: CREATING HELLO WORLD
In this part of the lab, you will create the all too familiar Hello World program, compile it, and then
execute the application.
1. Start Eclipse.
2. Create a new Workspace, if necessary, or use your existing workspace. I suggest that you either
use your student home directory on the U:\ drive or a USB stick.
3. Now you will create a new Java project. A Java project is conceptually similar to a Visual Basic
Project. That is, it contains a number of folders and has a well-defined structure. Click File, New,
Java Project to create a new Java project. The following dialog box will appear.
Page 1 of 22
4. As shown in the above dialog box, name the project Hello. Note that the execution environment
is set to JavaSE-1.7. You can create a project using different execution versions.
5. Click Next to display the following dialog box:
Page 2 of 22
6. You need not change any of the defaults in the above dialog box. However, note that the folder
named src will contain the source code for your project. When compiled, the executable code
will be saved to the folder named bin.
7. Click Finish, to create the project. When you do, the Eclipse IDE should display your new project
in the Package Explorer. The Package Explorer is similar to the Visual Studio Solution Explorer.
Note that the window you see will contain different packages. The src folder contains the
default package:
Page 3 of 22
8. Next, you will create a new class. Every Java program contains an entry point. That entry point is
static method named main. A program’s entry point is where the Java runtime begins program
execution.
9. Click File, New Class to display the following dialog box:
Page 4 of 22
10. Note that the source folder is set to Hello/src. Set the Name to Hello. Note that the Modifier is
set to public. Access modifiers control the visibility of a class. For the main class, the access
modifier is set to public. Make sure that the check box named public static void main(String[]
args) is checked. This causes the IDE to create the main method in the class. This main method is
the program’s entry point. Click the Finish button to create the class. Eclipse will create the class
and display the template Java code as follows:
Page 5 of 22
11. As you can see, the program contains a class named Hello. The class contains one method
(function) named main. The function accepts one argument – an array of type String. The
argument is named args. Function arguments work the same way in Java as they do in Visual
Basic.
12. Enter the following statement inside of the main procedure:
13. The System.out class contains methods to write output to the console window. In the above
example, you are writing the literal string Hello using the println method. Literal strings are
enclosed in double quotation marks. Note that statements are terminated with a semicolon.
Remember that Java is case sensitive.
14. Run the program. The output is displayed to the Console window as shown in the following
screen: By default, the Console window appears at the bottom of the screen. If the Console
window does not appear, Window, Show View, Console.
Page 6 of 22
Before continuing, you will use several different packages (libraries). So that you need not enter the fully
qualified package name for all of the objects, you will import the classes that you will use in this lab.
1. Enter the following statements at the beginning of the class:
PART 2: PRIMARY DATA TYPES
In this next part of the lab, you will work with the basic Java data types and work with expressions. Java
is a strongly typed language, meaning that every variable has an explicit data type. In this regard, Java
works the same way as Visual Basic. The following table describes the Java primitive data types and the
minimum and maximum values that can be stored in the variable.
TYPE
byte
short
int
long
float
double
SIZE
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
VALUE
-128 to +127
-32,768 to +32,767
(about)-2 billion to +2 billion
(about)-10E18 to +10E18
-3.4E+38 to +3.4E+38
-1.7E+308 to 1.7E+308
Java primitive data types can be converted to objects through a process known as boxing. Boxing
converts a primitive data type to an object using a wrapper class. These wrapper classes, in turn, have
properties and methods that allow you to determine the minimum and maximum value of the type,
along with methods to perform type conversion. The following table shows the wrapper classes that
correspond to primitive data types:
Primitive type
Byte
Short
Int
Long
Float
Double
Char
Boolean
Wrapper class
Byte
Short
Int
Long
Float
Double
Character
Boolean
Page 7 of 22
1. Create a Java function named DoMaxValues and enter the following code:
The preceding code illustrates a static method that does not return a value (type void). This
is roughly equivalent to a Visual Basic Sub procedure. The first group of statements declare
whole number types. The maximum value of each type is stored in the variable. Note that the
object types Byte, Short, Integer, and Long have associated constants named
MAX_VALUE that store the maximum value for the data types. The next group of statements
declare a char and boolean variable. The final group of statements print the value of these
variables to the Console window. Note that in Java, the string concatenation operator is the plus
(+) sign.
2. In the main procedure, write the following statement to call the function.
The above statement illustrates a function call. To call a function in Java, you use the function
name followed by the argument list enclosed in parenthesis. In the above example, the function
has no arguments.
Page 8 of 22
3. Run the program. The following output should appear in the Console window:
In the next set of steps, you will work with arithmetic expressions. The Java arithmetic operators are
similar to the VB operators. The Java programming language has five arithmetic operators: + (addition),
- (subtraction), * (multiplication), / (division), and % (modulo).
1. Create a Java function named DoArithmetic and enter the following code.
Page 9 of 22
The above code illustrates the use of the addition, subtraction, multiplication, division and
modulus arithmetic.
2. In the main procedure, write the following statement to call the function:
3. Run the program. The following output appears in the Console window.
PART 3: DECISION-MAKING STATEMENTS
In this part of the lab, you will work with decision-making statements. Decision-making statements work
the same way in both VB and Java. That is, Java has 1-way, 2-way, and multi-way decision making
statements. In addition, Java supports a form of Select Case statement called a switch.


The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true.
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.
The following example illustrates a multi-way if statement.
Page 10 of 22
The preceding code first tests whether the test score is greater than or equal to 90. If it is, the grade
“A” is stored in the variable named grade. If the grade is not >= 90, then the first else if condition is
tested to determine whether the test score is greater than or equal to 80, and so on. Note that in
Java braces mark the beginning and end of the if block. There is no EndIf statement as there is in
Visual Basic.
1. Create a Java function named DoConditional and enter the following code.
2. In the main procedure write the code to call the procedure.
3. Run the application. Enter a number into the Console window in response to the prompt.
Page 11 of 22
Note the following about the above statements:

Recall that .NET supports the StreamReader class. Java has similar classes to read and write
data.

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes
and decodes them into characters using a specified charset. The charset that it uses may be
specified by name or may be given explicitly, or the platform's default charset may be accepted.

Each invocation of one of an InputStreamReader's readLine() methods may cause
one or more bytes to be read from the underlying byte-input stream. To enable the efficient
conversion of bytes to characters, more bytes may be read ahead from the underlying stream
than are necessary to satisfy the current read operation.

For top efficiency, consider wrapping an InputStreamReader within a BufferedReader.
For example
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

The try, catch block is known as an exception handler. The statement
stdin.readLine() reads characters from the keyboard.

The statement Integer.parseInt(inS) reads string input and converts that string input
to an integer. Note that an exception will be thrown if the input cannot be converted. The if
statement tests whether the input value is less than zero, or greater than or equal to zero.
Java supports a switch statement that operates similar to a Visual Basic Select Case statement.
Unlike if-then and if-then-else statements, the switch statement can have a number of
possible execution paths. A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types, the String class, and a few special classes that wrap certain
primitive types: Character,Byte, Short, and Integer
1. Create a procedure named DoSwitch and enter the following statements.
Page 12 of 22
2. Write the statement in the main procedure to call the procedure that you just created and run
the program.
DoSwitch(1);
Note the following about the above code.

First, note that the procedure accepts one argument. The argument has a data type of int.

Remember that the switch statement operates on primitive data types, such as int.

The case keyword contains an integer value. If the value of month is 1, then the first case
executes, and the value January is stored in the variable monthString.

The break keyword causes the switch to exit.
Page 13 of 22
PART 4: LOOPS
In this part of the lab, you will work with loops. Loops work the same way in both VB and Java. That is,
you can create both pre-test loops and post-test loops. In Java, braces {} mark the beginning and ending
of a statement block. Thus, there are no statements such as EndWhile.
The while statement continually executes a block of statements while a particular condition is true. Its
syntax is expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block.
The while statement continues testing the expression and executing its block until the expression
evaluates to false. Using the while statement to print the values from 1 through 10 can be
accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as
follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
Page 14 of 22
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
1. Create a Java function named DoLoops and enter the following code.
2. Write the code in the main procedure to call to call the procedure that you just wrote.
3. Run the program.
Note the following about the above code.

The counter is initialized to 1.

The loop is a pre-test loop.

The loop prints the counting numbers from 1 to 10.

The post-increment statement (count++) increases the value of count by one each time
through the loop.
The for statement provides a compact way to iterate over a range of values. Programmers often refer
to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is
satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment)
{
statement(s)
}
When using this version of the for statement, keep in mind that:

The initialization expression initializes the loop; it's executed once, as the loop begins.

When the termination expression evaluates to false, the loop terminates.
Page 15 of 22

The increment expression is invoked after each iteration through the loop; it is acceptable for
this expression to increment or decrement a value.
1. Create a Java function named ForLoops and enter the following code.
2. Write the statements to call the procedure.
3. Run the program
The preceding code initialize the loops counter (i) to 1. Each time through the loop, the variable (i) is
incremented by one. The loop iterates until (i) is greater than or equal to 11.
PART 5: ARRAYS
An array is a container object that holds a fixed number of values of a single type. The length of an array
is established when the array is created. After creation, its length is fixed. Each item in an array is called
an element, and each element is accessed by its numerical index. As shown in the preceding illustration,
numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
One way to create an array is with the new operator. The next statement in the ArrayDemo program
allocates an array with enough memory for 10 integer elements and assigns the array to
the anArray variable.
// create an array of integers
int[] anArray ;
anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
Page 16 of 22
ArrayDemo.java:4: Variable anArray may not have been initialized.
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray
100, 200,
400, 500,
700, 800,
};
= {
300,
600,
900, 1000
Here the length of the array is determined by the number of values provided between braces and
separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more
sets of brackets, such as String[][] names. Each element, therefore, must be accessed by a
corresponding number of index values.
In the Java programming language, a multidimensional array is an array whose components are
themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are
allowed to vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
The output from this program is:
Mr. Smith
Ms. Jones
Page 17 of 22
Finally, you can use the built-in length property to determine the size of any array. The following code
prints the array's size to standard output:
System.out.println(anArray.length);
Most programming languages support random numbers. Random numbers
An instance of the random class is used to generate a stream of pseudorandom numbers. The class
uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of
Computer Programming, Volume 2, Section 3.2.1.)
1. Create a Java function named InitArray and enter the following code.
2. Write the statement to call the procedure.
3. Run the program
Note the following about the above code:

The first statement creates a new instance of the Random class.

The second and third statement initialize the seed value to 0. This will cause the same sequence
of random numbers to be generated each time the program is run.

Next, an array is declared to store 10 integers.

The first for loop iterates 10 times storing a random number in each array element. The
nextInt method gets the next integer value from the random number generator.
Page 18 of 22

The second for loop enumerates the array and prints the random numbers to the Console
window.
PART 6: IO / CHARACTER STREAMS
An I/O Stream represents an input source or an output destination. A stream can represent many
different kinds of sources and destinations, including disk files, devices, other programs, and memory
arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized
characters, and objects. Some streams simply pass on data; others manipulate and transform the data in
useful ways.
No matter how they work internally, all streams present the same simple model to programs that use
them: A stream is a sequence of data. A program uses an input stream to read data from a source, one
item at a time:
The data source and data destination pictured above can be anything that holds, generates, or
consumes data. Obviously this includes disk files, but a source or destination can also be another
program, a peripheral device, a network socket, or an array.
The Java platform stores character values using Unicode conventions. Character stream I/O
automatically translates this internal format to and from the local character set. In Western locales, the
local character set is usually an 8-bit superset of ASCII.
For most applications, I/O with character streams is no more complicated than I/O with byte streams.
Input and output done with stream classes automatically translates to and from the local character set.
A program that uses character streams in place of byte streams automatically adapts to the local
character set and is ready for internationalization — all without extra effort by the programmer.
1. Create a file named input.txt and put some text in it. It does not matter the text that you create.
Page 19 of 22
2. Create the following procedure and the code to call it.
3. Run the program.
Note the following about the above code:

The first statements declare variables named inputStream and outputStream having data types
of FileReader and FileWriter. The FileReader is meant for reading streams of characters.
The FileWriter is meant for writing streams of characters.
Page 20 of 22

Because exceptions can occur when reading and writing files, the code is enclosed in exception
handlers.

The first statements in the try block create the actual FileReader and FileWriter.
Because the backslash is the escape character, the \\ sequence embeds the \ in the path.

The while loop reads characters from the input stream. Look closely at the while loop, the
code reads one character and stores that char in the integer variable c. Here, you are storing the
ASCII code of the character. If there are no more characters in the input stream, the read
method will return -1. The condition tests whether the variable c contains -1. If it does, all of the
characters have been read and the loop exits.

The statement in the while loop writes the character to the output stream by calling the write
method.

The outer catch blocks handle the exceptions that might occur when reading the file. If an
exception occurs, a stack trace is printed to the Console window. The stack trace lists the
current function class.

The code in the finally block tries to close the files. Files should be explicitly closed after
they have been read.
PART 6: IO / LINE-BASED IO
Character I/O usually occurs in bigger units than single characters. One common unit is the line: a string
of characters with a line terminator at the end. A line terminator can be a carriage-return/line-feed
sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n"). Supporting all possible line
terminators allows programs to read text files created on any of the widely used operating systems.
Invoking readLine returns a line of text with the line. The following code segment illustrates the use of
the readLine method to read code a line at a time instead of a character at a time.
Page 21 of 22
Page 22 of 22