Download Exercise 2 - Custom Training Institute

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
Exercises - Module Two: Introduction and
Overview of Java
Exercise 1: Compiling and Running a Simple Java Program
Objective: To code, compile, and run a simple Java program.
Java applications and applets can be created in an interactive development environment (IDE) or
using command-line tools. This class is will use command-line tools.
To create and modify your projects, you’ll need a text editor. This should be an editor that creates
text files without adding any formatting elements. On Windows, you can use NotePad but be
aware that if you use File -> Save As and then choose *.txt as the document type, notepad will
append a “.txt” extension to your filename. You can prevent it from doing this by choosing “All
Files” in the “Save as type” combo-box.
Java source code files use a ".java" suffix (for example, myproject.java). Compiled Java
source files will have a “.class” suffix (fox example, myproject.class). Projects can consist of
many different kinds of Java constructs, including packages, classes, and JavaBeans. They can
be very simple, as our first exercise illustrates, or very complex.
When you create a project, you will need to create a project directory. The files that make up
your project will be placed in this directory. Create two directories (c:\labs and
c:\labs\ModuleOne) where the class exercises will be placed. You may use File -> New ->
Folder from the Windows Explorer utility or enter the following from the command line
prompt:
 mkdir c:\labs
 mkdir c:\labs\ModuleOne
 cd c:\labs\ModuleOne
The first project you create using your text editor will be placed in the c:\labs\ModuleOne
directory.
In the first part of the exercise you will create a project that contains a simple Java program that
prints “Hello, World!” to the console window. The Java code to do this is shown below:
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello, world!");
}
}
Copyright ©2009, Custom Training Institute. All rights reserved.
The next few paragraphs explain the above syntax.
Java Syntax -- Classes
Every software unit in Java is a class -- a combination of methods (actions that can be taken, or
executable logic) and the data needed by those methods. At run time, the class definitions are
used to create objects. (Think of a class as a cookie-cutter, and an object as a cookie stamped
from that cookie-cutter.)
The example above creates a class called "HelloWorld," using the same name as the project. But
how does Java know to run this class? Because all Java applications contain one, and only one,
method called main(). Parentheses are required after the name of the method. When the JRE
starts to execute a program, it looks for a class containing main(), where it begins execution.
The keywords preceding main() -- public, static, and void -- also have meaning to
Java. A public function may be executed by any other method -- including the Java
interpreter. A void function does not return any values.
Functions take arguments, or parameters, as input values. In Java, those input arguments are
represented by variables inside the function's parentheses. In the example above, the syntax
String args[] means that the variable args is an array of text strings.
Java Syntax – Methods
The code in the main()method should display the text string Hello World! as its output.
Since the Java language was designed to be machine-independent, and since everything in Java is
an object, the characteristics of the particular machine on which a Java application is executing is
available to a java program via a System object, which encapsulates system-related behaviors
such as input and output. The System object has a member called out, which represents the
output side of the machine on which Java is running. Finally, the println()method is used to
display a line of text, ending it with a carriage return. The following summarizes some of the
methods available using the System object:
System.out is the output side of the system object.
System.out.println() prints a line of data to the output side of the system object.
The curly braces are used to indicate the beginning and end of a class. Within those curly braces,
method definitions are also enclosed in curly braces.
Note that you must create the file in our project directory. At the MSDOS prompt change your
current directory to the project directory:
Copyright ©2009, Custom Training Institute. All rights reserved.
 cd
C:\labs\ModuleOne
Create the HelloWorld.java example by starting your text editor and entering the code from the
illustration above. To compile at the MS-DOS prompt, simply type javac followed by a space
then the complete name of the file (including the .java file extension), like so:
 javac
HelloWorld.java
The HelloWorld.java file will be built (compiled to Java bytecode) and a HelloWorld.class file
will be created and run.
Run your newly created java class by typing the following:
 java
HelloWorld
A Java project has now been created in the directory ModuleOne, a Java source file added to the
project, a main method with simple code placed into the source file, and the code compiled and
run. The next part of the exercise teaches more about basic Java features and syntax.
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 4
Exercise 2: Java Language Features
Objectives: To understand the basic syntax of Java statements and to write a standalone
application.
This set of exercises will focus on Java syntax, and on how to use it to write realistic Java
applications.
Part One: Java Syntax
Java is case-sensitive and picky about punctuation. Variable names can be of any practical
length. Java provides eight basic (primitive) data types, as shown in Table 1 below:
Table 1. Java's Primitive Data Types.
byte
short
int
long
float
double
char
boolean
8 bits (-128 to +127)
16 bits (-32,768 to +32,767)
32 bits (-2,147,483,648 to +2,147,483,647)
64 bits (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
32 bits, seven digits of precision after the decimal point
64 bits, fourteen digits of precision after the decimal point
16 bits [unsigned]
true or false
Please note that a boolean value CANNOT be compared to 0 or ±1; Java booleans are NOT
integers. Always compare Booleans to true or false ONLY.
A floating-point variable is commonly initialized using the suffix f, as shown below:
float anHourlyWage = 12.5f;
To create a new data type, first create a class, then declare variables of that class' type.
Java provides the character constants or literals listed in
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 5
Table 2. Java's Character Literals.
\n
\t
\b
\r
\f
\\
\'
\"
\dddd
\xdddd
\udddd
newline
tab
backspace
carriage return
form feed
literal backslash
single quote
double quote
Octal value dddd
Hexadecimal value dddd
Unicode value dddd
Java has five standard arithmetic operators, as shown below in Table 3:
Table 3. Standard Arithmetic Operators in Java.
+
*
/
%
Addition
Subtraction
Multiplication
Division [integer division provides an integer quotient]
Modulus (integer remainder from division)
Java has six comparison operators, all of which return a Boolean value. These operators are
shown below in Table 4, which lists the operators and examples of their use:
Table 4. Java Comparison Operators.
==
?
<
>
<=
>=
equal
not equal
less than
greater than
less than or equal to
greater than or equal to
(x
(x
(x
(x
(x
(x
== 3)
? 3)
< 3)
> 3)
<= 3)
>= 3)
Java has three logical operators, shown below in
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 6
Table 5. Java Logical Operators.
&&
||
!
logical and ( A && B)
logical or ( A || B)
logical not (!(A || B))
Java also supports arithmetic assignment operators, which combine an arithmetic test with a
variable assignment.
Table 6. Java's Arithmetic Assignment Operators
+=
-=
*=
/=
add and assign
subtract and assign
multiply and assign
divide and assign
x
x
x
x
+=
-=
*=
/=
2
2
2
2
Java supports a String class, which overrides the + operator to perform string concatenation.
This means that statements such as
String myString = "This is " + "a test of" +
" string concatenation";
work as expected.
To control how an object is converted to a string, override the object's toString() method.
This method is inherited all the way down from Object. Overriding and inheritance are
covered in more detail in Module 2.
Finally, iterative (looping) statements:
for (int counter = 0; counter < 10; counter++)
System.out.println(counter);
do {System.out.println(counter);}
while (++counter < 20);
while (counter < 20)
do {System.out.println(counter); counter++; }
Normal loop execution can be modified using the break or continue keywords. If the loop
is labeled (a piece of text followed by a colon), the break keyword with the label causes
execution to branch out of the loop altogether (handy for nested loops):
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 7
getoutofloop: // this labels the loop
for (int I = 0; I < 4; I++)
for (int J = 0; J < 4; J++) {
System.out.println(I + J);
if ((I + J) > 6)
break getoutofloop;
}
System.out.println("end of loops");
This code will print out values until the sum of I and J exceeds 6. At that time, BOTH loops will
be terminated, and the code will print out "end of loops," and continue to execute any subsequent
instructions.
The break statement, in other words, is a branch -- like a goto, which does not exist in Java.
Part Two: Coding Examples
Here is an example of a class, called ArithmeticTest. This class illustrates the behavior of
the different arithmetic operators. Use your text editor to create the following class The only
difference is the name of this file will be ArithmeticTest and the code shown below put in
main().
class ArithmeticTest {
public static void main (String args[]) {
short x = 6;
int y = 4;
float a = 12.5f;
float b = 7f;
System.out.println("x
System.out.println("x
System.out.println("x
System.out.println("x
System.out.println("x
System.out.println("a
System.out.println("a
is " + x + ", y is " + y);
+ y = " + (x + y));
- y = " + (x - y));
/ y = " + (x / y));
% y = " + (x % y));
is " + a + ", b is " + b);
/ b = " + (a / b));
}
}
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 8
Compile and run your new class like this:


x
x
x
x
x
a
javac ArithmeticTest.java
java ArithmeticTest
is 6, y is 4
+ y = 10
- y = 2
/ y = 1
% y = 2
is 12.5, b is 7.0
The output of the run is displayed to your screen. Are the results as you expect? Note that the +
operator can be used inside the argument to println(), to construct a string from several
different components at run time.
Part Three: Java Applications
Java applications run "standalone," without a driver program. A Java application consists of one
or more classes, and can be as large or small as needed. A class is frequently created for the sole
purpose of encapsulating the main() method, necessary for the application to begin. Any class
may contain the main() method. When writing a large application with many separate class
files, a common programming technique is to create a class that contains the main() method,
plus any special initialization or termination routines for the application. This class could be
called Main.java.
The signature for the main() method always looks like this:
public static void main(String args[]) { }
The public keyword means that this method can be called by other class files; the static
keyword means there's only one occurrence of this function; the void keyword means it doesn't
return a value.
args[] is the array of strings passed as arguments to the application. Any name can be
chosen, but args is commonly used to make code easier to understand. However, the first value
in the array, args[0], is the first argument to the program, NOT the program name.
Since args is an array, it has a length member, indicating the number of values passed. Code
must be added to the application to test the number of arguments received, which is found in
args.length; Java does not verify this automatically. An example is given below. Add
another Java class to the ModuleOne project called EchoArguments. Use your text editor to
create a new file called EchoArguments.java, then enter the code below, and save it.
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 9
class EchoArguments {
public static void main(String args[]) {
for (int I = 0; I < args.length; I++) {
System.out.println("Argument " + I + ": " + args[I]);
}
}
}
Once again, let’s compile and execute our program: When we execute the program, add some
arguments to the program’s command-line.
 javac EchoArguments.java
 java EchoArguments roses are red
Argument 0: roses
Argument 1: are
Argument 2: red
The command-line arguments are passed to the java program as an array of String objects. If
your application requires one or more of the arguments to be integers, you have to convert from
strings to primitive integers (as opposed to instances of the Integer class) using the
parseInt method of the Integer class. Since the Integer class is imported automatically
as part of the java.lang package, its methods can be used directly.
To illustrate this, create a new file called SumArguments.java in the ModuleOne directory.
class SumArguments {
public static void main(String args[]) {
int sum = 0;
for (int I = 0; I < args.length; I++) {
sum += Integer.parseInt(args[I]);
}
System.out.println("The sum of the arguments is " + sum);
}
}
This application will require two arguments be passed to it when it is run. SumArguments will
add the two values together and print the result. Create your file in the same manner as before
and then compile and run it.
Copyright ©2009, Custom Training Institute. All rights reserved.
Compiling and Running a Simple Java Program-Exercise: Page 10
 javac SumArguments.java
 java SumArguments 10 20
The sum of the arguments is 30
Each of the java object that has a corresponding java primitive can be used in a similar fashion to
convert strings. The table below illustrates some of these methods:
static byte Byte.parseByte( String s )
static int Double.parseDouble( String s )
static float Float.parseFloat( String s )
static int Integer.parseInt( String s )
static long Long.parseLong( String s )
static short Short.parseShort( String s )
Summary
This exercise demonstrated how to edit, compile, configure, and test Java applications.
It also presented basic Java languages grammar and syntax, and provided examples of
their use.
Java applications must have at least one class file that contains a main() method. The
java runtime environment will automatically call the main() method to start the
application.
Copyright ©2009, Custom Training Institute. All rights reserved.