Introduction to Java Language 2 - cpe.ku.ac.thplw/oop/presentation/color/oojp_week_2-3... · 23...

81
23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 1 Introduction to Introduction to Java Java Language Language 2 2 ปรีดา เลิศพงศวิภูษณะ [email protected] ภาควิชาวิศวกรรมคอมพิวเตอร คณะวิศวกรรมศาสตร มหาวิทยาลัยเกษตรศาสตร

Transcript of Introduction to Java Language 2 - cpe.ku.ac.thplw/oop/presentation/color/oojp_week_2-3... · 23...

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 1

Introduction to Introduction to JavaJava LanguageLanguage 22

ปรีดา เลิศพงศวิภูษณะ[email protected]

ภาควิชาวิศวกรรมคอมพิวเตอรคณะวิศวกรรมศาสตร มหาวิทยาลัยเกษตรศาสตร

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 2

Primitive Data Types in Java• Java's primitive data types are very similar to those of C.• The boolean type has been added.• Where C and C++ leave a number of issues to be machine and compiler

dependent (for instance the size of an int) Java specifies everything.– Java prevents casting between arbitrary variables. Only casts between numeric

variables and between sub and superclasses of the same object are allowed.– All numeric variables in Java are signed.– sizeof isn't necessary in Java because all sizes are precisely defined. For instance,

an int is always 4 bytes.

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 3

Primitive Data TypesPrimitive Data Typesboolean : 1-bit. May take on the values true and false only.byte : 1 byte -128 to 127.char : 2 bytes, unsigned, Unicode, 0 to 65,535short : 2 bytes -32,768 to 32,767.int : 4 bytes -2,147,483,648 to 2,147,483,647.long : 8 bytes -9,223,372,036,854,775,808 to

+9,223,372,036,854,775,807.float : 4 bytes (IEEE 754) 1.40129846432481707e-45 to

(+-)3.40282346638528860e+38.double : 8 bytes (IEEE 754) 4.94065645841246544e-324d to

(+-)1.79769313486231570e+308d

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 4

Literal Data TypesLiteral Data TypesString : ”...”, sTemp = ”Test”;

boolean : true, false

char : ’...’, cTemp = ’T’;

int : l, 5, +55, -32

long : lL, 5L, +55L, -32L

float : 2E4F, 2.5E78F, -4.1E-2F, -7.45E16F

double : 2E4, 2.5E78, -4.1E-2, -7.45E16

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 5

Data Type ConversionsData Type Conversionschar : Integer, String

int : String

long : String

float : String

double : String

String : BLOB, Date, DateTime, Numeric, Time

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 6

Java OperatorsOperator : Purpose+ : addition of numbers, concatenation of Strings+= : add and assign numbers, concatenate and assign Strings- : subtraction-= : subtract and assign* : multiplication*= : multiply and assign/ : division/= : divide and assign| : bitwise OR|= : bitwise OR and assign^ : bitwise XOR^= : bitwise XOR and assign& : bitwise AND&= : bitwise AND and assign% : take remainder%= : take remainder and assign> : greater than>= : greater than or equal to< : less than<= : less than or equal to

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 7

Java Operators 2! : boolean NOT!= : not equal to++ : increment by one-- : decrement by one>> : shift bits right with sign extension>>= : shift bits right with sign extension and assign<< : shift bits left<<= : shift bits left and assign>>> : unsigned bit shift right>>>= : unsigned bit shift right and assign&& : boolean AND|| : boolean OR== : boolean equals= : assignment~ : bitwise NOT?: : conditional

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 8

White Space• Inside String and character literals the only white space permitted is the

space character. Carriage returns, tabs, line feeds and form feeds must be inserted with special escape sequences like \r, \t, \f, and \n.

String poem = "Mary had a little lambwhose fleece was white as snowand everywhere that Mary wentthe lamb was sure to go.";

String poem = "Mary had a little lamb\n" +"whose fleece was white as snow\n" +"and everywhere that Mary went\n" +"the lamb was sure to go.";

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 9

Identifiers in Java• The following are legal variable names:MyVariablemyvariableMYVARIABLEximyvariable$myvariable9pinsandros&alpha;&nu;&delta;&rho;&omicron;&sigmaf;OReillyThis_is_an_insanely_long_variable_name_that_just_keeps_going_and_going_and_going_

and_well_you_get_the_idea_The_line_breaks_arent_really_part_of_the_variable_name_Its_just_that_this_variable_name_is_so_ridiculously_long_that_it_won't_fit_on_the_page_I_cant_imagine_why_you_would_need_such_a_long_variable_name_but_if_you_do_you_can_have_it

• The following are not legal variable names.My Variable // Contains a space 9pins // Begins with a digita+c // The plus sign is not an alphanumeric charactertesting1-2-3 // The hyphen is not an alphanumeric characterO'Reilly // Apostrophe is not an alphanumeric characterOReilly_&_Associates // ampersand is not an alphanumeric character

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 10

KeywordsKeyword Purposeabstract declares that a class or method is abstractboolean declares a boolean variable or return typebreak prematurely exits a loopbyte declares a byte variable or return typecase one case in a switch statementcatch handle an exceptionchar declares a character variable or return typeclass signals the beginning of a class definitioncontinue prematurely return to the beginning of a loopdefault default action for a switch statementdo begins a do while loopdouble declares a double variable or return typeelse signals the code to be executed if an if statement is

not trueextends specifies the class which this class is a subclass offinal declares that a class may not be subclassed or that a

field or method may not be overriddenfinally declares a block of code guaranteed to be executedfloat declares a floating point variable or return typefor begins a for loopif execute statements if the condition is trueimplements declares that this class implements the given interfaceimport permit access to a class or group of classes in a package

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 11

Keywords 2Keyword Purposereturn returns a value from a methodshort declares a short integer variable or return typestatic declares that a field or a method belongs to a class

rather than an objectsuper a reference to the parent of the current objectswitch tests for the truth of various possible casessynchronized Indicates that a section of code is not thread-safethis a reference to the current objectthrow throw an exceptionthrows declares the exceptions thrown by a methodtransient This field should not be serializedtry attempt an operation that may throw an exceptionvoid declare that a method does not return a valuevolatile Warns the compiler that a variable changes

asynchronouslyinstanceof tests whether an object is an instanceof a classint declares an integer variable or return typeinterface signals the beginning of an interface definitionlong declares a long integer variable or return typenative declares that a method is implemented in native codenew allocates a new objectpackage defines the package in which this source code file

belongs

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 12

Keywords 3Keyword Purposeprivate declares a method or member variable to be privateprotected declares a class, method or member variable to be

protectedpublic declares a class, method or member variable to be

publicwhile begins a while loopreturn returns a value from a methodshort declares a short integer variable or return typestatic declares that a field or a method belongs to a class

rather than an objectsuper a reference to the parent of the current objectswitch tests for the truth of various possible casessynchronized Indicates that a section of code is not thread-safethis a reference to the current objectthrow throw an exceptionthrows declares the exceptions thrown by a methodtransient This field should not be serializedtry attempt an operation that may throw an exceptionvoid declare that a method does not return a valuevolatile Warns the compiler that a variable changes

asynchronouslywhile begins a while loop

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 13

Separators in JavaSeparator Purpose( ) Encloses arguments in method definitions and

calling; adjusts precedence in arithmetic expressions; surrounds cast types anddelimits test expressions in flow control statements

{ } defines blocks of code and automatically initializes arrays

[ ] declares array types and dereferences array values

; terminates statements, separates successive identifiers in variable

declarations; chains statements in the test,expression of a for loop

. Selects a field or method from an object;separates package names from sub-package and class names

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 14

Addition of Integers in Javaclass AddInts {

public static void main (String args[]) {int i = 1;int j = 2;int k;System.out.println("i is " + i);System.out.println("j is " + j);k = i + j;System.out.println("i + j is " + k);k = i - j;System.out.println("i - j is " + k);

}}C:> javac AddInts.javaC:> java AddIntsi is 1j is 2i + j is 3i - j is -1

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 15

Addition of doubles in Javaclass AddDoubles {

public static void main (String args[]) {double x = 7.5;double y = 5.4;double z;System.out.println("x is " + x);System.out.println("y is " + y);z = x + y;System.out.println("x + y is " + z);z = x - y;System.out.println("x - y is " + z);

}}

C:> javac AddDoubles.javaC:> java AddDoublesx is 7.5y is 5.4x + y is 12.9x - y is 2.0999999999999996

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 16

Multiplication and division in Javaclass MultiplyDivide {

public static void main (String args[]) {int i = 10;int j = 2;int k;System.out.println("i is " + i);System.out.println("j is " + j);k = i / j;System.out.println("i/j is " + k);k = i * j;System.out.println("i * j is " + k);

}}

C:> javac MultiplyDivide.javaC:> java MultiplyDividei is 10j is 2i/j is 5i * j is 20

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 17

Unexpected Quotients2/3 = 03/2 = 11/0 = ArithmeticException0/0 = ArithmeticException1.0/0.0 = Inf1.0/0 = Inf0.0/0.0 = NaN-1.0/0.0 = -InfInf + 1 = InfInf + Inf = InfInf - Inf = NaNInf/Inf = NaN

NaN + anything = NaNNaN - anything = NaNNaN * anything = NaNNaN - anything = NaNNaN < NaN is falseNaN > NaN is falseNaN <= NaN is falseNaN >= NaN is falseNaN == NaN is falseNaN != NaN is true

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 18

The Remainder or Modulus Operator in Javaclass Remainder {

public static void main (String args[]) {int i = 10;int j = 3;int k;System.out.println("i is " + i);System.out.println("j is " + j);k = i%j;System.out.println("i%j is " + k);

}}

C:> javac Remainder.javaC:> java Remainderi is 10j is 3i%j is 1

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 19

Operator Precedence in Javaint m = 1 + 2 + 3 + 4 + 5;int m = 1 + 2 / 3 * 4 - 5;

class mc2 {public static void main (String args[]) {

double mass = 9.1096E-25;double c = 2.998E8;double E = mass * c * c;System.out.println(E);

}}

1. *, /, % Do all multiplications, divisions and remainders from left to right.2. +, - Do additions and subtractions from left to right.3. = Assign the right-hand side to the left-hand side

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 20

Parentheses in Javaclass FahrToCelsius {

public static void main (String args[]) {double fahr, celsius;double lower, upper, step;// lower limit of temperature tablelower = 0.0;// upper limit of temperature tableupper = 300.0;// step sizestep = 20.0;fahr = lower;while (fahr <= upper) {

celsius = (5.0 / 9.0) * (fahr-32.0);System.out.println(fahr + " " + celsius);fahr = fahr + step;

}}

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 21

Parentheses in Java 2As usual here's the output:

C:> javac FahrToCelsius.javaC:> java FahrToCelsius0 -17.777820 -6.6666740 4.4444460 15.555680 26.6667100 37.7778120 48.8889140 60160 71.1111180 82.2222200 93.3333220 104.444240 115.556260 126.667280 137.778300 148.889C:>

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 22

Mixing Data Typesclass IntAndDouble {

public static void main (String args[]) {int i = 10;double x = 2.5;double k;System.out.println("i is " + i);System.out.println("x is " + x);k = i + x;System.out.println("i + x is " + k);k = i * x;System.out.println("i * x is " + k);k = i - x;System.out.println("i - x is " + k);k = x - i;System.out.println("x - i is " + k);k = i / x;System.out.println("i / x is " + k);k = x / i;System.out.println("x / i is " + k);

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 23

Mixing Data Types• This program produces the following output:C:> java IntAndDoublei is 10x is 2.5i + x is 12.5i * x is 25i - x is 7.5x - i is -7.5i / x is 4x / i is 0.25C:>

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 24

• Order can make a difference when data types are mixed. For example,1 / 2 * 3.5 = 0.03.5 * 1 / 2 = 1.753.5 / 2 = 1.75

• You cannot assume that the usual mathematical laws of commutativity apply when mixing data types, especially integer and floating point types.

1.0 / 2 * 3.5 = 1.753.5 * 1.0 / 2 = 1.751 / 2.0 * 3.5 = 1.753.5 * 1.0 / 2.0 = 1.75

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 25

Arithmetic Promotion, Assignments, and Castingint i = (int) (9.0/4.0);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 26

Converting Strings to Numbers• convert the String "22" into the int 22 you would writeint i = Integer.valueOf("22").intValue();• To convert a String like "22" into the long value 22 you would writelong l = Long.valueOf("22").longValue();• To convert "22.5" into a float or a double you would write:double x = Double.valueOf("22.5").doubleValue();float y = Float.valueOf("22.5").floatValue();

class mc2 {public static void main (String args[]) {

double mass;double c = 2.998E8; // meters/seconddouble E;mass = Double.valueOf(args[0]).doubleValue();E = mass * c * c;System.out.println(E + " Joules");

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 27

The char data type in Java\b backspace\t tab\n linefeed\f formfeed\r carriage return\" double quote, "\' single quote, '\\ backslash, \

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 28

Unicode\u00AE © The copyright symbol\u0022 “ The double quote\u00BD ½ The fraction 1/2\u0394 ∆ The capital Greek letter delta\u00F8 ø A little o with a slash through it

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 29

Java Flow ControlJava Flow Control• if • else• else if• while• for• do while• switch case• break• continue

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 30

The if statement in Javaclass Hello {

public static void main (String args[]) {if (args.length > 0) {

System.out.println("Hello " + args[0]);}

}} IF

งานที่ตองการทํา

จริง

เท็จ

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 31

Testing for Equality• ‘=’ ‘= =’• However there is one way you can still get into trouble:

boolean b = true;if (b = false) {

System.out.println("b is false");}

• To avoid this, some programmers get in the habit of writing condition tests like this:boolean b = true;if (false = b) {

System.out.println("b is false");}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 32

The else statement in Javaclass Hello {

public static void main (String args[]) {if (args.length > 0) {

System.out.println("Hello " + args[0]);}else {

System.out.println("Hello whoever you are.");

}}

}IF

จริง เท็จ

งานที ่2งานที ่1

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 33

Else If

IF

จริง เท็จ

ELSE IF

เท็จ

งานที ่2ELSE IF

เท็จ

งานที ่3

จริง

จริง

งานที ่1

งานที ่4

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 34

Else Ifclass Hello {

public static void main (String args[]) {if (args.length == 0) {

System.out.println("Hello whoever you are");}else if (args.length == 1) {

System.out.println("Hello "+args[0]);}else if (args.length == 2) {

System.out.println("Hello "+args[0]+" "+args[1]);}else if (args.length == 3) {

System.out.println("Hello "+args[0]+" "+args[1]+" "+args[2]);}else if (args.length == 4) {

System.out.println("Hello "+args[0]+" "+args[1]+" “+args[2]+" "+args[3]);

}else {

System.out.println("Hello "+args[0]+" "+args[1]+" “+args[2]+" "+args[3]+" and all the rest!");

}}

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 35

Formatting OutputFormatting OutputNumberFormat.getNumberInstance()NumberFormat.getCurrencyInstance()NumberFormat.getPercentInstance()

double x = 10000.0 / 3.0NumberFormat nf = NumberFormat.getNumberInstance();String fx = nf.format(x);System.out.println(fx);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 36

Formatting Output 2Formatting Output 2DecimalFormat df = new DecimalFormat(“0.######”);System.out.println(df.format(x));

double x = 10000.0 / 3.0DecimalFormat df = new DecimalFormat(“0.######”);System.out.println(df.format(x));

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 37

Format SymbolFormat Symbol• 0 A digit• # A digit; don’t show if it is a leading or trailing zero• . Location of decimal separator• , Location of grouping separator• ; Separates formats for positive and negative numbers• - Negative prefix• % Divide by 100 and show as percentage• Any other symbol Include symbol in output string

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 38

Format ClassFormat ClassFormat.print(System.out, “With rate %6.3f”, 100);

f Floating-point Numberd, i Integer in decimalx Integer in hexadecimalo Integer in octals Stringc Character

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 39

The while loop in Javaclass Hello {

public static void main (String args[]) {int i;System.out.print("Hello "); // Say Helloi = 0; // Initialize loop counterwhile (i < args.length) { // Test and Loop

System.out.print(args[i]);System.out.print(" ");i = i + 1; // Increment Loop Counter

}System.out.println(); // Finish the line

}}

WHILEเท็จ

งานท่ีตองการทํา

จริง

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 40

The for loop in Javaclass Hello {

public static void main (String args[]) {System.out.print("Hello "); // Say Hellofor (int i = 0; i < args.length; i = i + 1) {

// Test and LoopSystem.out.print(args[i]);System.out.print(" ");

}System.out.println(); // Finish the line

}}

i<=N2

i=N1

เท็จ

งานท่ีตองการทํา

i=i+N3

จริง

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 41

Multiple Initializers and Incrementersfor (int i = 1, j = 100; i < 100; i = i+1, j = j-1) {

System.out.println(i + j);}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 42

The do while loop in Javaclass Hello {

public static void main (String args[]) {int i = -1;do {

if (i == -1)System.out.print("Hello ");

else {System.out.print(args[i]);System.out.print(" ");

}i = i + 1;

} while (i < args.length);System.out.println(); // Finish the line

}}

WHILE

เท็จ

งานท่ีตองการทํา

จริง

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 43

Create LoopCreate Loop

c = 1;while (c <= 10) {//// คําสั่งอื่นๆ ที่ตองการใหทํางาน// c = c + 1;

}

C <= 10

C = 1

งานที่ตองการทาํ

C = C + 1Statement ที ่3

Statement ที ่2

Statement ที ่1ตรวจสอบเงื่อนไข

กําหนดคาเริ่มตนใหกับตัวนับ

เพิ่มคาใหกับตัวนับ

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 44

Booleansboolean test1 = true;boolean test2 = false;

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 45

Relational Operators• Java has six relational operators that compare two numbers and return a

boolean value. The relational operators are <, >, <=, >=, ==, and !=.x < y Less than

True if x is less than y, otherwise false.x > y Greater than

True if x is greater than y, otherwise false.x <= y Less than or equal to

True if x is less than or equal to y, otherwise false.x >= y Greater than or equal to

True if x is greater than or equal to y, otherwise false.x == y Equal

True if x equals y, otherwise false.x != y Not Equal

True if x is not equal to y, otherwise false.

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 46

Relational Operator Precedence*, /, % Do all multiplications, divisions and remainders from left to

right.+, - Next do additions and subtractions from left to right.<, >, >=, <= Then any comparisons for relative size.==, != Then do any comparisons for equality and inequality= Finally assign the right-hand side to the left-hand side

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 47

For exampleboolean b1 = 7 > 3 == true;boolean b2 = true == 7 > 3;b = 7 > 3;

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 48

Testing Objects for Equalityclass JackAndJill {

public static void main(String args[]) {String s1 = new String("Jack went up the hill.");String s2 = new String("Jack went up the hill.");if ( s1 == s2 ) {

System.out.println("The strings are the same.");}else if ( s1 != s2 ) {

System.out.println("The strings are not the same.");}

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 49

Testing for Equality with equals()class JackAndJill {

public static void main(String args[]) {String s1 = new String("Jack went up the hill.");String s2 = new String("Jack went up the hill.");if ( s1.equals(s2) ) {System.out.println("The strings are the same.");

}else {

System.out.println("The strings are not the same.");}

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 50

continuecontinue and and exitexit StatementStatement

continueกลับไปตรวจสอบเง่ือนไขแลวทํา LOOP ถัดไป

breakออกจาก LOOP หน่ึงลําดับช้ัน

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 51

continuecontinue and and breakbreak StatementStatement 22• Example

for (i = 1;i <= 10;i++) {if (i>3) continue;

}

while (i == 10) {X = X + 1;if (X == 3) break;

}

for (i = 1;i <= 10;i++) {while (j < 5) {

k = i + j;if (k > 25) break;

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 52

Breakclass CountWheat {

public static void main (String args[]) {int i, j, k;j = 1;k = 0;for (i=1; i <= 64; i++) {

j *= 2;if (j <= 0) {

System.out.println("Error: Overflow");break;

}k += j;System.out.print(k + "\t ");if (i%4 == 0) System.out.println();

}System.out.println("All done!");

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 53

Continuefor (int i = 0; i < m.length; i++) {

if (m[i] % 2 == 0) continue;// process odd elements...

}

for (int i = 0; i < m.length; i++) {if (m[i] % 2 != 0) {// process odd elements...}

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 54

Labeled Loopsfor (int i=1; i < 10; i++) {

for (int j=1; j < 4; j++) {if (j == 2) break;System.out.println(i + ", " + j);

}}

1, 12, 13, 14, 15, 16, 17, 18, 19, 1

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 55

Labeled Loops 2iloop: for (int i=1; i < 3; i++) {

for (int j=1; j < 4; j++) {if (j == 2) break iloop;System.out.println(i + ", " + j);

}}

1, 1

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 56

The switch statement in Javaif (x == 0) doSomething();else if (x == 1) doSomething1();else if (x == 2) doSomething2();else if (x == 3) doSomething3();else if (x == 4) doSomething4();else doSomething() else;

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 57

switch caseswitch case StatementStatementswitch (Expression) {

case constant_1:StatementBlock_1;

break;case constant_2:

StatementBlock_2;

break;default:

StatementBlock_n;break;

}

CASE

งานท่ี 1

งานท่ี 4งานท่ี 2

งานท่ี 3

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 58

switch (x) {case 0:

doSomething();break;

case 1:doSomething1();break;

case 2:doSomething2();break;

case 3:doSomething3();break;

default:doSomething4();

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 59

The ? : operator in Javaif (a > b) {

max = a;}else {

max = b;}

you can rewrite the above example in a single line like this:max = (a > b) ? a : b;

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 60

The ? : operator in Javaif (name.equals("Rumplestiltskin")) {

System.out.println("Give back child");}else {

System.out.println("Laugh");}

This may not be written like this:name.equals("Rumplestiltskin")

? System.out.println("Give back child"): System.out.println("Laugh");

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 61

Logical Operators in Javaif (x == 2) {

if (y != 2) {System.out.println("Both conditions are true.");

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 62

ANDAND OperatorsOperators (&&)(&&)• && is logical and.

– && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance

boolean b;b = 3 > 2 && 5 < 7; // b is trueb = 2 > 3 && 5 < 7; // b is now false

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 63

OROR OperatorsOperators (||)(||)• || is logical or.

– || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance

boolean b;b = 3 > 2 || 5 < 7; // b is trueb = 2 > 3 || 5 < 7; // b is still trueb = 2 > 3 || 5 > 7; // now b is false

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 64

NOT NOT OperatorsOperators (!)(!)• The last logic operator is ! which means not.

– It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true.

boolean b;b = !(3 > 2); // b is falseb = !(2 > 3); // b is true

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 65

Logical OperatorLogical Operatorif (x == 2) {

if (y != 2) {System.out.println("Both conditions are true.");

}}

if (x == 2 && y != 2) {System.out.println("Both conditions are true.");

}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 66

The Order of Evaluation of Logic Operatorsboolean b, c, d;b = !(3 > 2); // b is falsec = !(2 > 3); // c is trued = b && c; // d is false

boolean b = (n == 0) || (m/n > 2);

boolean b = (n != 0) && (m/n > 0);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 67

PrecedenceFinally let's add the &&, ||, &, | and ? operators to the precedence table

1. *, /, % Multiplicative operators2. +, - Additive operators3. <, >, >=, <= Relational operators4. ==, != Then do any comparisons for equality

and inequality5. & Bitwise and6. | Bitwise or7. && Logical and8. || Logical or9. ? : Conditional operator10. = Assignment operator

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 68

Declaring Arraysint[] k;float[] yt;String[] names;

int k[];float yt[];String names[];

int k[3];float yt[7];String names[100];

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 69

Creating Arraysk = new int[3];yt = new float[7];names = new String[50];

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 70

Initializing Arraysk[0] = 2;k[1] = 5;k[2] = -2;yt[17] = 7.5f;names[4] = "Fred";

float[] squares;squares = new float[101];for (int i=0; i <= 100; i++) {

squares[i] = i*i;}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 71

• Two things you should note about this code fragment:1. Watch the fenceposts! Since array subscripts begin at zero you need 101

components if you want to include the square of 100.2. Although i is an int, it is promoted to a float when it is stored in squares, since

squares is declared to be an array of floats.

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 72

System.arraycopy()public static void arraycopy(

Object source,int sourcePosition,Object destination,int destinationPosition,int numberOfElements);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 73

Copy ArrayCopy Arrayint[] unicode = new int[65536];

for (int i = 0; i < unicode.length; i++) {unicode[i] = i;

}

int[] latin1 = new int[256];System.arraycopy(unicode, 0, latin1, 0, 256);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 74

Multi-Dimensional Arrays

M[3][4]M[3][3]M[3][2]M[3][1]M[3][0]

M[2][4]M[2][3]M[2][2]M[2][1]M[2][0]

M[1][4]M[1][3]M[1][2]M[1][1]M[1][0]

M[0][4]M[0][3]M[0][2]M[0][1]M[0][0]

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 75

Declaring, Allocating and Initializing Two Dimensional Arrays

• This example fills a two-dimensional array with the sum of the row and column indexes

class FillArray {public static void main (String args[]) {

int[][] matrix;matrix = new int[4][5];for (int row=0; row < 4; row++) {

for (int col=0; col < 5; col++) {matrix[row][col] = row+col;

}}

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 76

class IDMatrix {public static void main (String args[]) {

double[][] id;id = new double[4][4];for (int row=0; row < 4; row++) {

for (int col=0; col < 4; col++) {if (row != col) {

id[row][col] = 0.0;} else {

id[row][col] = 1.0;}

}}

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 77

Initializing Two Dimensional Arraysdouble[][] ID3 = { {1.0, 0.0, 0.0},

{0.0, 1.0, 0.0},{0.0, 0.0, 1.0}

};

double[][] ID3 = {{1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{0.0, 0.0,1.0}};

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 78

Even Higher Dimensionsclass Fill3DArray {

public static void main (String args[]) {int[][][] M;M = new int[4][5][3];for (int row=0; row < 4; row++) {

for (int col=0; col < 5; col++) {for (int ver=0; ver < 3; ver++) {

M[row][col][ver] = row+col+ver;}

}}

}}

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 79

Show Input Dialog BoxShow Input Dialog Boximport javax.swing.JOptionPane;

String firstNumber;firstNumber = JOptionPane.showInputDialog(“Enter first integer”);

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 80

Show Message Dialog BoxShow Message Dialog Boximport javax.swing.JOptionPane;

JOptionPane.showMessageDialog(null,“Please press OK!”,“Confirm”JOptionPane.PLAIN_MESSAGE);

OptionJOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGEJOptionPane.ERROR_MESSAGE

23 มิถุนายน 2547 ปรีดา เลิศพงศวิภูษณะ ([email protected]) 81

คําถามคําตอบคําถามคําตอบ

ปรีดา เลิศพงศวิภูษณะ[email protected]

ภาควิชาวิศวกรรมคอมพิวเตอรคณะวิศวกรรมศาสตร มหาวิทยาลัยเกษตรศาสตร