Java Basic Syntax PDF
Java Basic Syntax PDF
Java Basic Syntax PDF
programming
Agenda
Creating, compiling, and executing simple
Java programs
Accessing arrays
Looping
Using if statements
Comparing strings
Building arrays
One-step process
Two-step process
Getting Started
Name of file must match name of class
It is case sensitive, even on Windows
www.corewebprogramming.com
Example
File: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world.");
}
}
Compiling
DOS> javac HelloWorld.java
Executing
DOS> java HelloWorld
Hello, world.
www.corewebprogramming.com
More Basics
Use + for string concatenation
Arrays are accessed with []
www.corewebprogramming.com
Example
File: ShowTwoArgs.java
public class ShowTwoArgs {
public static void main(String[] args) {
System.out.println("First arg: " +
args[0]);
System.out.println("Second arg: " +
args[1]);
}
}
www.corewebprogramming.com
Example (Continued)
Compiling
DOS> javac ShowTwoArgs.java
Executing
DOS> java ShowTwoArgs Hello World
First args Hello
Second arg: Class
DOS> java ShowTwoArgs
[Error message]
www.corewebprogramming.com
Looping Constructs
while
while (continueTest) {
body;
}
do
do {
body;
} while (continueTest);
for
for(init; continueTest; updateOp) {
body;
}
8
www.corewebprogramming.com
While Loops
public static void listNums1(int max) {
int i = 0;
while (i <= max) {
System.out.println("Number: " + i);
i++; // "++" means "add one"
}
}
www.corewebprogramming.com
Do Loops
public static void listNums2(int max) {
int i = 0;
do {
System.out.println("Number: " + i);
i++;
} while (i <= max);
// ^ Dont forget semicolon
}
10
www.corewebprogramming.com
For Loops
public static void listNums3(int max) {
for(int i=0; i<max; i++) {
System.out.println("Number: " + i);
}
}
11
www.corewebprogramming.com
12
www.corewebprogramming.com
Loop Example
File ShowArgs.java:
public class ShowArgs {
public static void main(String[] args) {
for(int i=0; i<args.length; i++) {
System.out.println("Arg " + i +
" is " +
args[i]);
}
}
}
13
www.corewebprogramming.com
If Statements
Single Option
if (boolean-expression) {
statement;
}
Multiple Options
if (boolean-expression) {
statement1;
} else {
statement2;
}
14
www.corewebprogramming.com
Boolean Operators
==, !=
&&, ||
Logical negation.
15
www.corewebprogramming.com
Example: If Statements
public static int max2(int n1, int n2) {
if (n1 >= n2)
return(n1);
else
return(n2);
}
16
www.corewebprogramming.com
Strings
String is a real class in Java, not an array of
characters as in C and C++.
The String class has a shortcut method to
create a new object: just use double quotes
This differs from normal objects, where you use the new
construct to build an object
17
www.corewebprogramming.com
www.corewebprogramming.com
Building Arrays:
One-Step Process
Declare and allocate array in one fell swoop
type[] var = { val1, val2, ... , valN };
Examples:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2),
... };
19
www.corewebprogramming.com
Building Arrays:
Two-Step Process
Step 1: allocate an array of references:
type[] var = new type[size];
Eg:
20
www.corewebprogramming.com
Multidimensional Arrays
Multidimensional arrays are implemented as
arrays of arrays
int[][] twoD = new int[64][32];
String[][] cats = { { "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted",
"red-point" } };
1 },
2, 3, 4},
5 },
6, 7 } };
www.corewebprogramming.com
TriangleArray: Example
public class TriangleArray {
public static void main(String[] args) {
int[][] triangle = new int[10][];
for(int i=0; i<triangle.length; i++) {
triangle[i] = new int[i+1];
}
}
22
www.corewebprogramming.com
TriangleArray: Result
> java TriangleArray
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
23
www.corewebprogramming.com
Data Structures
Java 1.0 introduced two synchronized data
structures in the java.util package
Vector
A strechable (resizeable) array of Objects
Time to access an element is constant regardless of
position
Time to insert element is proportional to the size of the
vector
In Java 2 (eg JDK 1.2 and later), use ArrayList
Hashtable
24
www.corewebprogramming.com
removeElement/removeElementAt
Removes an element from the vector
firstElement/lastElement
Returns a reference to the first and last element, respectively
(without removing)
elementAt
Returns the element at the specified index
indexOf
Returns the index of an element that equals the object specified
contains
Determines if the vector contains an object
25
www.corewebprogramming.com
size
The number of elements in the vector
capacity
The number of elements the vector can hold before
becoming resized
26
www.corewebprogramming.com
remove/clear
Removes a particular entry or all entries from the hashtable
containsKey/contains
Determines if the hashtable contains a particular key or element
keys/elements
Returns an enumeration of all keys or elements, respectively
size
Returns the number of elements in the hashtable
rehash
Increases the capacity of the hashtable and reorganizes it
27
www.corewebprogramming.com
Collections Framework
Additional data structures added by Java 2
Platform
Collection
Map
HashMap
Hashtable
Set
HashSet
SortedSet
List
ArrayList
LinkedList
Vector
SortedMap
TreeMap
TreeSet
Interface
28
Concrete class
Synchronized
Access
www.corewebprogramming.com
Collection Interfaces
Collection
Abstract class for holding groups of objects
Set
Group of objects containing no duplicates
SortedSet
Set of objects (no duplicates) stored in ascending order
Order is determined by a Comparator
List
Physically (versus logically) ordered sequence of objects
Map
Stores objects (unordered) identified by unique keys
SortedMap
Objects stored in ascending order based on their key value
Neither duplicate or null keys are permitted
29
www.corewebprogramming.com
Collections Class
Use to create synchronized data structures
List list = Collection.synchronizedList(new ArrayList());
Map map =
Collections.synchronizedMap(new HashMap());
max, min
reverse
shuffle
30
www.corewebprogramming.com
Wrapper Classes
Each primitive data type has a
corresponding object (wrapper class)
Primitive
Data Type
byte
short
int
long
float
double
char
boolean
Corresponding
Object Class
Byte
Short
Integer
Long
Float
Double
Character
Boolean
www.corewebprogramming.com
Wrapper Uses
Defines useful constants for each data type
For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
32
www.corewebprogramming.com
33
Basic Form
try {
statement1;
statement2;
...
} catch(SomeException someVar) {
handleTheException(someVar);
}
34
www.corewebprogramming.com
Exception Hierarchy
Simplified Diagram of Exception Hierarchy
Throwable
Exception
35
IOException
Error
RuntimeException
www.corewebprogramming.com
Throwable Types
Error
A non-recoverable problem that should not be caught
(OutOfMemoryError, StackOverflowError, )
Exception
An abnormal condition that should be caught and handled
by the programmer
RuntimeException
Special case; does not have to be caught
Usually the result of a poorly written program (integer
division by zero, array out-of-bounds, etc.)
A RuntimeException is considered a bug
36
www.corewebprogramming.com
(ExceptionType1 var1) {
something
(ExceptionType2 var2) {
something else
37
www.corewebprogramming.com
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
}
38
www.corewebprogramming.com
www.corewebprogramming.com
Thrown Exceptions
If a potential exception is not handled in the
method, then the method must declare that
the exception can be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
www.corewebprogramming.com
Summary
Loops, conditional statements, and array
access is the same as in C and C++
String is a real class in Java
Use equals, not ==, to compare strings
You can allocate arrays in one step or in two
steps
Vector or ArrayList is a useful data
structure
Can hold an arbitrary number of elements
www.corewebprogramming.com
core
programming
Questions?
42