02 language fundamentals. 2 fundamentals operators flow controls agenda

56
02 Language Fundamentals

Upload: diane-adams

Post on 17-Dec-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

02 Language Fundamentals

Page 2: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

2

• Fundamentals• Operators • Flow Controls

AgendaAgenda

Page 3: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

3

• Java Source File Structure• Java Keywords• Identifiers• Literals• Variables and Data Types• Variable Declaration and Initialization• Operators• Primitive Casting• Flow Controls

OutlineOutline

Page 4: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

4

At the end of this section, you should be able to:• Recognize and create correctly constructed source code• Recognize and create correctly constructed declarations• Distinguish between legal and illegal identifiers• Describe all the primitive data types and the ranges of

the integral data types• Recognize correctly formatted data types• Learn to properly declare and initialize variables• Understand the contents of the argument list of an

application’s main() method

ObjectivesObjectives

Page 5: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

5

Objectives (continued)Objectives (continued)

Operators:• Learn to use:

• Unary operators• Arithmetic operators• String operators• Relational operators• Conditional operators• Logical operators• Assignment operators

• Be familiar with object, shift and bitwise operators• Identify the order of evaluation and change its precedence• Learn how to cast primitive data types

Page 6: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

6

Objectives (continued)Objectives (continued)

Flow Controls:• Learn syntax and correct use of:

• if-else() statement• switch() statement• while() statement• do-while() statement• for() statement• break, continue and label statements

• Introduce the concept of return statement

Page 7: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

7

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

1. Package declaration

Used to organize a collection of related classes.

2. Import statement

Used to reference classes and declared in other packages.

3. Class declarationA Java source file can have several

classes but only one public class is

allowed.

1. Package declaration

Used to organize a collection of related classes.

2. Import statement

Used to reference classes and declared in other packages.

3. Class declarationA Java source file can have several

classes but only one public class is

allowed.

declaration order

Java Source File StructureJava Source File Structure

Page 8: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

8

1. Single Line Comment

// insert comments here

2. Block Comment

/*

* insert comments here

*/

3. Documentation Comment

/**

* insert documentation

*/

1. Single Line Comment

// insert comments here

2. Block Comment

/*

* insert comments here

*/

3. Documentation Comment

/**

* insert documentation

*/

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

Java Source File StructureJava Source File StructureComments

Tabs and spaces are ignored by the compiler. Used to improve readability of code.

Whitespaces

Page 9: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

9

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

•Every java program includes at least one class definition. The class is the fundamental component of all Java programs.

•A class definition contains all the variables and methods that make the program work. This is contained in the class body indicated by the opening and closing braces.

Java Source File StructureJava Source File Structure

Class

Page 10: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

10

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

Java Source File StructureJava Source File Structure

• Braces are used for grouping statements or block of codes.

• The left brace ( { ) indicates the beginning of a class body, which contains any variables and methods the class needs.

• The left brace also indicates the beginning of a method body.

• For every left brace that opens a class or method you need a corresponding right brace ( } ) to close the class or method.

• A right brace always closes its nearest left brace.

Braces

Page 11: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

11

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

Java Source File StructureJava Source File Structure

This line begins the main() method. This is the line at which the program will begin executing.

main() method

Declares a parameter named args, which is an array of String. It represents command-line arguments.

String args[]

Page 12: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

12

/* * Created on Jul 14, 2005 * * First Java Program */package com.jds.sample;import java.util.*;

/** * @author JDS */public class JavaMain {

public static void main(String[] args) {// print a messageSystem.out.println("Welcome to

Java!");}

}

class Extra {/* * class body */

}

Java Source File StructureJava Source File Structure

• A complete unit of work in a Java program.

• A statement is always terminated with a semicolon and may span multiple lines in your source code.

Java statement

Semicolon (;) is the terminating character for any java statement.

Terminating characterThis line outputs the string “Welcome to Java!” followed by a new line on the screen.

System.out.println()

Page 13: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

13

truetrue

strictfpstrictfp

nullnull

implementsimplements

extendsextends

char char

transienttransient

staticstatic

newnew

ifif

elseelse

catchcatch

throwsthrows

shortshort

nativenative

doubledouble

casecase

throwthrow

returnreturn

longlong

forfor

do do

bytebyte

whilewhile

thisthis

publicpublic

interfaceinterface

floatfloat

defaultdefault

breakbreak

volatilevolatile

synchronizedsynchronized

protectedprotected

intint

finallyfinally

continuecontinue

booleanboolean

voidvoid

switchswitch

privateprivate

instanceofinstanceof

finalfinal

assertassert

trytry

supersuper

packagepackage

importimport

falsefalse

classclass

abstractabstract

Java KeywordsJava Keywords

gotogotoconstconst

Page 14: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

14

printMe is not the same as PrintMe

Identifiers Identifiers

• An identifier is the name given by a programmer to a variable, statement label, method, class, and interface

• An identifier must begin with a letter, $ or _

• Subsequent characters must be letters, numbers, $ or _

• An identifier must not be a Java keyword

• Identifiers are case-sensitive

Incorrect Correct

3strikes strikes3

Write&Print Write_Print

switch Switch

Page 15: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

15

A literal is a representation of a value of a particular type

LiteralsLiterals

Type Examples & Values

boolean true false

character ’a’ ‘\uFFFF' ‘\777’

integer 123 123L O123 Ox123

floating-point123.5 123.5D 123.5F 123.5e+6

object “test” null

escape sequences \n \t \b \f \r \’ \” \\

Page 16: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

16

Variable and Data TypesVariable and Data Types

• A variable is a named storage location used to represent data that can be changed while the program is running

• A data type determines the values that a variable can contain and the operations that can be performed on it

• Categories of data types:

1. Primitive data types

2. Reference data types

Page 17: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

17

Primitive Data TypesPrimitive Data Types

Type Bits Lowest Value Highest Value

boolean (n/a) false true

char 16 '\u0000' [0] '\uffff' [216-1]

byte 8 -128 [-27] +127 [27-1]

short 16 -32,768 [-215] +32,767 [215-1]

int 32 -2,147,483,648 [-231] +2,147,483,647 [231-1]

long 64 -9,223,372,036,854,775,808 [-263] +9,223,372,036,854,775,807 [263-1]

float 32 ±1.40129846432481707e-45 ±3.40282346638528860e+38

double 64 ±4.94065645841246544e-324 ±1.79769313486231570e+308

• Primitive data types represent atomic values and are built-in to Java

• Java has 8 primitive data types

Page 18: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

18

Reference Data TypesReference Data Types

• Reference data types represent objects

• A reference serves as a handle to the object, it is a way to get to the object

• Java has 2 reference data types

1. Class

2. Interface

Page 19: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

19

• Declaring a variable with primitive data type

int age = 21;

• Declaring a variable with reference data type

Date now = new Date(); String name = “Jason”;

Variable Declaration & InitializationVariable Declaration & Initialization

identifier name

primitive type

initial value

identifier name

reference type

initial value

Page 20: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

20

Primitive Type DeclarationPrimitive Type Declaration

Identifier name

type

int age;

stack

age = 17;

valueIdentifier name

age

MEMORYdeclaration

initialization/assignment

allot space to memory

017

Page 21: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

21

The heap

Car object

Values

Reference Type DeclarationReference Type Declaration

type

Car myCar;

myCar = new Car(“Bumble Bee”);

Identifier name

Bumble Bee

memory address

location

allot space to memory

reference

myCar

Identifier name

Page 22: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

22

Member Variables Declared inside the class but outside of all methods. Accessible by all methods of the class.

Local Variables Available only within the method where they were declared. Method parameters have local scope.

Scope of VariableScope of Variable

public class HelloWorld { //accessible throughout the classString name;

public void otherMethod(){ float salary = 15000.00f; //can’t access age variable from here}

public static void main(String args[ ]) { //can’t access salary variable from here

int age=17;//can’t access ctr variable from

herefor (int ctr=0 ; ctr<5 ; ctr++) { //age variable accessible here

}

}}

Page 23: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

23

• Fundamentals• Operators • Flow Controls

AgendaAgenda

Page 24: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

24

• Unary operators• Arithmetic operators• String operator• Relational operators• Conditional operator• Logical operator• Assignment operators• Object operators• Shift operators• Bitwise operators• Evaluation order• Primitive Casting

Operators and AssignmentsOperators and Assignments

Page 25: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

25

Unary OperatorsUnary Operators• Unary operators use only one

operand++ Increment by 1, can be prefix or postfix

-- Decrement by 1, can be prefix or postfix

+ Positive sign

- Negative sign

int num=10;

System.out.println("incrementing/decrementing...");

System.out.println(++num);

System.out.println(--num);

System.out.println(num++);

System.out.println(num--);

System.out.println("setting signs...");

System.out.println(+num);

System.out.println(-num);

incrementing/decrementing...

11

10

10

11

setting signs...

10

-10

Sample code: Sample output:

Page 26: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

26

Arithmetic OperatorsArithmetic Operators• Arithmetic operators are used for basic

mathematical operations+ Add

- Subtract

* Multiply

/ Divide

% Modulo, remainder

int num1=15, num2=10;

System.out.println("calculating...");

System.out.println(num1 + num2);

System.out.println(num1 - num2);

System.out.println(num1 * num2);

System.out.println(num1 / num2);

System.out.println(num1 % num2);

calculating...

25

5

150

1

5

Sample code: Sample output:

Page 27: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

27

String OperatorString Operator

• String operator (+) is used to concatenate operands• If one operand is String, the other operands are converted to String

String fname = "Josephine", lname = "Santos", mi = "T";

String fullName = lname + ", " + fname + " " + mi + ".";

String nickName = "Jessy";

int age=21;

System.out.println("My full name is: " + fullName);

System.out.println("You can call me " + nickName + "!");

System.out.println("I'm " + age + " years old.");

My full name is: Santos, Josephine T.

You can call me Jessy!

I'm 21 years old.

Sample code:

Sample output:

Page 28: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

28

Relational OperatorsRelational Operators

• Relational operators are used to compare values• boolean values cannot be compared with non-boolean values• Only object references are checked for equality, and not their states• Objects cannot be compared with null• null is not the same as “”

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equals

!= Not equals

Page 29: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

29

Relational OperatorsRelational Operators

String name1 = "Marlon"; int weight1=140, height1=74;

String name2 = "Katie"; int weight2=124, height2=78;

boolean isLight = weight1 < weight2, isLightEq = weight1 <= weight2;

System.out.println("Is " + name1 + " lighter than " + name2 + "? " + isLight);

System.out.println("Is " + name1 + " lighter or same weight as " + name2 + "? " + isLightEq);

boolean isTall = height1 > height2, isTallEq = height1 >= height2;

System.out.println("Is " + name1 + " taller than " + name2 + "? " + isTall);

System.out.println("Is " + name1 + " taller or same height as " + name2 + "? " + isTallEq);

boolean isWeighEq = weight1 == weight2, isTallNotEq = height1 != height2;

System.out.println("Is " + name1 + " same weight as " + name2 + "? " + isWeighEq);

System.out.println("Is " + name1 + " not as tall as " + name2 + "? " + isTallNotEq);

System.out.println("So who is heavier?");

System.out.println("And who is taller?");

Is Marlon lighter than Katie? false

Is Marlon lighter or same weight as Katie? false

Is Marlon taller than Katie? false

Is Marlon taller or same height as Katie? false

Is Marlon same weight as Katie? false

Is Marlon not as tall as Katie? true

So who is heavier?

And who is taller?

Sample code:

Sample output:

Page 30: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

30

• The ternary operator (?:) provides a handy way to code simple if-else() statements in a single expression, it is also known as the conditional operator

• If condition is true, then exp1 is returned as the result of operation• If condition is false, then exp2 is returned as the result of operation

• Can be nested to accommodate chain of conditions

Conditional operatorConditional operator

condition ? exp1 : exp2;

int yyyy=1981, mm=10, dd=22;

String mmm = mm==1?"Jan":mm==2?"Feb":mm==3?"Mar":mm==4?"Apr":mm==5?"May":mm==6?"Jun":

mm==7?"Jul":mm==8?"Aug":mm==9?"Sep":mm==10?"Oct":mm==11?"Nov":mm==12?"Dec":"Unknown";

System.out.println("I was born on " + mmm + " " + dd + ", " + yyyy);

I was born on Oct 22, 1981

Sample code:

Sample output:

Syntax:

Page 31: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

31

Logical OperatorsLogical Operators• Logical operators are used to compare

boolean expressions• ! inverts a boolean value• & | evaluate both operands• && || evaluate operands conditionally

! NOT

& AND

| OR

^ XOR

&& Short-circuit AND

|| Short-circuit OR

Op1 Op2 !Op1 Op1 & Op2 Op1 | Op2 Op1 ^ Op2 Op1 && Op2 Op1 || Op2

false false true false false false false false

false true true false true true false true

true false false false true true false true

true true false true true false true true

Truth Table

Page 32: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

32

• Similar to the Boolean operators, but with an added ability to “short-circuit” part of the process, using a couple of mathematical rules:• If the left operand of an && operation is false, the result is

automatically false, and the right operand is not evaluated

• If the left operand of an || operation is true, the result is automatically true, and the right operand is not evaluated

• Boolean Complement ( ! ):• The NOT function inverts the value of boolean

Short-circuit Logical Operators (&&,|| and !)Short-circuit Logical Operators (&&,|| and !)

boolean a = (5>8) && (8>5);false;

boolean b = (8>5) || (5>8);true;

boolean c = !b;false;

Page 33: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

33

Logical OperatorsLogical Operators

int yrsService=8;

double perfRate=86;

double salary=23000;

char position='S';

// P-probationary R-regular, S-supervisor, M-manager, E-executive, T-top executive

boolean forRegular, forSupervisor, forManager, forExecutive, forTopExecutive;

forRegular = yrsService>1 & perfRate>80 & position=='P' & salary<10000;

forSupervisor = yrsService>5 & perfRate>85 & position=='R' & salary<15000;

forManager = yrsService>7 & perfRate>85 & position=='S' & salary<25000;

forExecutive = yrsService>10 & perfRate>80 & position=='M' & salary<50000;

forTopExecutive = yrsService>10 & perfRate>80 & position=='E' & salary<75000;

boolean isPromoted = forRegular||forSupervisor||forManager||forExecutive||forTopExecutive;

boolean isLuckyGuy = forExecutive ^ forTopExecutive;

System.out.println("Are you a candidate for promotion? " + isPromoted);

System.out.println("Will you be promoted as a regular employee? " + forRegular);

System.out.println("Will you be promoted as a supervisor? " + forSupervisor);

System.out.println("Will you be promoted as a manager? " + forManager);

System.out.println("Will you be paid more and work less? " + isLuckyGuy);

System.out.println("I hope you won't be demoted, are you? " + !isPromoted);

Sample code: Sample output:Are you a candidate for promotion? true

Will you be promoted as a regular employee? false

Will you be promoted as a supervisor? false

Will you be promoted as a manager? true

Will you be paid more and work less? false

I hope you won't be demoted, are you? false

Page 34: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

34

Assignment OperatorsAssignment Operators

• Assignment operators are used to set the value of a variable

= Assign

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulo and assign

&= AND and assign

|= OR and assign

^= XOR and assign

double unitPrice=120, qty=2, salesAmount;

double discRate=15, discAmount, vatRate=10, vatAmount;

// compute gross sales

salesAmount = unitPrice * qty;

System.out.println("Gross Sales: " + salesAmount);

// compute tax

vatRate /= 100;

vatAmount = salesAmount * vatRate;

salesAmount += vatAmount;

System.out.println("Tax: " + vatAmount);

// compute discount

discRate /= 100;

discAmount = salesAmount * discRate;

salesAmount -= discAmount;

System.out.println("Discount: " + discAmount);

System.out.println("Please pay: " + salesAmount);

Gross Sales: 240.0

Tax: 24.0

Discount: 39.6

Please pay: 224.4

Sample code:

Sample output:

Page 35: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

35

CastingCasting• Casting is converting from one data type to another

• Implicit casting is an implied casting operations• Explicit casting is a required casting operations• Primitive casting is converting a primitive data type to another

• Widening conversion is casting a narrower data type to a broader data type

• Narrowing conversion is casting a broader data type to a narrower data type

• Reference casting is converting a reference data type to another• Upcasting is conversion up the inheritance hierarchy

• Downcasting is conversion down the inheritance hierarchy

• Casting between primitive and reference type is not allowed• In Java, casting is implemented using () operator

Page 36: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

36

Primitive Casting FlowPrimitive Casting Flow

byte short int long float double

char

widening conversion

narrowing conversion

Page 37: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

37

Primitive Casting RulePrimitive Casting Rule

Operation Conversion Type

arithmetic implicit widening conversion

relational implicit widening conversion

shift implicit widening conversion

bitwise implicit widening conversion

assignment implicit widening conversion (if target is broader )

parameter passing implicit widening conversion (if formal parameter is broader)

logical none

ternary ?: none

boolean none

(all others) explicit casting (narrowing or widening conversion)

Page 38: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

38

Implementing Primitive CastingImplementing Primitive Casting

public static void main(String args[]) {short age = 20;char sex = ‘M’;byte iq = 80;int height = 64;long distance = 300;float price = 99.99f;double money = 500.00;

age = sex; // will this compile?sex = iq; // will this compile?iq = (byte) height; // will this compile?distance = height; // will this compile?price = money; // will this compile?sex = (char) money; // will this compile?

}

Page 39: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

39

Evaluation order of operators in Java is as follows:• Unary (++ -- + - ~ ())• Arithmetic (* / % + -)• Shift (<< >> >>>)• Comparison (< <= > >= instanceof == !=)• Bitwise (& ^ |)• Short-circuit (&& || !)• Conditional (?:)• Assignment (= += -= *= /=)

Summary of OperatorsSummary of Operators

Page 40: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

40

• Fundamentals• Operators • Flow Controls

AgendaAgenda

Page 41: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

41

Flow ControlsFlow Controls

• if-else() statement• switch() statement• while() statement• do-while() statement• for() statement• break statement• continue statement• Statement label

Page 42: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

42

Types of Flow ControlTypes of Flow Control

1. Sequential • Perform statements in the order

they are written

2. Selection• Perform statements based on

condition

3. Iteration• Perform statements repeatedly

based on condition

Page 43: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

43

if-else()if-else()• if-else() performs statements based on two conditions• Condition should result to a boolean expression• If condition is true, the statements following if are executed• If condition is false, the statements following else are executed• Can be nested to allow more conditions

if (condition) { // braces optional

// statement required

}

else { // else clause is optional

// statement required

}

int age=10;

if (age < 10) {

System.out.println("You're just a kid.");

} else if (age < 20){

System.out.println("You're a teenager.");

} else {

System.out.println("You're probably old...");

}

Syntax:

Example:

You're a teenager.Output:

Page 44: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

44

switch()switch()• switch() performs statements based on multiple conditions• exp can only be char byte short int, val should be a unique constant of exp• case statements falls through the next case unless a break is encountered• default is executed if none of the other cases match the exp

switch (exp) {

case val:

// statements here

case val:

// statements here

default:

// statements here

}

char sex='M';

switch (sex){

case 'M':

System.out.println("I'm a male."); break;

case 'F':

System.out.println("I'm a female."); break;

default:

System.out.println("I am what I am!");

}

Syntax:

Example:

I'm a male.Output:

Page 45: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

45

while()while()• while() performs statements repeatedly while condition remains true

while (condition) { // braces optional

// statements here

}

int ctr=10;

while (ctr > 0) {

System.out.println("Timer: " + ctr--);

}

Syntax:

Example:

Timer: 10

Timer: 9

Timer: 8

Timer: 7

Timer: 6

Timer: 5

Timer: 4

Timer: 3

Timer: 2

Timer: 1

Output:

Page 46: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

46

do-while()do-while()• do-while() performs statements repeatedly (at least once) while condition

remains true

do

// statements here

while (condition);

int ctr=0;

do

System.out.println("Timer: " + ctr++);

while (ctr < 10);

// next statement

Syntax:

Example:

Timer: 0

Timer: 1

Timer: 2

Timer: 3

Timer: 4

Timer: 5

Timer: 6

Timer: 7

Timer: 8

Timer: 9

Output:

Page 47: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

47

for()for()• for() performs statements repeatedly based on a condition• Init is a list of either declarations or expressions, evaluated first and only once• Condition is evaluated before each iteration• Exp is a list of expressions, evaluated after each iteration• All entries inside () are optional, for(;;) is an infinite loop

for (init; condition; exp) { // braces optional

// statements here

}

for (int age=18; age<30; age++) {

System.out.println("Enjoy life while you're " + age);

}

Syntax:

Example:

Enjoy life while you're 18

Enjoy life while you're 19

Enjoy life while you're 20

Enjoy life while you're 21

Enjoy life while you're 22

Enjoy life while you're 23

Enjoy life while you're 24

Enjoy life while you're 25

Enjoy life while you're 26

Enjoy life while you're 27

Enjoy life while you're 28

Enjoy life while you're 29

Output:

Page 48: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

48

breakbreak• break exits loops and switch() statements

break;

boolean isEating=true;

int moreFood=5;

while (isEating) {

if (moreFood<1) break;

System.out.println("Uhm, yum, yum...");

moreFood--;

}

System.out.println("Burp!");

Syntax:

Example:

Uhm, yum, yum...

Uhm, yum, yum...

Uhm, yum, yum...

Uhm, yum, yum...

Uhm, yum, yum...

Burp!

Output:

Page 49: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

49

continuecontinue• continue is used inside loops to start a new iteration

continue;

for (int time=7; time<12; time++) {

if (time<10) {

System.out.println("Don't disturb! I'm studying...");

continue;

}

System.out.println("zzzZZZ...");

}

Syntax:

Example:

Don't disturb! I'm studying...

Don't disturb! I'm studying...

Don't disturb! I'm studying...

zzzZZZ...

zzzZZZ...

Output:

Page 50: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

50

Statement LabelStatement Label• A label is an identifier placed before a statement, it ends with :• break labelName is used to exit any labelled statement• continue labelName is used inside loops to start a new iteration of the labeled loop

labelName:

break labelName;

continue labelName;

int[] scores = {3,9,10,0,8,10,7,1,9,8};

outer:

for (int i=0; i<10; i++) {

if (scores[i] <=0) break outer;

if (scores[i] > 5) {

inner:

for (int j=0; j<3; j++) {

if (scores[i] == 10){

System.out.println ("Perfect score! More claps!!!");

continue inner;

}

System.out.println ("Nice score! One clap!");

continue outer;

}

}

if (scores[i] <= 5) System.out.println("More practice...");

}

Syntax:

Example:

More practice...

Nice score! One clap!

Perfect score! More claps!!!

Perfect score! More claps!!!

Perfect score! More claps!!!

Output:

Page 51: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

51

Example 1:public int sum(int x, int y) { return x + y;}Example 2:public int sum(int x, int y) { x = x + y; if (x < 100){

return x; }else{

return x + 5; }}Example 2:public void getSum(int x) { System.out.println(x);return;

}

• return branching statement is used to exit from the current method.

• Two forms:• return <value>;• return;

returnreturn

Page 52: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

52

Key PointsKey Points

• A Java source file can include package, import and class declarations in that order

• The main() method is the start of execution of a Java application

• Each Java statement is terminated by a semicolon “;”• Identifiers are case-sensitive• Java keywords cannot be used as identifiers• Each variable must be declared with a data type• There are 8 primitive data types: boolean, char, byte, short, int, long, float and double

• There are 3 reference data types: class, array and interface

Page 53: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

53

Key Points (continued)Key Points (continued)

• Use unary, arithmetic operators for basic mathematical operations

• Use string operator to concatenate strings• Use relational operators to compare objects• Use conditional operator as alternative to if-else()

statement• Use logical operators to compare boolean values• Use assignment operators to assign values to variables• Get familiar with object, shift and bitwise operators• Java evaluates operators in order of precedence• Casting is converting one data type to another

Page 54: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

54

Key PointsKey Points

• if() and switch() are used for branching statements

• while(), do-while() and for() are used for iterating statements

• break, continue and label are used to branch inside loops

Page 55: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

55

• http://www.java.sun.com• http://www.java.com• http://www.java.net • http://javaboutique.internet.com• http://javaboutique.webdeveloper.com• http://www.javaworld.com• http://www.developer.com• http://javalobby.org• http://freewarejava.com• http://onjava.com• http://javaranch.com• http://www.cafeaulait.org• http://www.java.about.com• http://www.javacoffeebreak.com

Java Online ResourcesJava Online Resources

Page 56: 02 Language Fundamentals. 2 Fundamentals Operators Flow Controls Agenda

56

Tutorials:• http://java.sun.com/docs/books/tutorial • http://www.ibiblio.org/javafaq/javatutorial.html• http://www.javacoffeebreak.com/tutorials/index.html• http://www.cafeaulait.org/course/• http://oopweb.com/Java/Documents/

IntroToProgrammingUsingJava/VolumeFrames.html

FAQs:• http://java.sun.com/products/jdk/faq.html• http://www.ibiblio.org/javafaq/javafaq.html• http://www.apl.jhu.edu/~hall/java/Beginners-Corner.html• http://www.norvig.com/java-iaq.html• http://www.jguru.com/faq/subtopics.jsp?topic=JavaLanguage• http://www.javacoffeebreak.com/faq/

Java Online Resources Java Online Resources