Module 2: Basic Java Programming Language

•Sun Certified Programmer for the Java 2 Platform, Standard Edition 1.2 •Sun Certified Business Component Developer for java 2 Platform, Enterprise Edition 1.3 •IBM Test 486 Enterprise Connectivity with J2EE 1.3 •IBM Test 287 Enterprise Application Development with IBM WebSphere Studio, V5.0

BrainStream Co., Ltd.,

l Language Fundamentals l Operators and Assignments l Flow Control

BrainStream Co., Ltd.,2

Source Files
l All Java source files must end with ".java" l Source file should contain, at most, one top-

level public class definition. l if a public class is present, class name should match the unextended filename. public class Demo{} class Ok{} class Yes{}
BrainStream Co., Ltd.,3

Top-Level Elements

1. 2. 3.

These elements are not required. If they are present, then they must appear in order: Package declaration package javafun.lab2; Import java.util.Vector; Import statements import java.awt.*; Class definitions public class Demo{

BrainStream Co., Ltd.,4

l Package: source placed in directory

hierarchy that reflects package names.
package javafun.lab2; Import java.util.Vector; import java.awt.*; public class Demo{ }

BrainStream Co., Ltd.,5

Current Directory C:\

Change to E:\

BrainStream Co., Ltd.,6

Class Path
l Use Jar file in class-path “c:\utils.jar”

BrainStream Co., Ltd.,7

Class Path
l Use –classpath “.” means current directory.
Current Directory C:\


BrainStream Co., Ltd.,8

Package Recommendation
l <company-name>.<objective>
– – –** org.omg.* com.brainstream.iself.* com.brainstream.iself.applet.* com.brainstream.iself.servlet.*
BrainStream Co., Ltd.,9

l <company-name>.<project>
– – –

l Import: either an individual class &


package javafun.lab2; import java.awt.*; import java.util.Vector; public class Demo{ }
BrainStream Co., Ltd.,10

Import Recommendation
package javafun.lab2; import java.util.Vector; public class Demo{ Vector v = new Vector(); } package javafun.lab2; public class Demo{ java.util.Vector v = new java.util.Vector(); }
BrainStream Co., Ltd.,11

package javafun.lab2; import java.util.*; public class Demo{ Vector v = new Vector(); }

l Class: Should start with Capital letter.

package javafun.lab2; Import java.util.Vector; import java.awt.*; public class Demo{} class Ok{} class Yes{} compile

BrainStream Co., Ltd.,12

l Identifier is a word used by a programmer to

name a variable, method,class. l Must begin with a letter, a dollar sign ($), or an underscore (_) l Subsequent characters may be letters, dollar signs, underscores, or digits. l Don’t use Keywords and reserved words.
BrainStream Co., Ltd.,13

Java Keywords and Reserved Words
l goto and const are reserved: Although they

have no meaning in Java.

BrainStream Co., Ltd.,14

Identifier Example
test Bigtest $test 1test !test test test Start with digit. Must start with letter, $ or _ Can't use space
BrainStream Co., Ltd.,15

l Java has 3 comments l /* This is a comment */ l // one line comment l /** comment which is used by javadoc.exe to

generate HTML docuementation **/

BrainStream Co., Ltd.,16

l Example

BrainStream Co., Ltd.,17

l Javadoc command.

BrainStream Co., Ltd.,18

Primitive Data Types
l 8 primitive types defined in Java.
– – – –

Integral Floating Logical Textual

byte, short, int, long double and float boolean char <variable name> ;

l Variable declaration
– –

<primitive type> int i = 0;

BrainStream Co., Ltd.,19

Primitive Data Types
l Primitive Data Types and Their Effective Sizes

BrainStream Co., Ltd.,20

Four Signed Integral Data Types
l Ranges of the Integral Primitive Types.

BrainStream Co., Ltd.,21

l Char type is integral but unsigned. l Range of char is 0 - 2 16-1 l Java characters are in Unicode. l If the most significant 9 bits of a char are all 0,

then the encoding is the same as 7-bit ASCII.

BrainStream Co., Ltd.,22

Two Floating-Point
l float l double l follow IEEE 754


double d = -10.0 / 0.0; if (d == Double.NEGATIVE_INFINITY) System.out.println(“d just exploded: “ + d);
Output: d just exploded:-Infinity
BrainStream Co., Ltd.,23

What happens on overflow?
l Integer Overflow.

exception infinity

l Floating Point Overflow.

BrainStream Co., Ltd.,24

Boolean Literals
l Valid literals of boolean type are true and

boolean isBig = true; boolean isLittle = false;

BrainStream Co., Ltd.,25

Char Literals
l Enclosing desired character in single quotes.

char c = ‘w’

l Character literal is as a Unicode value

specified using four hexadecimal digits, preceded by \u

char c = ‘\u4567’

BrainStream Co., Ltd.,26

Char Literals
l Special Symbols
– – – – – – – –

‘\n’ for new line ‘\r’ for return ‘\t’ for tab ‘\b’ for backspace ‘\f’ for formfeed ‘\’’ for single quote ‘\”’ for double quote ‘\\’ for backslash
BrainStream Co., Ltd.,27

Integral Literals
l May be expressed in decimal, octal, or

hexadecimal. l Octal, prefix the literal with 0 (zero). l Hexadecimal, prefix the literal with 0x or 0X;
– – –

Decimal à 28 Octal à 034 Hexadecimal à 0x1c, 0x1C, 0X1c, 0X1C
BrainStream Co., Ltd.,28

Floating-Point Literals
l A decimal point: 1.414 l Letter E or e, indicating scientific notation:

4.23E+21 l Suffix F or f, indicating a float literal: 1.828f l Suffix D or d, indicating a double literal: 1234d l A floating-point literal with no F or D suffix defaults to double type.
BrainStream Co., Ltd.,29

l String is not a primitive but a class, is used to

represent sequences of characters. l Its literal is enclosed in double quotes, “ ”. l Example:

String s = “Hello World”

BrainStream Co., Ltd.,30

Class Fundamental
l Member Variable: is created when an

instance is created, and is destroyed when the object is destroyed. l Automatic Variable (method local): create in Member Variable method.
Automatic Variable

BrainStream Co., Ltd.,31

Member Variable
l Initialization Values for Member Variables.

BrainStream Co., Ltd.,32

Automatic Variable
l Not initialized by the system l Every automatic variable must be explicitly

initialized before being used.

The local variable automatic may not have been initialized

BrainStream Co., Ltd.,33

Argument Passing
l Copy of argument is passed.

int abc = 0; System.out.println(“>”+abc); replace(abc); System.out.println(“>”+abc); public void replace(int abc){ abc = abc +1; } BrainStream Co., Ltd.,34


Primitive type >0 >0

Argument Passing
l Object reference Button abc = new Button(“ABC”); System.out.println (“>”+abc.getLabel()); change(abc); System.out.println (“>”+abc.getLabel()); public void change(Button abc){ abc.setLabel(“XYZ”); }
BrainStream Co., Ltd.,35


Object >ABC >XYZ



Argument Passing
l Be careful! Button abc = new Button(“ABC”); >ABC System.out.println(“>”+abc.getLabel()); >ABC replace(abc); System.out.println(“>”+abc.getLabel()); public void replace(Button abc){ abc “ABC” abc= new Button(“XYZ”); } XYZ
BrainStream Co., Ltd.,36

Operators and Assignments
Unary Operators. l Arithmetic Operators. l Shift Operators. l Comparison Operators. l Equality Comparison Operators. l Bitwise Operators. l Boolean Operations. l Short-Circuit Logical Operators. l Conditional Operator. l Assignment Operators.
BrainStream Co., Ltd.,37

l Operators in Java, in Descending Order of


BrainStream Co., Ltd.,38

Evaluation Order
l Operand are evaluated from left to right.

int[] a = {4,4}; int b = 1; a[b] = b = 0; System.out.println(a[0]); System.out.println(a[1]); System.out.println(b);

a[b] = b = 0;
a[b] à a[1]

a[b] = b = 0;
b àb

a[b] = b = 0;

BrainStream Co., Ltd.,39

Evaluation Order
l Assignment are evaluated from right to left.

a[b] = b = 0;

a[b] = 0;
a[1] a[1] = 0

int[] a = {4,4}; int b = 1; a[b] = b = 0; System.out.println(a[0]); 4 System.out.println(a[1]); 0 System.out.println(b); 0

BrainStream Co., Ltd.,40

Evaluation Order
l (R to L) : l (L to R) : l (L to R) : l (L to R): l (L to R) : l (L to R) : l (L to R) :

++ * + << < == &

-/ >> > !=

+ - ~ ! (data type) % >>> <= >=


BrainStream Co., Ltd.,41

Evaluation Order
l (L to R) : l (L to R) : l (L to R) : l (L to R) : l (R to L) : l (R to L) :

^ | && || ?: = *= &= ^=

/= |=



BrainStream Co., Ltd.,42

Unary Operators
l Increment and decrement operators: ++ -l Unary plus and minus operators: + l Bitwise inversion operator: ~ l Boolean complement operator:! l Cast:()

BrainStream Co., Ltd.,43

Increment and decrement
l Adding or subtracting 1.

int x = 10 à ++x à11

l X++ vs. ++X ,Pre-Modify and Post-Modify

BrainStream Co., Ltd.,44

Unary plus and minus operators
l Unary + has no effect positive nature of a

numeric literal. l Unary - negates an expression.
x = -3; y = +3; z = -(y + 6);

Z = -9

BrainStream Co., Ltd.,45

Bitwise inversion operator
l ~ operator works by converting all 1 bits in a

binary value to 0s and all 0 bits to 1s.

~00001111 à 11110000

BrainStream Co., Ltd.,46

Boolean complement operator
l The ! operator inverts the value of a boolean

expression. l !true gives false l !false gives true. l Often used in the test part of an if() statement. If(! (obj instanceof String) ) {…}
BrainStream Co., Ltd.,47

Cast Operator: (type)
l Casting is used for conversion of

type of an

expression. l Compiler and runtime system check for conformance with typing rules.
– –

int x = (int)4.50; String s = (String)vector.get(0);

BrainStream Co., Ltd.,48

Arithmetic Operators
l Multiplication and Division * and / l Modulo Operator: % l Addition and Subtraction Operators: + and -

BrainStream Co., Ltd.,49

Multiplication and Division Operators
l Multiply first and then divide, which risks

overflow l divide first and then multiply, which almost definitely loses precision.
int a=12345,b=234567,c,d; long e,f; c=a*b/b; d=a/b*b; e=(long)a*b/b; f=(long)a/b*b;
BrainStream Co., Ltd.,50

-5965 0 12345 0

Modulo Operator
l Gives a value that is related to the remainder

of a division.
– – – –

7 divided by 4 gives 1, remainder 3. x = 7 % 4; à x=3 -5%2 = -1 -5%-2 = -1

BrainStream Co., Ltd.,51

Addition and Subtraction
l + expression with two operands of primitive

numeric type, the result:
– – – –

Is of a primitive numeric type. Is at least int, because of normal promotions.
l ‘a’+’a’ = 194

Is of a type at least as wide as the wider of the two operands. Promoting operands to result typeà might result in overflow or loss of precision.
BrainStream Co., Ltd.,52

Addition and Subtraction

+ expression with any operand that is not of primitive numeric type.

At least one operand must be a String object or literal; otherwise expression is illegal.
System.out.println((new Vector())+(new Vector())); ü System.out.println(“a”+(new Vector())+(new Vector()));

Any remaining non-String operands are converted to String, and result of the expression is the concatenation of all operands.

BrainStream Co., Ltd.,53

Shift Operators
l Left-shift << l Right-shift >> l Unsigned right-shift >>>

BrainStream Co., Ltd.,54

Comparison Operators
l Less than: < l Less than or equal to: <= l Greater than: > l Greater than or equal to: >=

int x = 5,y=10; if(x>y) à false. if(x<=y) à true.
BrainStream Co., Ltd.,55

Comparison Operators
l Tests the class of an object at runtime.

Object a = vector.get(“data”); if(a instanceof String){ System.out.println( (String)a ); }

BrainStream Co., Ltd.,56

Equality Comparison Operators
l == and != test for equality and inequality.

int x=10,y=10; if(x==y) à true

l Object uses “equals” method, and use == in

case compare “null” value.

String x=“test”,y=“test”; If(x.equals(y)) à true If(x==null) à false
BrainStream Co., Ltd.,57

Bitwise Operators
l & AND l | OR l ^ eXclusive-OR (XOR)

byte x = 10; // 00001010 byte y = 15; //00001111 z = (byte)(x^y);

BrainStream Co., Ltd.,58

Boolean Operations
l & AND l | OR l ^ eXclusive-OR (XOR)

boolean x = true; boolean y = false; boolean z = x&y;

BrainStream Co., Ltd.,59

Short-Circuit Logical Operators
l && and || provide logical AND and OR

operations on boolean types. l No XOR operation is provided.
boolean x = (5>0)||(5>(5/0)); System.out.println(x); boolean x = (5>0)|(5>(5/0)); System.out.println(x);
BrainStream Co., Ltd.,60

>true 5>0 is ture (5>(5/0) is never execute ArithmeticException: / by zero

Conditional Operator
l Known as the ternary operator, because it

takes three operands. l Conditions (if/else) into a single expression. a = x ? b : c;

BrainStream Co., Ltd.,61

Conditional Operator
l Type of expression x should be boolean. l Types of expressions b and c should be

assignment-compatible with type of a. l Value assigned to a will be b if x is true or will be c if x is false. a = x ? b : c;

BrainStream Co., Ltd.,62

Assignment Operators
l Set value of a variable or expression to a new

value. l Simple assignment uses = l Compound operators such as += and *= provide compound “calculate and assign”.
int a,b,c; a = b = c = 0; int x = 2; x += 3; à x = x+3;
BrainStream Co., Ltd.,63

Flow Control
l Loop Constructs
– – – –

while do For Break and continue in loops if/else switch
BrainStream Co., Ltd.,64

l Selection Statements
– –

while ( <boolean expression> ) { statement or block; 0 }
int i = 0; while( i < 5 ) { System.out.println(i); i++; } 1 2 3 4

BrainStream Co., Ltd.,65

l Loop at least once.

do { statement or block; } while ( <boolean expr> ) ;
int i = 0; do { System.out.println(i); i += 1; } while ( i<5 );
BrainStream Co., Ltd.,66

0 1 2 3 4

for ( statement ; condition ; expression){ loop_body } l statement: set up starting conditions. l condition: must be a boolean expression. l expression: increment a loop counter.

BrainStream Co., Ltd.,67

0 l for(;;) à Loop forever. 1 2 for ( int i = 0; i < 5; i++ ) { 3 System.out.println(i); 4 } int j, k; for (j = 3, k = 6; j + k < 20; j++, k +=2) { System.out.println(“j is “ + j + “ k is “ + k); }
BrainStream Co., Ltd.,68

j is 3 k is 6 j is 4 k is 8 j is 5 k is 10 j is 6 k is 12

l Can use comma to separate several

expressions. l Con't mix expressions with variable declarations l Con't have multiple declarations of different types. int i = 7;
for (i++, int j = 0; i < 10; j++) { } for (int i = 7, long j = 0; i < 10; j++) { }
BrainStream Co., Ltd.,69

Break and continue in loops
l The break statement

Exit from switch statements, loop statements, and labeled block too early. Syntax:break <label>; Skip over and jump to the end of the loop body Syntax: continue <label>;

l The continue statement
– –

BrainStream Co., Ltd.,70

Break and continue in loops
l Continue

mainLoop: for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] == ‘\u0000’) { continue mainLoop; } } }

BrainStream Co., Ltd.,71

Break and continue in loops
l Break

for (int j = 0; j < array.length; j++) { if (array[j] == null) { break; //break out of inner loop } // process array[j] }

BrainStream Co., Ltd.,72

If (<boolean expression>) { statements or blocks; } if (<condition is true>) { statements or blocks; } else { statements or blocks; }
BrainStream Co., Ltd.,73

l Example

if (x > 5) { System.out.println(“x is more than 5”); } if (x > 5) { System.out.println(“x is more than 5”); }else { System.out.println(“x is not more than 5”); }
BrainStream Co., Ltd.,74


choice between multiple alternative

switch (<expr1>) { case <expr2>: statement(s); break; case <expr3>: statement(s); break; default: statement(s); break; } BrainStream Co., Ltd.,75

l Example
switch (x) { case 1: System.out.println(“Got a 1”); break; case 2: case 3: System.out.println(“Got 2 or 3”); break; default: System.out.println(“Not a 1, 2, or 3”); break; }
BrainStream Co., Ltd.,76

x = 1 à Got a 1 x=2 àGot 2 or 3 x=3 àGot 2 or 3 X=4à Not a 1,2, or 3

l Source Files.

package, import, class definition a letter, a dollar sign ($), or an underscore (_) byte, short, int, long, double, float, boolean, char

l Keywords and Identifiers.

l Primitive Data Types.

BrainStream Co., Ltd.,77

l Literals. l Array. l Class Fundamentals. l Argument Passing.
– –

Copy value – primitive Object reference - object

BrainStream Co., Ltd.,78

l Operators and Assignments

BrainStream Co., Ltd.,79

l Loop Constructs
– – – –

while do For Break and continue in loops if/else switch
BrainStream Co., Ltd.,80

l Selection Statements
– –

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.