36
1 Java Programming Java Syntax from the Ground Up CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 2 Introduction CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 3 Lexical Structure - Unicode Character Set ! Most languages use a 7/8 bit ASCII code table for encoding (128/256 different characters) CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 4 Lexical Structure - Unicode ! Unicode is 16 bit (32,768 different characters) ! Special unicode editor might be required ! or, encode characters as \uxxxx ! xxxx is in hex ! Examples: ! \ux0020 is space ! \u03c0 is !

Introduction - University of Nevada, Las Vegas

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction - University of Nevada, Las Vegas

1

Java Programming

Java Syntax from the Ground Up

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 2

Introduction

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 3

Lexical Structure -Unicode Character Set

! Most languages use a 7/8 bit ASCII codetable for encoding (128/256 differentcharacters)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 4

Lexical Structure - Unicode

! Unicode is 16 bit (32,768 differentcharacters)! Special unicode editor might be required! or, encode characters as \uxxxx

! xxxx is in hex! Examples:

! \ux0020 is space! \u03c0 is !

Page 2: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 5

Lexical Structure -Case-Sensitivity and Whitespace

! Java is cAse-SEnsitIve ;-)! While, WHILE, and while are different

things! While and WHILE are identifiers.! while is a reserved word.

! If you have declared a variable i you cannotrefer to it as I.

! Whitespace is ignored (spaces, tabs andnewlines)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 6

Comments

! Comments are ignored by the compiler;there are three different types ofcomments:! Single line comment ( //… )int i = 0; // initialize the loop variable

! Multi-line comments (type 1, /* … */)/* * First, establish a connection to the server. * If the connection attempt fails, quit right away */

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 7

Comments

! Multi-line comments (type 2, /** … */,doc-comment) used for generatingautomatic Javadoc documentation/** * Upload a file to a web server * * @param file The file to upload * @return <tt>true</tt> on success. * <tt>false</tt> on failures. * @author David Flanagan */

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 8

Generated Javadoc

Page 3: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 9

Reserved Words

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconstabstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 10

Reserved Words (Modifiers)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 11

Reserved Words (Types)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 12

Reserved Words (Exceptions)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

Page 4: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 13

Reserved Words (Control Flow)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 14

Reserved Words (Literals)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 15

Reserved Words (Modularity)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 16

Reserved Words (OO stuff)

thisprotectedinstanceoffalseclass

whilesyncrhonizedprivateimportextendschar

volatileswitchpackageimplementsenumcatch

voidsupernullifelsecase

trystrictfpnewgotodoublebyte

truestaticnativefordobreak

transientshortlongfloatdefaultboolean

throwsreturninterfacefinallycontinueassert

throwpublicintfinalconst abstract

Page 5: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 17

Identifiers

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 18

Literals

! Integer and floating point numbers,characters, strings, as well as true,false and null

1, 1.0, 1f, 1L, ‘1’, “one”, true, null

(int, double, float, long, char, string, boolean, class type)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 19

Punctuation

! Separators( ) { } [ ] < > : ; , . @

! Operators+ - * / % & | ^ << >> >>>+= -= *= /= %= &= |= ^= <<= >>= >>>== == != < <= > >=! ~ && || ++ ? :

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 20

Primitive Data Types! Java supports 8 primitive types

+/-4.9E-324 to+/-1.7976931348623157E+308

64 bit0.00IEEE 754 floatingpoint

double

+/-1.4E-45 to +/-3.4028235E+3832 bit0.0IEEE 754 floatingpoint

float

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,80764 bit0Signed integerlong

-2,147,483,648 to 2,147,483,64732 bit0Signed integerint

-32,768 to 3276716 bit0Signed integershort

-128 to 1278 bits0Signed integerbyte

\u0000 to \uffff16 bits\u0000Unicode characterchar

N/A1 bitfalsetrue or falseboolean

RangeSizeDefaultContainsType

Page 6: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 21

The boolean Type

! Represents a truth value.! Only two possible values:true or false

! Not like C where 0 is false and anythingelse is true.

! Cannot be compared to integers.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 22

The char Type

! Represents unicode characterschar c = ’A’;char tab = ’\t’;char apostrophe = ’\’’;char nul = ’\000’;char aleph = ’\u05D0’;

! Note the difference here:char \u05D0 = ’\u05D0’;

\u05D0 is a variable name is unicode‘\u05D0’ is a character literal inunicode.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 23

The char Type

Unicode character xxxx hexadecimal value\uxxxxLatin-1 character xxx octal value (0 to 377)\xxx/Backslash\\Single quote\’Double quote\”Carriage return\rForm feed\fNewline\nHorizontal tab\tBackspace\bCharacter valueEscape sequence

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 24

Strings

! String is not a primitive type, but aclass.

! Java does allow string Literals”Hello, World””This is a string!”

! Or some code:String greeting = “Hello stranger!”;String \u03c0 = "\"\'\u03c0\'\"";

delcares a string ”’π’” in a unicodevariable called \u03c0

Page 7: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 25

Integer Types

! byte, short, integer, and long areall signed integer types (no unsignedinteger types exist in java)! 255 (decimal) = 0xff (hex) = 0377 (octal)! 1234 is a int value, 1234L is a long value

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 26

Overflow

! Neither the compiler nor the runtimesystem catches overflow

byte b1 = 127, b2 = 1;byte sum = (byte)(b1 + b2);

! What is the value of sum?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 27

Wrapper Classes

! Classes for each integer type exist:Byte, Short, Integer, Long(Note the capital letter)

Byte.MAX_VALUEByte.MIN_VALUE

gives the max/min byte values

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 28

Floating-Point Types

! Real numbers in Java are representedby the float and double data types.

! 123.45! 0.0! .01! 1.2345E02 // 1.2345*102, or 123.45! 1e-6 // 1*106, or 0.000001

Page 8: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 29

Floating-Point Types

! Just like integer values are int types bydefault, floating point values are doubleby default.

double d = 6.02E23;float f = 6.02E23f;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 30

Floating-Point Types

! int i = 1/0 causes an exception,division by 0 is illegal in integerarithmetic.

! double inf = 1.0/0.0 does notcause an exception.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 31

Floating-Point Types

! 4 Special ‘values’ for floating points:

double inf = 1.0/0.0; // prints Infinitydouble neginf = -1.0/0.0; // prints -Infinitydouble negzero = -1.0/inf; // prints -0double NaN = 0.0/0.0; // prints NaN

! Infinity + anything = Infinity! -0 == 0! NaN is not equal to anything (incl. itself)! Double.isNaN() checks for NaN

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 32

Primitive Type Conversions

! Conversion is legal between integer andfloating points (incl. chars, but notboolean)! Widening: A value is converted to a type

with a larger range of legal values:double d = 10;

double is a ‘wider’ type than int.! Widening is always allowed

Page 9: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 33

Primitive Type Conversions

! Narrowing: Converting a value to a type thathas a smaller range of legal values.! Ok sometimes: int value 13 can be converted to

a byte, but 1300 cannot (byte range is -128 to127)

! Narrowing conversions can be forced by a cast.

int i = 13;byte b = (byte)i; // force int to be converted to a bytei = (int)13.456; // force this double literal to the int 13

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 34

Primitive Type Conversions

---CCCCCCNdouble

Y---CCCCCNfloat

Y*Y*---CCCCNlong

YY*Y---CCCNint

YYYY---CCNchar

YYYYC---CNshort

YYYYCY---Nbyte

NNNNNNN---booleandoublefloatlongintcharshortbyteboolean

ToFrom

Y = yes, the conversion is a widening.N = not, the conversion cannot occur.C = yes, the conversion must be a narrowing cast.Y* = yes, by automatic widening that can cause loss of precision. This can happen when converting int and long to float and double.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 35

Expressions and Operators

! The Java interpreter evaluatesexpressions to compute its value.

! The simplest expressions are calledprimary expressions, and consists ofliterals and variables: 1.7 // a floating point literal

true // a boolean literalsum // a variable

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 36

Expressions and Operators

! The value of a literal is the value itself:The value of 1.7 is 1.7!

! The value of a variable is the valuestored in the location in memoryrepresented by that variable

Page 10: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 37

Expressions and Operators

! We use operators together with primaryexpressions to form more interestingexpressions:

sum = 1.7sum = 1 + 2 +3*1.2 + (4+8)/3.0 sum/Math.sqrt(3.0 * 1.234)(int)(sum + 33)

! Note, all valid expressions; assignments arenot statements but expressions, they have avalue.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 38

Operator Summary

Left shift ( * 2)Right shift w/sign extension ( / 2)Right shift w/zero extension

Integer, integerInteger, integerInteger, integer

<<>>>>>

L10

Addition, subtractionString concatenation

Number, numberString, any

+,-+

L11

Multiplication, division, remainderNumber, number*,/,%L12

Object creationCast (type conversion)

Class, anyType, any

new( type )

R13

Pre increment/decrementUnary plus/minusBitwise complementBoolean NOT

VariableNumberIntegerBoolean

++/--+/-~!

R14

Object member accessArray element accessMethod invocationPost increment/decrement

Object, memberArray, intMethod, arglistVariable

.[ ]( args )++/--

L15

Operation PerformedOperand(s) typesOperatorAP

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 39

Operator Summary

Conditional ORBoolean, boolean||L3

Conditional ANDBoolean, boolean&&L4

Bitwise ORBoolean OR

Integer, integerBoolean, boolean

||

L5

Bitwise XORBoolean XOR

Integer, integerBoolean, boolean

^^

L6

Bitwise ANDBoolean AND

Integer, integerBoolean, boolean

&&

L7

Equal (have identical values)Not equal (have different values)Equal (refer to the same object)Not equal (refer to different objects)

Primitive, primitivePrimitive, primitiveReference, referenceReference, reference

==!===!=

L8

Less than, less than or equalGreater than, greater than or equalType comparison

Number, numberNumber, numberReference, type

<, <=>, >=Instanceof

L9

Operation PerformedOperand(s) typesOperatorAP

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 40

Operator Summary

AssignmentAssignment with operation

Variable, anyVariable, any

=*=, /=, %=,+=, -=, <<=,>>=, >>>=,&=, ^=, |=

R1

Conditional (ternary) operatorBoolean, any? :R2

Operation PerformedOperand(s) typesOperatorAP

Page 11: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 41

Precedence

! Precedence specifies the order in whichoperations are performed. Eg.:

1 + 2 * 3 // == 7* has higher precedence than +, and isperformed first. Precedence can beoverruled using ( ):

(1 + 2) * 3 // == 9

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 42

Associativity

! Associativity governs the order ofoperation when we use operators of thesame precedence.! a = b += c = -~d! is: a = (b += (c = -(~d)))! Precedence can be overridden using ( )

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 43

Operand Number and Type

! Operators take different number ofoperands:! Unary operators take one operand

! -8 (unary minus)! ~i (bitwise complement)

! Binary operators take two operands! a + 8 (binary plus)! a << 8 (binary left shift)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 44

Operand Number and Type

! Operators take different number ofoperands:! Ternary operators take three operands

! x > y ? x : y (called a ternary expression)! Like an ‘if’-statement, but as an expression! min = (x > y) ? x : y

Page 12: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 45

Operand Number and Type

! Not all operators work on all types.! -”Hello”

(you cannot negate a string)! a + false

(+ does not work with booleans)! x > y ? “x is greater” : y

(Why is this one wrong? ;-) )

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 46

Return Type

! Just as an operator only works onspecific types, it also returns a value of aspecific type (sometimes dependent onthe type of the operands)! 1 + 1 = 2 (int + int = int)! 1.0 + 2.0 = 3.0

(double + double = double)! 1 + 2.0 = ???

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 47

Return Type

! Not all operators return values of thesame type as their operands:! a < 0 is of boolean type! x < y ? “x is smaller” : “y issmaller”always returns values of string type, but xand y can be any type compatible with <.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 48

Side Effects

int a=2;a = ++a + ++a * a++;

Page 13: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 49

Order of Evaluation

! The order in which operands areevaluated is always left to right! Taking into account

! Associativity of operator! Precedense of operator! Parentehsis ( )

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 50

Order of Evaluation

! Some operators do not evaluate all theiroperands:! x ? y : z (Ternary), only x and the

chosen branch are evaluated! x && y. If x is false there is no need to

evaluate y.! x || y. if x is true there is no need to

evaluate y.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 51

Order of Evaluation

int a = 2;int v = ++a + ++a * ++a;

What is the value of v after theassignment?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 52

Arithmetic Operators

! Addition (+)! Normally + adds numbers:

! 2 + 2 = 4 (integer + integer = integer)! 2 + 2.0 = 4.0 (integer + double = double)

! Can be used on strings:! “Hello “ + “world” = “Hello world”

! Be careful when mixing strings and numbers! “Total: “ + 3 + 4 = “Total: 34”! 3 + 4 + “ is the total” = “7 is the total”

Page 14: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 53

Arithmetic Operators

! Other arithmetic operators:! Subtraction (-), both binary and unary! Multiplication (*)! Division (/ )

! 7/3 = 2! 7/3.0f = 2.3333333! 7/3.0 = 2.3333333333333335! 7/0 causes a runtime error (An exception)! 7/0.0 evaluates to ! (positive infinity)! 0.0/0.0 evaluates to NaN (Not a Number)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 54

String Concatenation Operator

! Reminder: + and += can be used withstrings.

! Objects are converted to strings with thetoString() method(more about that later)

! “Once a string, always a string”:remember to use ( ) around arithmeticwhen mixed with strings.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 55

Increment/Decrement Operators

! ++ or -- increment/decrement its singleoperand by 1.i = 1;j= i++;Is equivalent toi = 1;j = i + 1;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 56

Increment/Decrement Operators

! a++ is not the same as ++a.! a++ uses the value of a then incrementint a = 1;System.out.println(a++); // prints 2

! ++a increments the value of a then uses itint a = 1;System.out.println(++a); // prints 1

Page 15: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 57

Increment/Decrement Operators

! Be REAL careful about the ++ and --operators.

! Most of time x++ is equivalent tox = x + 1

! But not always:a[i++]++;a[i++] = a[i++] + 1;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 58

Comparison Operators

! Used to test equality and size (order)! == equal (values!)

! Eg. a == b tests is the value stored in a is thesame as the value stored in b

! != not equal! a != b is the same as !(a == b)

! Careful: = is not a test for equality, it isassignment

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 59

Comparison Operators

! <, >, <=, >=! For comparing values that are ordered

! !=, == works on ‘anything’! <, >, <=, >= works on numbers only

! The result of all of these operators is aboolean value: either true or false

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 60

Comparison Operators

Example:boolean b;int a, c;a = 10;c = 4;

b = !(a > c);

What is the value of b?

Page 16: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 61

Boolean Operators

! A number of operators work on booleanvalues. They are either binary (two operands)or unary (one operand), but all produce aboolean result:! && Conditional AND

! true && true == true! true && false == false! false && false == false! false && true == false

Example: (x < 10 && y > 3)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 62

Boolean Operators

! || Conditional OR! true || true == true! true || false == true! false || false == false! false || true == true

! ! Boolean NOT! !true == false! !false == true

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 63

Short Circuit Boolean Evaluation

! Remember: Evaluation from LEFT to RIGHT,and with SCBE.

! To avoid SCBE and force evaluation of alloperand expressions use & and | instead.

! & and | used with integer operands computesa bit-wise operation. and | used with integeroperands computes a bit-wise operation.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 64

Boolean Operators

! ^ is exclusive or (XOR)! true ^ true == false! true ^ false == true! false ^ true = true! false ^ false = false

! Can be used on integers as well! With boolean operands: ^ is the same as!=

Page 17: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 65

Bitwise Operators

! Used to manipulate the individual bits ofintegral values/variables:! ~ bitwise complement! & bitwise AND (we already saw this with

booleans)! | bitwise OR! ^ bitwise XOR

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 66

Shift Operators

! Shift operators moves bits left or right:! << Left Shift:

10 << 1 // 00001010 << 1 == 00010100 = 20 = 10*2

! >> Signed Right Shift:27 >> 3 // 00011011 >> 3 == 00000011 = 3 /27/(2*2*2)-50 >> 2 // 11001110 >> 2 == 11110011 = -13 = -50/(2*2)

! >>> Unsigned Right Shift:-50 >>> 2 // 0xFFFFFFCE >>> 2 = 0x3FFFFFF3

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 67

Assignment Operator

! We have already see this one:! = (and not == which is comparison)

! Others exist:! += for example: a += 2; which is the same

as a = a + 2;! Others: -=, *=, /=, %=, &=, |=,^=, <<=, >>=, >>>=

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 68

The Conditional Operator

! The only operator to take three operands:! … ? … : …Example:a > 10 ? b+1 : c-2

! If a>10 then the entire thing evaluates to the valueof the expression b+1, else the value of c-2

! Really is an if-expression (as opposed to an ifstatement.

! Can be used as an expression: d = a>2 ? 4 :8;

! The two last operand expressions must be thesame type

Page 18: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 69

The Conditional Operator

! Example of the conditional operator! Compute max value of x and y and assign to z;

if (x > y) z = x;else z = y;

! Orz = (x > y) ? x : y;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 70

The instanceof Operator

! We will return to this one later! Determines if the left hand side object expression is

an object of a certain class type:! o instanceof A

! True if o is an object based on class A.

! Note, if o instanceof A is true, and B is asuper class of A, o instanceof B will also betrue.

! Tells us when it is safe to ‘cast’ an object referenceto a different class type.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 71

Special Operators

! A number exist, let’s just considerexplicit casting! Explicit casting is “changing the type of a

value”(byte) 28(float) 3.14

! Objects can be cast as well.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 72

Statements

! A Statement is a single command that has noreturn value. They include! Expression statements (Expressions where return values are

ignored)! Compound (block) statements: { … }! Empty statement: ;! Local variable declarations: int a;! If/else statement: if (…) … else …! Switch statement: switch (…) { case ..: …. ….. }! While statement: while (…) …! Do statement: do … while (…)! For statement: for (…;…;…) …! Break- / continue- / return-statement

Page 19: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 73

Expression Statements

! An expression statement is anexpression used as a statement (valueof expression is ignored)a = 1;a *= 2;--c;f(7);

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 74

Compound Statements

a = 10; b = 1; while (a > 0) a = a - 1; b = b * 2;

What is the value of a and bafter the loop?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 75

Compound Statements

a = 10; b = 1; while (a > 0) a = a - 1; b = b * 2;

What is the value of a and bafter the loop?

a = 0b = 2

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 76

Compound Statements

! A compound statement is a number ofstatements grouped together using { }

a = 10;b = 1;

while (a > 0) { b = b * 2; a = a - 1;

}

Page 20: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 77

The Empty Statement

! The empty statement is just a semicolon:;

for (int i=0; i<10; a[i++]++) ;

! Rarely a use for it! The above exampleshould be written differently

for (int i=0; i<10; i++) { a[I]++;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 78

Local Variable Declarations

! We know how to do these:<type> name;<type> name = <expr>

! But for how long is a name ‘valid’?! The part of the code where a name can be

referenced is called the name’s scope.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 79

Scope

{int a = 10;int b = 1;while (a > 0){ int c = b * 2; b = c;

}}Scope of a in red

{int a = 10;int b = 1;while (a > 0){ int c = b * 2; b = c;

}}

{int a = 10;int b = 1;while (a > 0){ int c = b * 2; b = c;

}}

Scope of c in redScope of b in red

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 80

! The scope of a local variable is the restof the closest enclosing block!! { } creates a block! ….. Others to come later

Page 21: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 81

If-statements

! Used for flow control (decisions)! Two general forms:

if (<bexpr>)<then-stmt>

if (<bexpr>)<then-stmt>

else<then-stmt>

If <bexpr> evaluates to true,then the <then-stmt> is executed,If <bexpr> evaluates to false,execution continues at …

If <bexpr> evaluates to true,then the <then-stmt> is executed.If <bexpr> evaluates to false,then the <else-stmt> is executed

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 82

If-statements

! Be careful about nested if-statements:if (i==j) if (j==k) System.out.println(“i = k”);else

System.out.println(“i != j”);

! An else always matches the inner-mostif. To make sure you get it right use { }

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 83

If-statements

if (i==j) { if (j==k) { System.out.println(“i = k”);}

} else { System.out.println(“i != j”);}

Technically { } and { } are not needed.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 84

If-statements

! If-statements can alsobe chained:if (i == 2) { b = 3;} else if (i == 3) {b = 5;

} else if (i == 4) {b = 7;

} else {b = 9;

}

if (i == 2) b = 3;else if (i == 3)b = 5;

else if (i == 4)b = 7;

elseb = 9;

or without { }

Page 22: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 85

Switch-statement

! A multi-case replacement for a lot of if-statementsif (n == 1) a = 2;else if (n == 2) a = 4;else if (n == 3) a = 6;else if (n == 4 || n == 5) a = 7;else a = 9;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 86

Switch-statement

! A multi-case replacement for a lot of if-statementsif (n == 1) a = 2;else if (n == 2) a = 4;else if (n == 3) a = 6;else if (n == 4 || n == 5) a = 7;else a = 9;

switch (n) { case 1: a = 2; break; case 2: a = 4; break; case 3: a = 6; break; case 4: case 5: a = 7; break; default: a = 9; break;}

Same as

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 87

Switch-statement

! A few things are important to rememberabout switch-statements.! The default label is optional (just likeelse is!)

! The break statement for each case isoptional (but almost always needed)! When hitting a break (!) in a switch statement,

control jumps to the end of it (I.e., the } )

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 88

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 2;

Page 23: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 89

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 2;

}

4321

cban

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 90

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 1;

}

432

1111cban

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 91

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 1;

}

43

11021111cban

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 92

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 1;

}

4110311021111cban

Page 24: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 93

Switch-statement

! Consider this:a = b = c = 0;switch (n) { case 1: a = 1;

case 2: case 3: b = 1;default: c = 2;

}

1004110311021111cban

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 94

While-statement

! Simple looping mechanismwhile (<bexpr>)<statement>

! While the <bexpr> is true, execute<statement> and go back andevaluate the <bexpr>

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 95

While-statement

! Remember, if more than one statementis to be executed, use { }:

b = 1; b = 1;while (a > 0) { while (a > 0)

a = a - 1; vs. a = a - 1;b = b * 2; b = b * 2;

}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 96

While-statement

! Remember, if more than one statementis to be executed, use { }:

b = 1; b = 1;while (a > 0) { while (a > 0)

a = a - 1; vs. a = a - 1;b = b * 2; b = b * 2;

}a = 0 and b = 2a a = 0 and b = 2

Page 25: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 97

Do Statement

! Almost like a while:do statementwhile ( expression );

! statement always executes at leastonce.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 98

While vs do

a = 100; a = 100;b = 1; b = 1;while (a > 0) { do {

a = a - 1; a = a - 1;b = b * 2; b = b * 2;

} }

! Are these two pieces of the same?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 99

While vs do

while (expression) do statement statement

while (expression)

! Are these two pieces of the same?! Always???

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 100

While vs do

b = 0; b = 0;while (a > 0) { do {

b = b + 2; b = b + 2;a = a - 1; a = a - 1;

} } while (a > 0)

! For which values of a do they produce the sameresult?

Page 26: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 101

Do statement

! Can we make a do loop work like a whileloop?while (expression) statement

if (expression) do statement while (expression)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 102

Do statement

! Can we make a do loop work like a whileloop?while (expression) statement

if (expression) do statement while (expression)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 103

For statement

! One last loop mechanism: the for loopfor (initialize; test; update) statement

! initialize is executed ONCE! test is executed BEFORE the statement; the

statement is executed for as long as test istrue

! update is executed after the statement

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 104

For statement

for (initialize; test; update) statement

! is equivalent toinitializetest; statement; update; test; statement; update;…test; statement; update; test;

Page 27: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 105

For statement

int result = 0; for (int i=1; i<=100; i++)

result = result + i;

! Sums up the first 100 numbers.! Note:

! You may declare variables in the initializer.! The scope of these variables is the body of the loop.! More than one variable can be initialized and more than

one variable can be updated.! If declaring one or more variable in the initializer nothing

else can go there!

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 106

For statement

int result, count, i; for (result=0, count=0, i=0; i<=100; i=i+2, count++)

result = result + i;

! For loops can be written using while loopseasily:

initialize;while (test) { statement;

update;}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 107

For/in statement

! Special type of for loop:for (declaration : expression) statement

! Often used to ‘iterate’ through acollection/arrayint[] primes = new int[] {2,3,5,7,9,11,13,17,19,23,29}for (int n: primes) System.out.println(n);

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 108

For/in statement

int[] primes = new int[] {2,3,5,7,9,11,13,17,19,23,29}for (int n: primes) System.out.println(n);

! The base type of the iterating variablemust match that of the collection.! More on arrays soon!

Page 28: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 109

Skipping for now

! Break! Continue! Return

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 110

Skipping completely

! Synchronized! Throw/exceptions! Assert

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 111

Methods

! A method is a way to abstract awaycomputation.! Just like math: f(x,y) = x*x + y*y;

! It has formal paramters (x,y)! It has a (return) type: what ever type x*x + y*y is.! It can be applied to many different pairs of actual

parameters: f(6,7), f(8,9), f(g(5),5),….

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 112

Methods

! Simple example:public int f(int x, int y) { int result; result = x*x + y*y; return result;}

! public is a modifier (more about that later)! int is the type that the method returns! f is the name, int x, int y the formal

paramters.

Page 29: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 113

Methods

! Simple example:public int f(int x, int y) { int result; result = x*x + y*y; return result;}

int a;a = f(5,7);

! 5 and 7 are the actual parameters.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 114

Scoping in Methods

! Methods have the same scoping rules aswhat we have used until now except forthe parameters! The scope of a parameter is the entire body

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 115

Call by value

! A method in Java uses call by value callsemantics:void f(int a) { a = 10000;}

int a = 0;f(a);// value of a?

! The variable a is not passed to f, its VALUE is.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 116

Methods

! When calling a method, the order of the actualparameters must match the order of the formalparameters.

! The same number of actual parameters asformals must be passed to a method.

! If a method does no return anything, its type isvoid.

! Return value may be ignored.

Page 30: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 117

Arrays

! An array is a collection of values all ofthe same type (more or less!)! Either all of a primitive type! Or all of a reference type (more about that

later)! Not a primitive type, but an object type.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 118

Arrays

! Arrays are allocated dynamically! Cannot be allocated statically on the stack,

but must be on the heap.

int[] intArray;

declares a variable that can hold areference to an array of integers.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 119

No Static Arrays

! We cannot declare static arrays:

int[3] myLittleArray;or

int myBigArray[1000];

are both illegal.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 120

Creating an array

! All arrays must be allocated/createdbefore they can be used.! Unlike other primitives which are just there

when declaredint a; // you can assign to a

//and use it as an intint[] as; // you cannot use as until // it has been given a

// value

Page 31: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 121

Creating an Array

! Let us create an array of 100 integers:

int[] myInts;myInts = new int[100];

Or

int[] myInts = new int[100];

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 122

Indexing an array

! An array is indexed by an integer valuestarting at 0. The first element is at index0, the second at index 1 etc.

int[] myInts = new int[100];// index 0..99

for (int i=0; i<100; i++) myInts[i] = i;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 123

Indexing an array

! The first index of an array is index 0! The last is l-1 where l is the length of

the array.! The length can be obtained like this:

int len = myInts.length;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 124

! We could redo the code from 2 slidesago:

int[] myInts = new int[100]; // index 0..99for (int i=0; i<myInts.length; i++) myInts[i] = i;

Page 32: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 125

Initializing arrays

! We can write code to initialize an arraylike on the previous slide.

! Or we can do it when the array iscreated:int[] myInts = new int[]{0, 1, 2, 3, 4};

! When initializing an array like this, nosize is given. I.e., this is illegal: int[] myInts = new int[5]{0, 1, 2, 3, 4};

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 126

Call by reference vs call by value

! Consider the following code:public static void foo(int a) { a = 900;

}

public static void main(String[] args) { int a = 0; foo(a); int b=0; foo(b);

}

! What is the value of a and b after the call to foo?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 127

Call by reference vs call by value

! Consider the following code:public static void foo(int a) { a = 900;

}

public static void main(String[] args) { int a = 0; foo(a); // the value of a is still 0 int b=0; foo(b); // the value of b is still 0

}

! Remember, copies of the values of a and b are transferred tofoo, and the a parameter belongs to foo, and not main!

CALL BY VALUE:COPIES of the

ACTUAL parametersare passed to the

method. Any changesmade to the parameterseffect only the FORMALparameters inside the

method, not the ACTUALparameters passed.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 128

Call by reference vs call by value

! Consider the following code:public static void foo(int a) { a = 900;

}

public static void main(String[] args) { int a = 0; foo(a); // the value of a is still 0 int b=0; foo(b); // the value of b is still 0

}

! Remember, copies of the values of a and b are transferred tofoo, and the a parameter belongs to foo, and not main!

CALL BY VALUE:COPIES of the

ACTUAL parametersare passed to the

method. Any changesmade to the parameterseffect only the FORMALparameters inside the

method, not the ACTUALparameters passed.

CALL BY REFERENCE:Changes made to

the FORMAL parametersWILL effect the ACTUAL

parameters.

Page 33: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 129

Call by reference vs call by value

! All primitives in Java are passed by value (call-by-value)

! Arrays are passed by reference (call-by-reference)! Any chances made in a method to an array

parameter will be made to the actual parameter

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 130

Call by reference

public class ArrayTest {

public static void fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i; // <-- will change intArray }

public static void main(String[] args) { int[] intArray = new int[100]; fill(intArray);

for(int i=0;i<100;i++) System.out.println(intArray[i]); }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 131

Aliasing

public class ArrayTest {

public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;

return array; }

public static void main(String[] args) { int[] intArray = new int[100];

int[] newIntArray; newIntArray = fill(intArray);

for(int i=0;i<100;i++) { System.out.println(intArray[i]);

System.out.println(newIntArray[i]); } }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 132

Aliasing

public class ArrayTest {

public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;

return array; }

public static void main(String[] args) { int[] intArray = new int[100];

int[] newIntArray; newIntArray = fill(intArray);

for(int i=0;i<100;i++) { System.out.println(intArray[i]);

System.out.println(newIntArray[i]); } }}

intArray and newIntArraywill contain the same data.NOT copies of the samedata, but THE SAMEdata

Page 34: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 133

Aliasingpublic class ArrayTest {

public static int[] fill(int[] array) { for (int i=0;i<array.length;i++) array[i]=i;

return array; }

public static void main(String[] args) { int[] intArray = new int[100] int[] newIntArray; newIntArray = fill(intArray);

for(int i=0;i<100;i++) { System.out.println(intArray[i]);

System.out.println(newIntArray[i]); }}

The integer array is onlyallocated once; all other‘copies’ of it are just copiesof ‘arrows’ pointing to the same set of integers.

This is called aliasingWhen a method is invoked with an array parameter it is passed by reference

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 134

Multi-dimensional Arrays

! Java supports multi-dimensional arrays:int[][] twoDimArray;twoDimArray = new int[10][10];

! This creates a 2D array indexed like this:twoDimArray[0][0] = 100;twoDimArray[9][9] = 900;

! Java allows ‘ragged arrays’ (wherehigher dimensions’ entries aren’t thesame length.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 135

Ragged Arrays

int[][] bs = new int[2][];bs[0] = new int[5];bs[1] = new int[]{1,2,3};

! bs is 2 dimensional

! bs[0] is 1 dimensional of type int[]! bs[1] is 1 dimensional of type int[]

bs[0]

bs[1]

bs[0][0]Val: ?

bs[0][1]Val: ?

bs[0][2]Val: ?

bs[0][3]Val: ?

bs[1][0]Val: 1

bs[0][4]Val: ?

bs[1][1]Val: 2

bs[1][2]Val: 3

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 136

Multi-dimensional arrays

! You may leave the allocation of a higherdimension to later (last slide), but youmay not leave lower ones:

int[][] bs = new[][2]; // illegal

Page 35: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 137

Multi-dimensional arrayconstants

! We can write constants of multi-dimensional type as well:

int[][] myInts = new int[][]{ {1,2}, {3,4,5,6},

{7,8,9} };

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 138

Copying arrays

! As we have seen using = on arrayvariables just copies a ‘pointer’

! If we want to copy an entire array we caneither use a for loop and copy theelements by hand, or use .clone()int[] a = new int[]{1,2,3};int[] b = a.clone();a[1] = 900; // a = {1,900,3}, b={1,2,3}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 139

Copying array

int[][] bs = new int[2][]; bs[0] = new int[]{100,200,300}; bs[1] = new int[]{1,2,3}; int[][] q = bs.clone(); bs[0][1] = 999;

System.out.println(q[0][1]);

What is printed?

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 140

Copying array

int[][] bs = new int[2][]; bs[0] = new int[]{100,200,300}; bs[1] = new int[]{1,2,3}; int[][] q = bs.clone(); bs[0][1] = 999;

System.out.println(q[0][1]);

What is printed? 999

.clone() is a SHALLOWcopy - it copies only the TOP level. If an arraycontains entries that arereference, then they arecopied as REFERENCESnot as VALUES.

Page 36: Introduction - University of Nevada, Las Vegas

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 141

Traversing an array

! We are familiar with this:int sum = 0;for(int i=0; i<myArray.lengh; i++) sum = sum + myArray[i]

! We can use a different for-loop int sum = 0;

for (int e : myArray) sum = sum + e;