Download IS389JavaSyntax

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
Java Syntax
Lecture Overview


In this lecture, I roughly follow the ORACLE
tutorial on the Web site
http://docs.oracle.com/javase/tutorial/java/n
utsandbolts/index.html
Two Important Notes
Java IS case sensitive
File names ARE case
sensitive
Comments

/* and */ are comment markers



Comments do not nest
Comments may span multiple lines
// is the single line comment marker
/* This is a comment appearing on
two lines. */
// And this is a comment on one line.
Statement Format


A semicolon terminates a statement
A physical line means nothing



Statements can span multiple lines
Multiple statements can appear on the same line
There exists no continuation character as in VB
.NET.
Variables (Types)

Java is strongly typed



There are 8 primitive data types
Whole numbers


char - Note that this is not a string
Boolean


float, double
Character


byte, short, int, long
Floating point numbers


EVERY variable must be declared with a type
true and false
Note these are all lower case
Whole Number Types




byte (1 bytes)
short (2 bytes)
int (4 bytes)
long (8 bytes)


Value has a suffix of "L" for long
All of these are signed types
Floating Point Types

float (4 bytes)



double (8 bytes)



6-7 digits of precision
Suffix constant values with "F"
15 digits of precision
Suffix constant values with "D"
These types are not acceptable for financial
calculations because of rounding errors

Use the BigDecimal class instead
Numeric Overflow

Per the IEEE 754 specification:




Division by 0 evaluates to constant value
Double.POSITIVE_INFINITY
Square root of a negative number produces NaN
(Not a Number)
The value is Double.NEGATIVE_INFINITY
Use double.isNaN(x); to check
The Boolean Type

Represents the values true and false

Note that these are reserved words

Unlike in C, integers are not converted to
boolean values
Internally, 0 is false
All other values are true

Note these names are all lower case


The Character Type (1)

The data type is char



This is not the same as a String – String is a
class
Surround literal values with a single quote
character
Java uses Unicode encoding rather than
ASCII encoding
The Character Type (2)

Use C-like escape sequences for non-printable
characters







\b
\t
\n
\r
\"
\'
\\
-
backspace
tab
linefeed
carriage return
double quote
single quote
backslash
Variable Naming

Variables must begin with a letter and not contain
special characters




Underscore ( _ ) character is legal
Variable names are CASE SENSITIVE
All variables must be declared with an explicit type
Suggest using camel-case for variable names


First word is all lower case
Capitalize the first character of subsequent words
Declaring Variables


Note that variables should be initialized before they are used
Variable declarations can appear anywhere


They need not appear at the beginning of a module
type varname [,varname];
int counter;
float radius = 3.8;
boolean isValid = true;
char firstLetter = ‘a’;
int counter1, counter2;
Constants

The final keyword denotes a constant
A value can be assigned to a constant only once
Constants can be declared inside or outside of a
procedure
Constant names typically appear in upper case

Example:



final double PI = 3.14;
Operators (Arithmetic)




+ (Addition)
– Subtraction
* (Multiplication)
/ (Division)



If both operands are integers then integer division is
performed
 Integer division by 0 throws an exception
Otherwise floating point division is performed
% (Integer remainder)

Same as Mod function in VB
Increment and Decrement Operators

Increment (++)
x++;

// adds 1 to x
Decrement (--)
x--; // subtracts 1 from x

Prefix vs. postfix
y = 2 * ++x;

x is incremented before the multiplication
y = 2 * x++;

x is incremented after the multiplication
Operators ( Relational)

Relational operators return true or false






== (Equality)
!= (Inequality)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)
Operators (Logical)



&& (And)
|| (Or)
Logical operators support short circuiting


Evaluates from left to right
Once a sub-expression is deemed to be false,
evaluation of subsequent sub-expressions is
terminated
Operators (Bitwise)

Bitwise operators operate on whole number
types (We don't do much bit fiddling in
business applications)






& (And)
| (Or)
^ (XOr)
~ (Not)
>> (Shift right)
<< (Shift left)
Type Conversion (1)

When evaluating an expression, Java
converts operands to a common type before
evaluating the expression

Conversion is to the least restrictive type
Type Conversion (2)




Implicit type conversion is only performed from a more restrictive
type to a less restrictive type
Use a cast to perform explicit type conversion
Out of bounds casts will produce incorrect results
Same as CType function in VB.NET


Place desired type in parenthesis before the operand
Example to convert a double to an int

Fractional value is truncated rather than rounded
double x = 3.1415;
int nx = (int)x;
Type Conversion (3)


When casting a floating point number to a
whole number, the result is truncated
Call Math.round(x) to round a number as
in
double x = 9.997
int nx = (int)Math.round(x) // 10
Enumerations


Really the same as .NET enumerations
enum statement declares the enumeration
enum Size {SMALL, MEDIUM, LARGE,
REALLY_LARGE};
Strings – Introduction (1)


String is not a type in Java – It’s a built-in class
Strings are immutable



We will talk about string pools and why immutable strings are good
later
Character positions are 0-based
Java performs automatic garbage collection on strings

This is true of all other class instances
Strings – Introduction (2)



A string is a sequence of characters
Unlike C++, you need not suffix a string with a null byte
(+) is the string concatenation operator unlike (&) in VB
.NET


Note that the (+) operator is overloaded in this context
When concatenation is performed, non-string variables are
implicitly converted to strings
 Java (like .NET) can convert any type to a string
String Equality
Use the equals method of the
String class to test for equality
 == only tests for reference
equality not value equality

String greeting = "Hello";
greeting.equals("Hello");
String Methods (1)

substring extracts a sub string from a string


First argument contains starting character position (0based)
Second argument contains the number of characters
String myName = "Michael Ekedahl";
String s = myName.substring(0, 7);
String Methods (2)



equals method compares two strings for value
equality
equalsIgnoreCase compares for value equality
but comparison is case insensitive
Example:
String s1 = "Name";
String s2 = "Name";
Boolean b;
b = s1.equals(s2);
String Methods (3)

charAt gets the character at a position
 Returns a char data type
Position is 0 based
length gets the length of a string





The value is 1-based
Length returns an int
compareTo compares two strings for equality or
inequality
String Examples

Declare an empty string
String s = “”;

Declare an initialized string
String s = “Hello”;

Concatenate a string
s = s + “ World”;
Exiting a Program


By default, Java does not return an exit code
to the operating system
java.lang.System package contains an
Exit method to return a value from a Java
program
System.Exit(3)
Conditional Statements (1)



Note that the condition MUST be surrounded by parenthesis
Note the if and else are all lower case
Unlike VB, { } marks the block of the if statement
if (condition)
{
Statements;
}
else
{
Statements;
}
Conditional Statements (2)

The else if version has a similar syntax
if (condition)
{
Statements;
}
else if (condition )
{
Statements;
}
else
{
Statements;
}
Conditional Statements
(Example)

A simple if statement
if (value >= Math.PI)
{
System.out.println(“Greater than or =”);
}
else
{
System.out.println(“Less than”);
}
Multiple Selection

The switch statement is a limited form of
the if statement



Syntax is the same as in C
Similar to a VB Select Case statement
Condition is tested once for multiple
alternatives
Switch Statement Syntax
switch (expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
break;
}
Indeterminate Loops


Use an indeterminate loop when you don’t know in
advance how many times the loops statements will
execute
Java supports two forms


A while loop executes statements while a condition is
true
 Statements in the loop body may never execute
A do loop executes statements first and then tests the
condition
 Statements in the loop body will execute at least once
Indeterminate Loops (while)



Condition evaluates to a boolean value
Statements only execute while the condition is true
{ } mark the block of statements
while (condition)
{
statements;
}
Indeterminate Loops (do)

Executes statement body before testing the
condition
do
{
statements;
}
while (condition);
Determinate Loops




Determinate loops are used when the
iteration count is known in advance
Commonly used to iterate through the
elements of an array
Use whole numbers as floating point errors
will cause serious problems
Any for loop can be written as a while loop
but not the other way around
Determinate Loops (for)

Syntax
for (statement1; expression1; expression2)
{
statements;
}

statement1 initializes the counter
expression1 supplies the terminal condition
expression2 updates the counter

A semicolon separates each segment


For Loop example

Print the counting numbers from 1 to 10
int I;
for (i = 1; i <= 10; i++)
{
System.out.println(i);
}
Interrupting Control Flow




The break statement breaks control flow
causing a loop to exit
By itself, the statement causes a loop to exit
break label cause control to transfer to
label
continue causes control to transfer to the
start of the innermost enclosing loop
Arrays




Arrays contain multiple elements of the same type
Arrays are 0-based
Unlike C arrays, you cannot perform pointer
arithmetic
Java arrays perform bounds checking


No need to worry about walking over memory
Compared to VB, use [ ] instead of ( )
Declaring Arrays

Declare an array variable (note that the
following does not initialize the array)

Array points to null
int[] Alist;
Array Initializers

Arrays are initialized with the new keyword


New as the same meaning as it does in .NET
Note the following initializes the array with
100 elements having subscripts from 0 to 99
int[] AList = new int[100];
Array Initializers

Arrays can be initialized using C-like syntax:

Note that new keyword is omitted using this
syntax
int[] Alist = {1, 2, 3, 4, 5};

Or
Alist = new int[] {1, 2, 3, 4, 5};

The preceding syntax can be used to reinitialize
an existing array
Copying Arrays (1)


Again, this works the same way in .NET
Assignment of an array does not copy the
data – Rather the two variables point to the
same array (memory)
int[] AList = {1 ,2 ,3 ,4 , 5};
int[] BList = AList;

AList and BList both reference the same
array memory

Copy by reference
Copying Arrays (2)


Call System.arrayCopy to copy array data
thereby allocating new memory
System.arrayCopy(from, fromIndex, to
toIndex, count);
Arrays and Command Line
Parameters



Main accepts an array of string as an argument
Note that Java does not store the program name
as the first argument as we would in C
Print the first command line argument
Public static void main(String[] args)
{
System.out.println(args[0]);
}
Sorting Arrays

Call the Sort method of the Arrays class

Note Java uses a version of the QuickSort
algorithm
int[] Alist = {32, 24, 33, 18, 12};
Arrays.Sort(Alist);
MultiDimensional Arrays


Add additional subscripts for each dimension
Declare 2-dimensional array
int[][] TableArray;

Declare and initialize the array. Note the use
of nested { }
int[][] TableArray = { { 1,2 }, {3, 4} };
Exception Handing
(Introduction)



In a perfect world, users would enter data correctly
It’s not a perfect world though
Errors (exceptions) occur and cannot be prevented






File not found
Numeric overflow
Type conversion
The network died
Null references
Array out-of-bounds errors
Categorization of Errors

User input errors



Device errors



Printers turned off
Network errors
Physical limitations


Typos
Doing things that just don’t make sense
Out of disk or memory
Code errors

A method behaves incorrectly returning bad data
Ways to Deal with Errors

Return an error code when possible


This is the C way of doing things
Create an exception handler when an error
code won’t do it


A disk has not been placed in a disk drive
We cannot control network availability
Java Exceptions (Introduction)




Like everything else, Java exceptions are classes
Exception classes are hierarchical
The base class for all exceptions is Throwable
Two primary classes derive from Throwable



The Error class is for catastrophic internal errors
The Exception class contains derived classes for errors
that we can handle
See Figure 11-1 on page 559
Java Exceptions (Introduction)

Two categories of exception classes inherit
from Exception

RuntimeException





Bad casts
Out-of-bounds array access
Null pointer references
IT’S YOUR FAULT
Everything else

These are generally exceptions that cannot be
prevented
Examining Exceptions
Catching Exceptions
(Introduction)


If an exception is not caught, the applications
will end and a stack trace will be printed
To handle an exception, we set up a try,
catch, finally block

It’s really a glorified switch statement
Catching Exceptions (Syntax)
try
{
// statements that can cause an exception
}
catch (ExceptionType e)
{
// statements that handle the exception
}
finally
{
// statements that always execute
}
Catching Exceptions
(Example)
Public void read(String filename)
{
Try
{
// statements that may cause an
exception
}
Catch (IOException exception)
{
exception.printStackTrace();
}
}
Catching Multiple Exceptions



Some method calls may throw different
exceptions
In such a case, create multiple catch blocks
to handle these different exceptions
You must order catch blocks from the most
specific exception to the most general
exception
Understanding the finally
Block

It contains code that executes whether an
exception was thrown or not


One common use is to close an open file
Do NOT place return statements in a
finally block

The reason, a finally block executes before the
method ends
Understanding
Stack Traces (1)




Stack traces list all pending method calls
Stack traces are produced when a Java
program crashes
We can also get the stack trace at any time
during execution
See StackTraceTest.java
Understanding
Stack Traces (2)


Throwable class has a method
getStackTrace(); to get the current stack
trace
getStackTrace(); returns
StackTraceElement[]


Each element is a stack call
StackTraceElement members:



getLineNumber();
getMethodName();
toString();
Directories



Relative file names are based on the current
working directory
Call System.getProperty(“user.dir”) to
get the current directory
File.separator gets the file (path) separator


Use \\ to escape Windows file names
Forward slashes work but should be avoided for
compatibility with future Windows versions
Reading and Writing Files (FileReader,
FileWriter)

Constructors for both classes accept the file
name as the argument
FileReader read method reads a byte
FileWriter write method writes a byte

Note we must handle the possible exceptions


(FileInputStream,
FileOutputStream) Example

Code segment to copy a file
fin = new FileReader(source);
fout = new FileWriter(dest);
while (( b = fin.read()) != -1)
{
fout.write(b);
}
fin.close();
fout.close();
IO Layering (Introduction)





The Java approach is much different than the .NET
approach
The problem
FileInputStream can only read bytes
DataInputStream can read numeric types but
has no notion of a file
There are comparable FileOutputStream and
DataOutputStream classes
IO Layering (Introduction)

The solution:


Java uses a layering mechanism to separate
high/low level responsibility
We call these filtered streams
 Compare to pieces of pipe in a pipeline
IO Layering (Example)

Create an input stream to read numbers
DataInputStream din =
new DataInputStream( new
BufferedInputStream( new
FileInputStream(“somefile.dat”)));
Stream Buffering



By default, stream IO is not buffered
A disk request is generated for each IO
operation
Use the following streams to do buffered IO


BufferedInputStream
BufferedOutputStream
DataInputStream Class







Methods read particular data types
readBoolean();
readChar();
readDouble();
readFloat();
readInt();
readLong();
DataOutputStream Class

Methods write particular data types






writeBoolean(boolean b);
writeChar(char c);
writeDouble(double d);
writeFloat(float f);
writeInt(int i);
writeLong(long l);
DataOutputStream
Example

Write a list of Numbers (See WriteNumbers.java)
dos = new DataOutputStream(new
BufferedOutputStream(new
FileOutputStream("junk.dat")));
for (i=0;i<1000;i++)
{
dos.writeInt(i);
}
dos.close();
DataInputStream Example

Read the list of numbers (See ReadNumbers.java)
dos = new DataInputStream(new
BufferedInputStream(new
FileInputStream("junk.dat")));
for (i=0;i<1000;i++)
{
value = dos.readInt();
System.out.println(value);
}
dos.close();
Reading and Writing Textual Streams




Remember that Java uses Unicode internally
Consuming systems may want ASCII or other
Unicode formats
InputStreamReader class reads text files
converting data from one character set to
another
PrintWriter class writes text files
The PrintWriter Class
(Writing Text Files)

Use the PrintWriter to write formatted
textual output


Call print(string) to write output without a
line terminator
Call println(string) to write output with a
line terminator
The BufferedReader Class
(Reading Text Files)


The BufferedReader Class reads text files
a line at a time with the readLine method
Use the StringTokenizer class to parse
delimited files

StringTokenizer has the same purpose as
the .NET Split method
The StringTokenizer Class

Constructor takes two arguments



The first is the input string
The second argument is a String containing the
delimiter or delimiters
Methods



nextToken() gets the next token
countTokens() gets the number of tokens
remaining
hasMoreTokens() returns true if there are
more tokens
The StringBuilder Class




It’s now to Java 5.0
Remember that strings are immutable
Lots of string concatenation is very inefficient
The StringBuilder class works like an
ArrayList for strings