Transcript Document

A Quick Tour of Java
In this lesson you will be learning about:
The Java Platform.
Basics elements of the Java Language:
 Variables
 Named Constants
 Flow of Control
Classes and Objects.
How to compile and execute a Java program.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
1
Getting Started
Java programs are built from classes.
A class is a template to build objects and contains members of the
following type:
 Fields – Data belonging either to class or object of the class.
 Methods – Collections of statements that operate on fields.
 Classes – Nested or inner classes defined inside a class.
Example: First.java file
class First {
public static void main(String[] args) {
System.out.println(“The first program in Java – PRO404”);
}
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
2
Java Platform – JDK 1.2
Java Platform has 3 components:
 1. Java Programming Language.
 2. Java Packages.
 3. Java Virtual Machine.
Java Programming Language – called simply Java.
 General-purpose, ease of programming, safety features.
Java Packages.
 Grouping of related interfaces and classes. Ex: java.lang.
Java Virtual Machine.
 The Java virtual machine is an abstract computing machine.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
3
How to Use Java Platform
Learn Java Programming Language Concepts,
Vocabulary, Syntax, Semantics and Patterns.
 Write program and safe source code in files according with the Java
Programming Language rules.
Learn the structure of packages that come with JDK.
 Use classes already defined in the JDK packages according with your
program design. Do not invent the wheel!
Compile and run your program using tools from JDK.
 Compile using java compiler: javac MyProgramName.java
 Run your program using JVM: java MyProgrmName
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
4
From Birth to Execution
1. Coding: Java code is produced by the programmer.
COMPILER:
javac
2. Compiling: Build the Java program into byte-code, which is saved as a
".class" file.
JAVA VIRTUAL MACHINE:
java
3. Loading: The class file is loaded by the Java Virtual Machine with its
attached digital signature.
4. Bytecode Verification: The JVM verifies the class file digital signature.
The JVM is simply an interpreter.
6. Internal Integrity: Verification checks are made to insure that the
loaded Java program is well formed. Data types are verified along with
other syntax structure.
7. Execution: Program execution begins from the main entry point.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
5
Variables
Java has build-in primitives to support boolean, character, integer
and floating-point values.
---------------------------------------------------------------------------------------- boolean either true or false
boolean b = true;
----------------------------------------------------------------------------------------- char
16-bit Unicode 1.1 character
char ch = ‘J’;
----------------------------------------------------------------------------------------- byte
8-bit integer (signed) byte bt = 127;
 short
16-bit integer (signed) short sh = 32767;
 int
32-bit integer (signed) int i = 2147483647;
 long
64-bit integer (signed) long l = 9223372036854775807L;
------------------------------------------------------------------------------------------ float
32-bit floating-point (IEEE 754-1985) float f = 1.0f;
 double
64-bit floating-point (IEEE 754-1985) double d = 1.e-1;
------------------------------------------------------------------------------------------Copyright @ 2000 Jordan Anastasiade. All rights reserved.
6
Comments, Named Constants
Comments in Code – enable to write descriptive text.
 /* Comment type 1 – This text is ignored by the compiler */
 // Comment type 2 – The text up to the end of line is ignored
 /** Documentation comment is extracted by javadoc tool */
Named Constants – name used to describe constants.
 public static final int MAX_INDEX = 1000;
 class MathConstant {
static final double E = 2.71; //the base of the natural logarithms
static final double PI = 3.14;
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
7
Flow of Control
Flow of control is the term used for describing which
statements are executed in a program.
Flow statements are:






if – else
for
switch
do – while
while
block of code – statements group within { and }.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
8
Fibonaci sequence
The Fibonacci sequence is an infinite sequence that starts with terms 1 and 1 and each
successive term is the sum of the previous two terms.
class Fibonacci {
/** Print out the Fibonacii numbers
*/
static final int MAX_INDEX = 10;
public static void main(String[] args) {
int lo = 1;
int hi = 1;
System.out.println(“1: “ + lo);
for (int i = 2; i < MAX_INDEX; i++) {
System.out.println(“i: “ + hi);
hi = lo + hi;
//new hi is the sum of previous two terms.
lo = hi – lo;
//new lo is the old hi i. e. sum – old hi
}
}
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
9
Classes and Objects
Each class has three kinds of members:
 Fields are data variables of a class that store results of computations
performed by class’s methods.
 Methods contain the executable code, built from statements.
 Classes and interfaces can in the same time be members of a class.
Every object in Java has a state and a behavior.
class Point {
private double x_ = 0;
private double y_ = 0;
//the state of object is defined by values of its data
/* the behaviors of an object is defined by its methods */
public void movePoint(double x, double y) {
x_ = x; y_ = y;
}
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
10
Creating Objects
Objects are created using an expression containing
the new keyword.
Point lowerLeft = new Point();
All objects are allocated within an area of system
memory known as Heap and are accessed only via an
object reference.
Each Point object is unique and has its own copy of x and y fields.
Point object
x=0
y=0
Memory Heap
lowerLeft reference
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
11
Identifiers
The name you choose for anything in java is called a java identifier.
Identifiers must start with a letter, an underscore ( _ ) or a dollar
sign ( $ ) followed by letters or digits.
There is no limit for the length of identifiers and they are composed
from the Unicode charter set.
Ex: toStart _color
$accountÉvalué
übung
Java language keywords cannot be used as
identifiers.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
12
Java Keywords
abstract
byte
char
continue
double
final
for
implements
int
native
private
return
super
this
transient
volatile
boolean
case
class
default
else
finally
goto
import
interface
new
protected
short
switch
throw
try
while
break
catch
const
do
extends
float
if
instanceof
long
package
public
static
synchronized
throws
void
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
13
Literals
Each type in Java has literals, which are the way that constant
values of that type are written.
 Integer constants are string of octal, decimal, hexadecimal digits.
Ex: decimal 58L, octal 027, hexadecimal 0x8AF
 Floating-point numbers are decimal numbers optional followed by an
exponent.
Ex: double 18. .234E3 1.8e-1;
float 1.234f 0.2e-5F
 Characters literals appear between single quotes. Any valid Unicode
character can appear between the quotes. Certain special characters are
represented as escape sequence.
Ex: ‘J’, ‘A’, ‘V’, ‘A’ ‘\n’ newline ‘\u000A’ ‘\t ‘tab ‘\u0009’
\ddd a char by octal value d 0-7
 String literals appear between double quote. Ex: “JAVA”
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
14
Numeric operators in Java
Prec Operator Description
Example
1
1
1
1
2
2
2
3
3
5
5
5
5
6
6
13
k++
k-+value
-value
x * y
x / y
x % y
x + y
x - y
x < y
x > y
x <= y
x >= y
x == y
x != y
x += y
++
-+
*
/
%
+
<
>
<=
>=
==
!=
op=
Increment by 1(or 1.0)
Decrement by 1(or 1.0)
Unary plus
Unary minus
Multiplication
Division
Modulo
Addition
Subtraction
Less than
Greater than
Less than/equal
Greater than/equal
Equals (identical values)
Is not equal to
op assignment(+ =, - =, *=, etc)
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
15
Bitwise and logic operators
Prec
Operator Type
Description
Example
1
1
4
4
4
5
6
6
7
7
8
8
9
9
~
!
<<
>>
>>>
instanceof
==
!=
&
&
^
^
|
|
Unary bitwise complement
Unary logical complement
Left shift
Right shift (keep sign)
Right shift (zero fill)
Tests class membership
Equals (same object)
Unequal (different object)
Bitwise AND
Logical AND
Bitwise XOR
Logical XOR
Bitwise OR
Logical OR
~x
!b
x << 2
x >> 5
x >>> 3
o instanceof X
x == y
x != y
x&y
b1 & b2
x ^ y
b1 ^ b2
x | y
b1 | b2
Integral
Logical
Integral
Integral
Integral
Obj type
Object
Object
Integral
Logical
Integral
Logical
Integral
Logical
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
16
Bitwise and logic operators (continued)
Prec Operator Type
Description
Examp.
10
11
12
13
13
13
13
13
13
13
13
13
13
Logical AND (conditional)
Logical OR (conditional)
Conditional (ternary)
Assignment
Left shift with assignment
Right shift with assignment
Right shift, zero fill, assign
Bitwise AND with assign
Logical AND with assign
Bitwise OR with assignment
Logical OR with assignment
Bitwise XOR with assignment
Logical XOR with assignment
b && c
b1 || b2
b?x:y
x=1
x <<= 2
x =>> 3
x =>> 4
x &= y
b1 &=b2
x |= y
b1 |=b2
x ^= y
b1 ^=b2
&&
||
?:
=
<<=
>>=
>>>=
&=
&=
|=
|=
^=
^=
Logical
Logical
Logical
Variable,any
Binary
Binary
Binary
Binary
Logical
Binary
Logical
Binary
Logical
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
17
Bitwise logic rules
AND 0
1
0
0
0
1
0
1
OR
0
1
0
0
1
1
1
1
XOR 0
1
0
0
1
1
1
0
0&0=0
1&0=0
0&1=0
1&1=1
0|0=0
1|0=1
0|1=1
1|1=1
0^0=0
1^0=1
0^1=1
1^1=0
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
18
Bitwise operations on short
primitives (16 bit integers)
Binary
Operation
Decimal
Hex
0000 0000 0101 0100
op1
84
0x0054
0000 0001 0100 0111
op2
327
0x0147
0000 0000 0100 0100
op1 & op2
68
0x0044
0000 0001 0101 0111
op1 | op2
343
0x0157
0000 0001 0001 0011
op1 ^ op2
275
0x0113
1111 1110 1011 1000
~op2
-328
0xFEB8
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
19
Results of some bit-shifting
0000 0000 0000 0000 0000 0000 0110 0011 starting a = 99
0
0
0
0
0
0
6 3
a = 0x00000063
0000 0000 0000 0000 0000 0011 0001 1000 after a << 3 (792)
0
0
0
0
0
3
1
8
a = 0x00000318
0000 0000 0000 0000 0000 0000 0001 1000 after a >> 2 (24)
0
0 0
0 0
0
1
8
a = 0x00000018
1111 1111 1111 1111 1111 1111 1001 1101 stating b = -99
F F F
F
F F
9
D
b = 0xFFFFFF9D
1111 1111 1111 1111 1111 1111 1111 1001 after b >> 4 = -7
F F
F
F
F
F
F 9
b = 0xFFFFFFF9
0000 0000 0000 1111 1111 1111 1111 1111 after b >>> 12 = 1048575
0
0 0
F F
F
F
F
b = 0x000FFFFF
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
20
Type Conversions
Java is a strong typed language.
Implicit conversion for primitive value: any numeric value can be
assigned to any numeric value whose type supports a larger range of values.
byte  short  int  long  float  double
Explicit conversion – casting.
 boolean type doesn’t allow any casting at all.
 A char can be cast to any integer type and vice versa excepting to a
short type. When chart is cast to int type upper bits are filled with zeros.
Attention: Interger types are converted by chopping off the upper bits.
If the larger integer has a value outside the range off the smaller type, dropping the
upper bits changes the value, including possibly changing sign.
Ex:
short sh = -129;
byte b = (byte)sh; b will have the value 127
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
21
if, if-else, if else –if else
1.
if (boolean-expression) {
statements;
}
2.
if (boolean-expression) {
statements;
} else {
statements;
}
3.
if (boolean-expression) {
statements;
} else if (boolean-expresion ) {
statements;
} else {
statements;
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
22
for Statement
A for statement should have the following form:
for (initialization; condition; update) {
statements;
}
Ex:
for (k = 0, flag; k < 10 && flag; k++ ) {
...
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
23
while, do - while Statements
while, do-while and for control looping are
classified as iteration statements.
while (condition) {
statements;
}
do {
statements;
} while (condition);
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
24
break - Labeled break
A break “drops out of the bottom” of the loop. The break statement
with no label attempts to transfer control to the innermost enclosing
switch, for, while or do-while of immediately enclosing
statement.
A labeled break drops out of the bottom of the end of the loop
denoted by the label.
Ex:
out:
for (int i = 0; i < 10; i++ ) {
for (int k = 0; k < 10; k++) {
if (i == k)
break out;
}
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
25
continue – Labeled continue
A plain continue goes to the top of the innermost loop
and continues.
A labeled continue goes to the label and re-enters the
loop right after that label.
Ex: Calculates the factorials of odd number.
outerLoop: for (int i = 0; i < limit; i++ ) {
for (int k = 2; k < i; k++) {
if (i % 2)
continue outerLoop;
factory *= i;
}
}
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
26
switch
The switch is classified as a selection statement.
switch (integral-selector) {
case integral-value1:
statements;
break;
default:
statements;
}
Integral-selector is an expression that produces an integral value.
The switch compares the result of integral-selector to each integral-value. If it
finds a match, the corresponding statement (simple or compound) executes. If no
match occurs, the default statement executes.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
27
Array
An array is simply a sequence of either objects or primitives, all the same
type and accessed together under one identifier name.
Arrays are implicit extensions of Object.
Arrays are defined and used with square-brackets indexing operator [ ].
int [ ] integerArray = new int[3];
A Java array is guaranteed to be initialized and cannot be accessed
outside of its range.
for (int k = 0; k < integerArray.length; k++)
integerArray[k] = k;
Creating an array of objects, one are really creating an array of
references, and each of those references is automatically initialized to null.
CelestialBody[ ] celBoliesArray = new CelestialBody[5];
Regardless of what type of array you’re working with, the array
identifier is actually a reference to a true object that’s created on the heap.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
28
Strings
Java strings are standard objects with built-in language support.
The String class represents character strings. All string literals in
Java programs, such as "abc", are implemented as instances of
String class.
Strings are constant; their values cannot be changed after they are
created. Stringbuffer class supports mutable strings. Because String
objects are immutable they can be shared.
For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
29
String Examples
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
The basic two methods:
int
length();
Returns the length of this string.
char
charAt(int index); Returns the character at the specified index.
The Java language provides special support for the string concatentation
operator ( + ), and for conversion of other objects to strings. String
concatenation is implemented through the StringBuffer class and its append
method. String conversions are implemented through the method toString,
defined by Object and inherited by all classes in Java.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
30
Strings’ Methods
Constructor Summary:
String();
String(byte[] bytes);
String(byte[] bytes, String enc);
String(char[] value);
String(char[] value, int offset, int count);
String(String value);
String(StringBuffer buffer);
char
int
int
charAt(int index);
compareTo(String anotherString);
compareToIgnoreCase(String str);
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
31
Strings’ Methods (cont)
static
static
String
copyValueOf(char[] data, int offset, int count);
boolean equals(Object anObject);
boolean equalsIgnoreCase(String anotherString);
byte[]
getBytes(String enc);
int
hashCode();
int
indexOf(int ch);
int
lastIndexOf(int ch);
int
length();
String
replace(char oldChar, char newChar);
boolean startsWith(String prefix);
String
substring(int beginIndex, int endIndex);
char[]
toCharArray();
String
toLowerCase();
String
toString();
String
toUpperCase();
String
trim();
String
alueOf(Object obj);
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
32
Conclusions
After completion of this lesson you should know:
How to write a simple Java Program.
How to work with primitives: Integers and Floats.
To use Java Tools: compiler, interpreter, debugger.
Copyright @ 2000 Jordan Anastasiade. All rights reserved.
33