dennis komm programming and problem solving · java language constructs literals literals –...
TRANSCRIPT
Dennis Komm
Programming and Problem SolvingJava Language Constructs
Spring 2019 – February 20, 2019
Exercise – Age Calculator
public class AgeCalc {public static void main(String[] args) {
Out.print("Enter your year of birth: ")...
}}
Output: "In 2020, you will turn 25."
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 1 / 39
Java Language ConstructsNames and Identifiers
Names and Identifiers
A program (i.e., a class) needs a name
public class SudokuSolver { ...
Convention for class names: Use CamelCase
ï Words are combined into one word, each starting with a capital letter
Allowed names for “entities” in a program
Names begin with a letter or _ or $
Then, sequence of letters, numbers or _ or $
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 2 / 39
Names – What is Allowed?
_myName
TheCure
__AN$WE4_1S_42$__
$bling$
me@home
49ers
side-swipe
Ph.D.
strictfp ?!
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 3 / 39
Keywords
The following words are already used by Java and cannot be used as names
abstract continue for new switchassert default goto package synchronizedboolean do if private thisbreak double implements protected throwbyte else import public throwscase enum instanceof return transientcatch extends int short trychar final interface static voidclass finally long strictfp volatileconst float native super while
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 4 / 39
Java Language ConstructsVariables
Variables and Constants
Variables are buckets for a value
Have a data type and a name
The data type determines what kind of values is allowed in the variable
23
int x
42
int y
0.0f
float f
’a’
char c Declaration in Java
int x = 23, y = 42;float f;char c = ’a’;
Initialization
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 5 / 39
Constants
Keyword final
The value of the variable can be set exactly once
Example
final int maxSize = 100;
Hint
Always use final, unless the value actually needs to change over time
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 6 / 39
Java Language ConstructsTypes
Standard Types
Data Type Definition Value Range Initial Value
byte 8-bit integer −128, . . . , 127 0
short 16-bit integer −32 768, . . . , 32 767 0
int 32-bit integer −231, . . . , 231 − 1 0
long 64-bit integer −263, . . . , 263 − 1 0L
float 32-bit floating point ±1.4E−45, . . . ,±3.4E+38 0.0f
double 64-bit floating point ±4.9E−324, . . . ,±1.7E+308 0.0d
boolean logical value true, false false
char unicode-16 character ’\u0000’ ,. . . ,’a’ ,’b’ ,. . . ,’\uFFFF’ ’\u0000’
String string arbitrarily long sequence of characters null
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 7 / 39
Types and Memory Usage
Reminder: Memory cells contain 1 byte = 8 bit
byteboolean
short, char
int, float
long, double
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 8 / 39
Java Language ConstructsLiterals
Literals – Integer Numbers
Type int (or short, byte)
Example
12, value 12-3, value −3
Type long
Example
25_872_224L, value 25 872 224
Hint
Underscores between digits are allowed
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 9 / 39
Literals – Floating Point Numbers
Floating point numbers are different from integersby providing
decimal comma1.0, type double, value 1
1.27f, type float, value 1.27
and / or exponent
1e3, type double, value 1000
1.23e-7, type double, value 1.23 · 10−7
1.23e-7f, type float, value 1.23 · 10−7
1.23e-7f
integer part
fractional part
exponent
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 10 / 39
Literals – Characters and Strings
Individual characters
’a’, type char, value 97
Strings
"Hello There!", type String"a", type String
Attention
Characters and strings are two different things
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 11 / 39
Character – In ASCII Table
0–18 19–37 38–56 57–75 76–94 95–113 114–127
Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char.
0 NUL 19 DC3 38 & 57 9 76 L 95 _ 114 r1 SOH 20 DC4 39 ’ 58 : 77 M 96 ‘ 115 s2 STX 21 NAK 40 ( 59 ; 78 N 97 a 116 t3 ETX 22 SYN 41 ) 60 < 79 O 98 b 117 u4 EOT 23 ETB 42 * 61 = 80 P 99 c 118 v5 ENQ 24 CAN 43 + 62 > 81 Q 100 d 119 w6 ACK 25 EM 44 , 63 ? 82 R 101 e 120 x7 BEL 26 SUB 45 - 64 @ 83 S 102 f 121 y8 BS 27 ESC 46 . 65 A 84 T 103 g 122 z9 HT 28 FS 47 / 66 B 85 U 104 h 123 {10 LF 29 GS 48 0 67 C 86 V 105 i 124 |11 VT 30 RS 49 1 68 D 87 W 106 j 125 }12 FF 31 US 50 2 69 E 88 X 107 k 126 ~13 CR 32 SP 51 3 70 F 89 Y 108 l 127 DEL14 SO 33 ! 52 4 71 G 90 Z 109 m15 SI 34 "’ 53 5 72 H 91 [ 110 n16 DLE 35 # 54 6 73 I 92 \ 111 o17 DC1 36 $ 55 7 74 J 93 ] 112 p18 DC2 37 % 56 8 75 K 94 ˆ 113 q
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 12 / 39
Java Language ConstructsAssignments
Value Assignment
In pseudo code: x← valueIn Java: x = value
Copies a value into variable x
value value
x
(copy)
Attention
“=” is the assignment operator and not a comparison
Therefore, int y = 42 is both a declaration and an assignment
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 13 / 39
Value Assignment
Example
int a = 3;double b;
b = 3.141;
int c = a = 0;
String name = "Inf";
A nested assignment:The expression a = 0 stores the value0 into variable a and then returns thevalue
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 14 / 39
Arithmetic Binary Operators
Infix notation: x op y with op being one of the following operators
+, −, ∗, /, %
modulo
Precedence: Multiplication, division, and modulo first, then addition andsubtraction
Associativity: Evaluation from left to right
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 15 / 39
Arithmetic Binary Operators
Division x / y: Integer division if x and y are integer
Division x / y: Floating-point division if x or y is a floating-poing number
Examples (Integer division and modulo)
5 / 3 evaluates to 1 -5 / 3 evaluates to -1
5 % 3 evaluates to 2 -5 % 3 evaluates to -2
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 16 / 39
Arithmetic Assignment
x = x + y
mx += y
Analogous for -, *, /, %
Examples
x -= 3; // x = x - 3name += "x"// name = name + "x"num *= 2;// num = num * 2
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 17 / 39
Java Language ConstructsArithmetic Operators
Arithmetic Unary Operators
Prefix notation: + x or - x
Precedence: Unary operators bind stronger than binary operators
Examples
Assuming the value of x is 3
2 * -x evaluates to -6
-x - +1 evaluates to -4
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 18 / 39
Increment / Decrement Operators
Increment operators ++x and x++ have the same effect: x← x + 1But they have different return values
Prefix operator ++x returns the new valuea = ++x; ⇐⇒ x = x + 1; a = x;
Postfix operator x++ returns the old valuea = x++; ⇐⇒ temp = x; x = x + 1; a = temp;
Precedence: Increment and decrement operators bind stronger than unaryoperators
Analogous for x-- and --x
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 19 / 39
Increment/Decrement Operators
Examples
Assuming the value of x is initially set to 2
y = ++x * 3 evaluates to: x is 3 and y is 9
y = x++ * 3 evaluates to: x is 3 and y is 6
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 20 / 39
Java Language ConstructsExpressions
Expressions
represent computations
are either primary
or composed . . .
. . . from other expressions, using operators
are statically typed
Examples
Primary: “-4.1d” or “x” or "Hi"
Composed: “x + y” or “f * 2.1f”
The type of “12 * 2.1f” is float
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 21 / 39
Exercise – Celsius to Fahrenheit Calculator
Write a program that
takes an integer as input
interpretes this number as atemparatur in degree Celsius
outputs the same temperatur indegree Fahrenheit
uses the following formula
fahrenheit = 9 · celsius5 + 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 22 / 39
Celsius to Fahrenheit
public class Main {public static void main(String[] args) {
Out.print("Celsius: ");int celsius = In.readInt();float fahrenheit = 9 * celsius / 5 + 32;Out.println("Fahrenheit: " + fahrenheit);
}}
15◦ Celsius are 59◦ FahrenheitProgramming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 23 / 39
Celsius to Fahrenheit – Analysis
9 * celsius / 5 + 32
Arithmetic expression
three literals
one variable
three operator symbols
Where are the brackets in this expression?
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 24 / 39
Rule 1: Precedence
Multiplicative operators (*, /, %) have a higher precedence (“bind stronger”)than additive operators (+, -)
Example
9 * celsius / 5 + 32
means
(9 * celsius / 5) + 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 25 / 39
Rule 2: Associativity
Arithmetic operators (*, /, %, +, -) are left-associative: in case of the sameprecedence, the evaluation happens from left to right
Example
9 * celsius / 5 + 32
means
((9 * celsius) / 5) + 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 26 / 39
Rule 3: Arity
Unary operators +, - before binary operators +, -
Example
9 * celsius / + 5 + 32
means
9 * celsius / (+5) + 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 27 / 39
Bracketing
Any expression can be bracketed unambiguously using the
associativities
precedences
arities (number of operands)
of the involved operators
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 28 / 39
Expression Trees
Bracketing leads to an expression tree
(((9 * celsius) / 5) + 32)
+
/
*
9 celsius 5 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 29 / 39
Evaluation Order
“From leafs to the root” in the expression tree
9 * celsius / 5 + 32
+
/
*
9 celsius 5 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 30 / 39
Expression Trees – Notation
Usual notation: root on top
9 * celsius / 5 + 32
+
/
*
9 celsius
5
32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 31 / 39
Java Language ConstructsType System
Type System
Java features a static type system
All types must be declared
If possible, the compiler checks the typing . . .
. . . otherwise it is checked at run-time
Advantages of a static type system
Fail-Fast: Bugs in the program are often found already by the compiler
Understandable code
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 32 / 39
Type errors
Example
int pi_ish;float pi = 3.14f;
pi_ish = pi;
Compiler error./Root/Main.java:12: error: incompatible types:
possible lossy conversion from float to intpi_ish = pi;
^
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 33 / 39
Explicit Type Conversion
Example
int pi_ish;float pi = 3.14f;
pi_ish = (int) pi;
Explicit type conversion using casts (type)Statically type-correct, compiler is happyRun-time behavior: depends on the situationhere, e.g., loss of precision: 3.14 ï 3Can crash a program at run-time
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 34 / 39
Type Conversion – Visually for Integer Numbers
byte
short
int
longex
plic
itca
st
implicitconversion
Potential loss of information when casting explicitly, because less memoryavailable to represent the number
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 35 / 39
Java Language ConstructsMixed Expressions
Mixed Expressions, Conversion
Floating point numbers are more general than integers
In mixed expressions, integers are converted to floating point numbers
9 * celsius / 5 + 32
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 36 / 39
Type Conversions for Binary Operations
Numeric operands in a binary operation are converted according to the followingrules
If both operands have the same type, no conversion will happen
If one operand is double, the other operand is converted to double as well
If one operand is float, the other operand is converted to float as well
If one operand is long, the other operand is converted to long as well
Otherwise: Both operands are being converted to int
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 37 / 39
Celsius to Fahrenheit – Type Analysis
What is the type of the result?
9 * celsius / 5 + 32
int
int
int
int int int int
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 38 / 39
Celsius to Fahrenheit – Type Analysis
Better: computation and result as float
9f * celsius / 5 + 32
float
float
float
float int int int
Programming and Problem Solving – Java Language Constructs Spring 2019 Dennis Komm 39 / 39