Download Chapter 2

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

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

Document related concepts
no text concepts found
Transcript
Chapter 2
Introductory Programs
1
Getting started
• To create and run a Java program
– Create a text file with a .java extension for the
source code. For instance, source code for a
first program might reside in the file Hi.java.
– Write the source code.
– Compile the source code into binary code.
– Execute the binary code.
2
Compiling
• Suppose that the Java source code resides in
the text file Hi.java. Using the $ as the
system prompt, the source code is compiled
with the command
$ javac Hi.java
The javac utility comes with the JDK (Java
Development Kit).
3
Compiling
• Compiling a source file such as Hi.java
generates one or more binary files with a
.class extension, e.g., Hi.class.
– If fatal errors occur during compilation, the
process ends with appropriate error messages.
– If nonfatal errors occur during compilation, the
process continues with appropriate warnings.
4
Executing
• Once the program has been compiled, it can
executed with the java utility. For instance,
if the file Hi.class contains a compiled
standalone program, the command
$ java Hi
executes the program.
5
Compiling versus executing
• Note that the .java extension is included in
the compilation but that the .class extension
is not included in the execution. Note the
constrast:
$ javac Hi.java
$ java Hi
6
A first program
// This program prints
//
Hello, world!
// to the standard output.
class Hi {
public static void main( String[ ] a ){
System.out.println( “Hello, world!” );
}
}
7
A first program
• The source code for the Hi program resides
in a text file with a .java extension, e.g.,
Hi.java. (The name Hi.java is appropriate
because the program has a single class
named Hi.)
• Every Java program requires at least one
source code class, as the Hi example
illustrates.
8
A first program
• The Hi program is a Java application rather
than, for instance, an applet or a bean,
which are other program types. A Java
application is the most general and basic
program type.
9
A first program
• The source code begins with three
comments, each introduced with a double
slash //. A double-slash comment runs
until the end of the line.
• The program’s single class is named Hi and
its body is enclosed in curly braces { }.
• The class Hi encapsulates a single static
method named main.
10
A first program
• Java applications require that main be
defined with the attributes public and
static.
– main has void in replace of a return type such
as int to signal that the method does not return
a value.
– main expects one argument, a reference to an
array that can hold references to Strings.
11
A first program
• The syntax
String[ ] a
indicates that a (for “array”) refers to an
array. In general, the square brackets
indicate an array. In this case, the array can
hold references to Strings, which are any
command-line arguments passed to the
program.
12
A first program
• In the print statement
System.out.println( “Hello, world!” );
– System is a standard Java class that represents
the system on which the program executes.
– out is a static field in the System class
and its type is PrintStream, another
standard Java class.
– println is a PrintStream method.
13
A first program
• In the Hi program’s print statement, the
parts System, out, and println are
separated by the member operator, the
period.
• The print statement is terminated by a
semicolon.
– In Java, the semicolon terminates statements.
14
Identifiers
• The Hi program has a single class named
Hi. A programmer-defined class can have
any name except a Java keyword such as
int.
• Java names are case sensitive. A class
named Hi is distinct from one named hi.
15
The import statement
• Java programs often include import
statements such as
import java.util.Date;
for convenience. If a program requires the
standard Date class, for instance, then the
fully qualified name java.util.Date
must be used if the import is omitted.
16
The import statement
• The * can be used to import all classes in a
package but not to import subpackages. The
statements
import java.util.*;
import java.awt.*;
import java.awt.event.*;
illustrate.
17
Fields and local variables
• A class can encapsulate fields and
constructors and methods can have local
variables.
• In Java, all fields and local variables must
be declared before they are used.
– A variable declaration specifies the variable’s
name, data type, and any attributes such as
public.
18
Fields and local variables
• Fields have default values but local
variables do not. In the code segment
class C {
void m() { int x; }
int n; // default value is 0
}
the field n has a default val but local
variable x does not have a default value.
19
Initializing local variables
• Because local variables do not have default
values, they must be initialized before being
used, for example, in function calls or as the
source in an assignment operation.
– A local variable can be initialized in its
declaration
int x = -1;
for convenience.
20
The if statement
• The if statement is used for tests. Its
simplest for is
int n1 = 1, n2 = 3;
if ( n1 < n2 )
System.out.println( n1 );
• The if condition is enclosed in parentheses
and must evaluate to a boolean value.
21
The if statement
• If the body of an if statement contains
multiple statements, the body must be
enclosed in curly braces:
int n1 = 1, n2 = 3, n3;
if ( n1 < n2 ) {
n3 = n1;
System.out.println( n1 );
} // end of if
22
The if statement
• The if construct can be used for multiway
decisions through the use of else and
else if clauses:
int n1 = 1, n2 = 3, min;
if ( n1 < n2 )
min = n1;
else
min = n2;
23
The while statement
• The while statement is one of three loop
constructs.
• The while loop is suited for conditional
looping, that is, looping until a specified
condition is satisfied.
• The while statement is similar in syntax to
the simple if statement.
24
The while statement
• The code segment
int n = 100, i = 0;
while ( i < n ) {
System.out.println( i );
i = i + 1;
} // end of while loop
illustrates. The loop body prints the integers
0 through 99.
25
Arrays
• Primitive types such as int and class types
such as String can be aggregated in
arrays.
• Arrays are fixed size. Once storage for an
array has been allocated, the array cannot
grow or shrink in size.
• Arrays of one, two, and even more
dimensions can be constructed.
26
Arrays
• The code segment
int[ ] nums = new int[ 100 ];
declares an array of int named nums and
allocates storage for 100 ints.
– The array’s cells are initialized to 0, the default
value for an int, regardless of whether nums
is a field or a local variable.
27
Arrays
• Array elements are accessed through an
index expression. The code segment
int[ ] nums = new int[ 100 ];
int i = 0;
while ( i < nums.length )
nums[ i ] = i + 1;
illustrates by populating the array with the
integers 1, 2,…,100.
28
Arrays
• Every array has a convenient length
member that specifies the number of
elements in the array. The code segment
int[ ] nums = new int[ 100 ];
int i = 0;
while ( i < nums.length ){
nums[ i ] = i + 1; i = i + 1;
}
illustrates.
29
Array utilities
• Java provides utility classes for filling,
searching, sorting, and performing other
standard operations on arrays. If nums
refers to an array of integers, the statement
Arrays.sort( nums );
sorts the array in ascending order.
30
Strings
• Java provides two standard classes,
String and StringBuffer, for string
processing.
– Strings are immutable but
StringBuffers are not.
• A double quoted string such as “hi” is a
reference to a String object.
31
The toString method
• Every class has a toString()instance
method that returns an appropriate string
representation. For example, the statement
System.out.println( new Date() );
prints a Date as a human-readable string.
• toString() is an example of a
polymorphic method.
32
Wrapper classes
• Java provides “wrapper” classes such as
Integer and Boolean for primitive
types such as int and boolean,
respectively.
• Wrapper classes have various uses,
including data conversion.
33
Wrapper classes
• The code segment
String num = “123”;
int n = Integer.parseInt( num );
illustrates data conversion with the
Integer wrapper class.
• Wrapper classes also can be used to store
primitive types in “object-only” constructs
such as Vectors and Hashtables.
34
Standard utility classes
• The java.util package has an
assortment of utility classes such as Date
for representing dates, Random for
generating random numbers of various
types, Vector for dynamically sized
aggregates of class types,
StringTokenizer for tokenizing
strings, and so on.
35