Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Java Language Basics Java Statements –Declarations primitive types classes modifiers –Expressions operators –arithmetic, bitwise, comparison,

Similar presentations


Presentation on theme: "Chapter 5: Java Language Basics Java Statements –Declarations primitive types classes modifiers –Expressions operators –arithmetic, bitwise, comparison,"— Presentation transcript:

1 Chapter 5: Java Language Basics Java Statements –Declarations primitive types classes modifiers –Expressions operators –arithmetic, bitwise, comparison, logical, assignment compound (precedence, associativity) Math class –Return statements –Conditional statements if if-else switch

2 Java Language A Java program consists of a set of classes –an application program has a method main –an applet generally has a class that extends the Applet class (instantiated when applet run) Classes have instance vars and methods –methods have a header and body –body consists of a sequence of statements

3 Java Statements Declarations - of variables Expression statements –includes method calls Return statements Empty statements Group (compound) statements - more later All statements end with semi-colon(;)

4 Declarations At the class level (outside of a method), they define instance variables –each class member has a slot for instance vars In a method they create a local variable –“local” - exists only when method is running –disappears when method ends

5 Declaration Forms PrimitiveType Name Class Name PrimitiveType Name = Expression –Expressions can be primitive values Class Name = new Class(args) - ctor call Class Name = Expression - returns instance Class Name = ClassValue - somewhat rare

6 Primitive Type Values Differ from classes, have possible values, don’t need to instantiate –Primitives have lots or preestablished values –Primitives don’t allow the creation of new values Example: integer 1, don’t need to create an instance with value 1, “1” translates to 1

7 Primitive Types Whole numbers: byte, short, int, long –differ by the number of bits (8,16,32,64) –limited (by #bits), short -32768 to 32767 Floating point numbers: float, double –differ by number of bits (32,64) Character values: char Logical values: boolean

8 Whole Numbers value format: [ + | - ] digit digit* L at end for long constants examples: +5, 3, -30, 0005, 5000L representation: two’s complement –can use bitwise ops to extract parts of number

9 Two’s Complement positive number: 0 (sign) + binarynum –ex. 0 + 0100101 = 37 = (2^5 + 2^2 + 2^0) negative numbers: –take binarynum for magnitude (37 = 0100101) –invert (change 1s to 0s) (1011010) –add 1 (1011011) –add leading 1 for sign –-37 = (11011011)

10 Floating-Point Numbers Constant values optional sign (+|-) plus digitstring, digitstring “.”, “.” digitString, or digitString “.” digitString plus optional exponent: “e” intString examples: 3, 3.0,.4e+20, 3.4e-097 add f at end for float constants representation: sign (1 bit) + magnitude + exponent

11 Characters Constant values between single quotes (‘) Special values: –‘\b’ - backspace –‘\n’ - linefeed –‘\r’ - carriage return –‘\t’ - tab char –‘\’’ - quote –‘\\’ - backslash –‘\”’ - double quote

12 Logical (boolean) values constant values: true, false no other values

13 Instance Variable Modifiers Various terms can appear before each instance variables (and methods): –access modifiers: private, protected, public determine where the var/class can be accessed –static indicates only one copy needed –final indicates initial value is “final” Can appear in order (up to you)

14 Static A static instance variable means there is one copy for the whole class –static int classcount = 0; // count # instances A static method is usually associated with a class that cannot be sub-classed (e.g. Math classes) Can refer to static vars through class (as in Math.PI)

15 Final A final instance variable is given a value, and the value remains unchanged (constant) –often used with static –final static double PI = 3.14152…; in a final declaration there must be an assignment (=), once this assignment is done no change is allowed

16 Access Modifiers private - this instance/method can only be used by members of the class (not inherited) protected - same as private, except can be inherited public - can be used/accessed by any class (be careful with public instance vars) package (default) - used by any member of package

17 Object-Oriented Orientation Generally restrict access (make instance vars private) How to change/look at vars outside class? –Accessor method (method that returns value) –Mutator method (method that changes value)

18 Making a Package Put files in a directory with package name At the top of each file add a statement: package myPackageName; To include your package in another class definition: import myPackageName.*; etc.

19 Scope Common problems: –undefined variable (Java does not see var) –multiply defined variable –resolved by scoping rules Rules: –item connected to most recent declaration –cannot have two items with same name in same block

20 Scope Example class MyClass { int huh = 2; void method1() { int huh = 3; // is huh 2 or 3 here? } void method2() { // is huh 2 or 3 here? } void huh() { // is this ok? }

21 Expressions Need not be simple values Can be the result of a complex calculation involving operators (+, *, &&) Java has rules for resolving operators Some operators provided by Math class (automatically included)

22 Arithmetic Operators Apply to numbers (whole, floating-point) + - addition (e.g. 5 + 3 is 8) also used as unary (as in + 5) - - subtraction (e.g. 5 - 3 is 2) also used as unary (as in - 3) * - multiplication (e.g. 5 * 3 is 15) / - division (e.g. 5 / 3 is 1 or 1.66666) result depends on args (whole -> whole, float-> float) % - mod or remainder (e.g. 5 % 3 is 2) whole nums only

23 Bitwise Operators Apply to integrals (whole numbers, chars) Assume x=10001000, y=11000111 ~ - one’s complement (flip bits) (~x is 01110111) & - and (x & y is 10000000) | - or (x | y is 11001111) ^ - xor (x ^ y is 01001111) << - left shift, pad with 0 (x << 5 is 00000000) >> - right shift, pad leftmost (x >> 5 11111100) >>> - right shift, pad 0 (x >>> 5 is 00000100)

24 Comparison Operators Apply to all primitive types Assume x = 5 == - equals (x == 5 is true) applies to all types != - not equals (x != 5 is false) applies to all <= - less than or equal (x <= 5 is true) >= - greater than or equal (x >= 5 is true) < - less than (x < 5 is false) > - greater than (x > 5 is false)

25 Logical Operators Apply to boolean expressions Assume p is true q is false ! - not (!p is false) & - and (p & q is false) && - short circuit and (p && q is false) | - or (p | q is true) || - short circuit or (p || q is true) ^ - have different values (p ^ q is true) “short circuit” - if first arg determines value, second arg not evaluated

26 Assignment Operators Set the value of any variable = - assign (x = 5) can be strung together x = y = 5 Assignment shorthands: example: x += 5 is x = x + 5 others: -=, *=, /=, %=, >=, >>>=, &=, +=, ^=

27 Increment Operators ++ (increment by 1) -- (decrement by 1) can be used before or after an expression: x++ or ++x –prefix version - in/decrements and returns changed value –postfix version - in/decrements and returns value before change –y = ++x or y = x++

28 Assigning Primitives, Instances x = 5; y = 3; x = y; // both have copies // of value 3 MyClass c1 = new MyClass(); MyClass c2 = new MyClass(); c1 = c2; // Both point at second // MyClass object created Primitive variables hold values Class variables point to objects Can lose track of object when assigning with Class vars

29 Math Class Provides constants: Math.PI, Math.E Methods (called by Math.methodname): –double sqrt(double x) - square root of x –double pow(double x, double y) - x raised to y –type abs(type x) - absolute value –type max(type x, type y) - maximum of x,y –type min(type x, type y) - minimum of x,y type for all 3 can be int, long, float, double

30 Math Class Methods –double ceil(double x) - round up to whole num –double floor(double x) - round down to whole –double rint(double x) - round to nearest whole –int round(float x) - round to nearest int –long round(double x) - round to nearest long –double exp(double x) - e of x –double log(double x) - natural log of x –double cos(double x) –double sin(double x) –double tan(double x)

31 Casting Operator (Type) object (e.g. (float) x, x is an int) Requesting a conversion Some are silly (boolean) myClassInstance Generally safe to go from a limited to more expansive type: –int -> float –class -> parent class Some casting done for you –x + 3 (if x is a float, 3 is cast to float)

32 Method Calls Form: –instanceName.methodName(args) or –className.methodName(args) - for static methods Some methods return values, some don’t (void) –illegal to use a void return value in operator expecting type

33 Other Operators x instanceof Class - returns boolean, true if x is an instance of the class boolExpr ? expr1 : expr2 - ternary expression, if boolExpr evaluates to true, return expr1, else returns expr2

34 Compound Expressions How to resolve operations with multiple operators: x + 3 * y == Math.sqrt(5) All operators have precedence, associativity: operators first evaluated in order of precedence x + 3 * y is x + (3 * y) since * has higher prec within same precedence associativity (left to right or right to left) determines 5 - 3 - 2 is (5 - 3) - 2 because of left associativity

35 Precedence () ++ -- (unary +) (unary -) ! ~ (typecast) * / % + - > >>> >= instanceof == != & ^ | && || ?: = += -= *= /= %= &= ^= |= >= >>>= Associativity left to right right to left left to right right to left

36 Expression Statements Consist of a single expression followed by a semi-colon (;) –x = y * z; –myInstance.methodCall(); –5;

37 Return Statements In a method you signal the value you have calculated with a return statement: public double mySqr(double x) { return x * x; } Type must match header type Must have a return statement (in every path)

38 Empty Statements Just a semi-colon (;) ; Need to be careful when using compound ops such as if statements

39 Conditional Statements If statement - checks condition, if true, conditional statement executed If-else statement - depending on conditions executes then or else condition Switch statement - jumps to one of many labels depending on value of switch expression

40 If Statement Form: if (booleanExpression) statement; example: if (x != 0) y = y / x; Statement evaluated if booleanExpression evaluates to true Can compose if (x != 0) if (y > 0) y = y * x;

41 Executing > 1 Statement What if you want two statements executed when condition is true: if (x != 0) y = y / x; z = z / x; doesn’t work Use blocks {} - treated as one statement if (x != 0) { y = y / x; z = z / x; } safe to always use (even if only one statement in {})

42 If-Else Statement Form: if (boolExpr) thenstmt; else elsestmt; if (x == 0) y = 0.0; else y = y / x; which statement executes depends on whether x is 0 or not If > 1 if and only one else? if (x > 0) if (y < 0) x = 0.0; else y = 0.0; // which?? Else always matches the most recent if

43 Switch Statement Form: switch (expression) { case const1a: case const1b: … some statements case const2a: case const2b:.. some statements … default: some statements }

44 Switch Selection Switch expression is evaluated Value matched to case All statements following that case are executed Cases must be constants, of same type as expression Default is used if value matches no case

45 Breaks in Switch Blocks Switch evaluates all statements after case: switch (x) { case 1: doA; default: doB; } When x is 1, doA and doB are executed, use a break to stop the switch statement

46 Breaks in Switch Blocks Adding a break: switch (x) { case 1: doA; break; default: doB; } When x is 1, doA is executed, then break ends switch


Download ppt "Chapter 5: Java Language Basics Java Statements –Declarations primitive types classes modifiers –Expressions operators –arithmetic, bitwise, comparison,"

Similar presentations


Ads by Google