Title: Chapter%205:%20Java%20Language%20Basics
1Chapter 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
2Java 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
3Java Statements
- Declarations - of variables
- Expression statements
- includes method calls
- Return statements
- Empty statements
- Group (compound) statements - more later
- All statements end with semi-colon()
4Declarations
- 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
5Declaration 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
6Primitive Type Values
- Differ from classes, have possible values, dont
need to instantiate - Primitives have lots or preestablished values
- Primitives dont allow the creation of new values
- Example integer 1, dont need to create an
instance with value 1, 1 translates to 1
7Primitive 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
8Whole Numbers
- value format - digit digit
- L at end for long constants
- examples 5, 3, -30, 0005, 5000L
- representation twos complement
- can use bitwise ops to extract parts of number
9Twos Complement
- positive number 0 (sign) binarynum
- ex. 0 0100101 37 (25 22 20)
- negative numbers
- take binarynum for magnitude (37 0100101)
- invert (change 1s to 0s) (1011010)
- add 1 (1011011)
- add leading 1 for sign
- -37 (11011011)
10Floating-Point Numbers
- Constant values
- optional sign (-) plus
- digitstring, digitstring ., . digitString, or
digitString . digitString plus - optional exponent e intString
- examples 3, 3.0, .4e20, 3.4e-097
- add f at end for float constants
- representation sign (1 bit) magnitude
exponent
11Characters
- Constant values between single quotes ()
- Special values
- \b - backspace
- \n - linefeed
- \r - carriage return
- \t - tab char
- \ - quote
- \\ - backslash
- \ - double quote
12Logical (boolean) values
- constant values true, false
- no other values
13Instance 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)
14Static
- 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)
15Final
- 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
16Access 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
17Object-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)
18Making 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.
19Scope
- 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
20Scope 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?
-
21Expressions
- 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)
22Arithmetic 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 -gt whole, float-gt
float) - - mod or remainder (e.g. 5 3 is 2)
- whole nums only
23Bitwise Operators
- Apply to integrals (whole numbers, chars)
- Assume x10001000, y11000111
- - ones complement (flip bits) (x is 01110111)
- - and (x y is 10000000)
- - or (x y is 11001111)
- - xor (x y is 01001111)
- ltlt - left shift, pad with 0 (x ltlt 5 is 00000000)
- gtgt - right shift, pad leftmost (x gtgt 5 11111100)
- gtgtgt - right shift, pad 0 (x gtgtgt 5 is 00000100)
24Comparison 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
- lt - less than or equal (x lt 5 is true)
- gt - greater than or equal (x gt 5 is true)
- lt - less than (x lt 5 is false)
- gt - greater than (x gt 5 is false)
25Logical 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
26Assignment 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 -, , /, , ltlt, gtgt, gtgtgt, , ,
27Increment 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
28Assigning Primitives, Instances
Primitive variables hold values Class variables
point to objects Can lose track of object when
assigning with Class vars
- MyClass c1 new MyClass()
- MyClass c2 new MyClass()
- c1 c2 // Both point at second
- // MyClass object created
- x 5
- y 3
- x y // both have copies
- // of value 3
29Math 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
30Math 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)
31Casting 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 -gt float
- class -gt parent class
- Some casting done for you
- x 3 (if x is a float, 3 is cast to float)
32Method Calls
- Form
- instanceName.methodName(args) or
- className.methodName(args) - for static methods
- Some methods return values, some dont (void)
- illegal to use a void return value in operator
expecting type
33Other 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
34Compound 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
35Precedence () -- (unary ) (unary -) !
(typecast) / - ltlt gtgt gtgtgt lt lt gt gt
instanceof ! ? - /
ltlt gtgt gtgtgt
Associativity left to right right to left left to
right left to right left to right left to
right left to right left to right left to
right left to right left to right left to
right right to left right to left
36Expression Statements
- Consist of a single expression followed by a
semi-colon () - x y z
- myInstance.methodCall()
- 5
37Return 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)
38Empty Statements
- Just a semi-colon ()
-
- Need to be careful when using compound ops such
as if statements
39Conditional 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
40If 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 gt 0)
- y y x
41Executing gt 1 Statement
- What if you want two statements executed when
condition is true - if (x ! 0)
- y y / x
- z z / x
- doesnt 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
)
42If-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 gt 1 if and only one else?
- if (x gt 0)
- if (y lt 0)
- x 0.0
- else y 0.0 // which??
- Else always matches the most recent if
43Switch Statement
- Form
- switch (expression)
- case const1a case const1b
- some statements
- case const2a case const2b ..
- some statements
-
- default
- some statements
44Switch 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
45Breaks 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
46Breaks 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