Elementary Programming
EECS2030: Advanced Object Oriented Programming Fall 2018
CHEN-WEI WANG
Learning Outcomes
Learn ingredients of elementary programming:
X data types
X literal values
X constants
X variables
X operators
X expressions
X input and output
[numbers, characters, strings]
[arithmetic, relational]
Given a problem:
X First, plan how you would solve it mathematically.
X Then, Implement your solution by writing a Java program.
2 of 31
Tester vs. Controller
For effective illustrations, code examples will mostly be written in the form of a tester (i.e., a Java class with a main method).
public class MyClass {
public static void main(String[] args) {
/* Your programming solution is defined here. */
} }
The main method is treated by Java as the starting point of executing your program.
The execution starts with the first line in the main method, proceed line by line, from top to bottom, until there are no more lines to execute, then it terminates .
When developing an Android app, the controller (e.g., the
BMIActivity Java class) should look similar to the tester. 3 of 31
Compile Time vs. Run Time
These terms refer to two stages of developing your program. Compile time : when editing programs in Android Studio.
X There are two kinds of compile-time errors :
X Syntax errors: your program does not conform to Java’s grammar. ● e.g.,missingthesemicolon,curlybraces,orroundparentheses
● JavasyntaxisdefinedintheJavalanguagespecification.
X Type errors: your program manipulates data in an inconsistent way e.g., [ ì multiplication is only for numbers ]
4 of 31
is when you executing/running the Tester or app.
X Exceptions: your program crashes and terminates abnormally ● e.g.,ArithmeticException(e.g., ),
ArrayIndexOutOfBoundException, NullPointerException. X Logical errors: your program terminates normally but does not
behave as expected
e.g., calculating the BMI using a wrong formula
Run time
“York” * 23
10 / 0
Compile Time Errors vs. Run Time Errors
At the end of a computer lab test, if your submitted program:
X
Your program cannot even be run
Cannot compile
Zero!
What you should do :
Practice writing as many programs as possible.
X
Not necessarily zero, but likely low marks!
What you should do :
Truly understand the logic/rationale beyond programs.
Compiles, but run with exceptions or unexpected outputs.
5 of 31
Literals (1)
A literal is a constant value that appears directly in a program.
1. Character Literals
X A single character enclosed within a pair of single quotes X e.g., ‘a’, ‘1’, ‘*’, ‘(’, ‘ ’
X It is invalid to write an empty character: ‘’
2. String Literals
X A (possibly empty) sequence of characters enclosed within a pair
of double quotes
X e.g., ‘‘’’, ‘‘a’’, ‘‘York’’, ‘‘*#@$’’, ‘‘ ’’
3. Integer Literals
X A non-empty sequence of numerical digits X e.g., 0, -123, 123, 23943
4. Floating-Point Literals
X Specified using a combination of an integral part and a fractional
part, separated by a decimal point, or using the scientific notation X e.g., 0.3334, 12.0, 34.298, 1.23456E+2 (for 1.23456 102),
1.23456E-2 (for 1.23456 102) 6 of 31
Literals (2)
Q. Outputs of System.out.println(‘a’) versus System.out.println(‘‘a’’)? [SAME] Q. Result of comparison ‘‘a’’ == ‘a’? [TYPE ERROR]
X Literal ‘‘a’’ is a string (i.e., character sequence) that consists of a single character.
X Literal ‘a’ is a single character.
You cannot compare a character sequence with a character.
7 of 31
Escape Sequences
An escape sequence denotes a single character.
Specified as a backslash ( ) followed by a single character
X e.g., t, n, ’, “,
Does not mean literally, but means specially to Java compiler
X t means a tab
X n means a new line
X means a back slash
X ’ means a single quote X ” means a double quote
May use an escape sequence in a character or string literal:
X ‘’’
X ‘ ’’
X ‘”’
X ‘‘”’’ X ‘‘ “’’ X ‘‘’’’
[INVALID; need to escape ’] [VALID] [VALID; no need to escape “] [INVALID; need to escape “] [VALID] [VALID; no need to escape ’] [VALID]
X ‘‘ n t “’’ 8 of 31
Operations
An operation refers to the process of applying an operator to its operand (s).
1. Numerical Operations e.g., 1.1 + 0.34
e.g., 13 / 4 e.g., 13.0 / 4 e.g., 13 % 4 e.g., -45
e.g., -1 * 45
2. Relational Operations e.g.,3 <= 4
e.g.,5 < 3
e.g., 56 == 34
3. String Concatenations
[results are numbers]
[ quotient: 3 ] [ precision: 3.25 ] [ remainder: 1 ]
[results are true or false] [true] [false] [ false ]
9 of 31
[results are strings] e.g., ‘‘York’’ + ‘‘ ’’ + ‘‘University’’ is equivalent to
‘‘York University’’
Java Data Types
A (data) type denotes a set of related runtime values. 1. Integer Type
byte
short
int
long
8 bits 16 bits 32 bits 64 bits
−128,...,−1,0,1,...,27 −1] [−215, 215 − 1]
[−231, 231 − 1]
[−263, 263 − 1]
2. Floating-Point Number Type
3. Character Type
char: the set of single characters
4. String Type
String: the set of all possible character sequences
Declaring a variable v to be of type T constrains v to store only
those values defined in T. 10 of 31
float double
32 bits 64 bits
Identifiers & Naming Conventions
Identifiers are names for identifying Java elements: classes, methods, constants, and variables.
An identifier:
X Is an arbitrarily long sequence of characters: letters, digits, underscores ( ), and dollar signs ($).
X Must start with a letter, an underscore, or a dollar sign.
X Must not start with a digit.
X Cannot clash with reserved words (e.g., class, if, for, int).
Valid ids: $2, Welcome, name, name, YORK University Invalid ids: 2name, +YORK, Toronto@Canada
More conventions:
X Class names are compound words, all capitalized:
e.g., Tester, HelloWorld, TicTacToe, MagicCardGame
X Variable and method names are like class names, except 1st word is all lower cases: e.g, main, firstName, averageOfClass
X Constant names are underscore-separated upper cases:
e.g., PI, USD IN WON 11 of 31
Named Constants vs. Variables
A named constant or a variable: Is an identifier that refers to a
Must be declared with its (of stored value) before use:
placeholder
type
final double PI = 3.14159; /* a named constant */ double radius; /* an uninitialized variable */
Can only store a value that is compatible with its declared type
However, a named constant and a variable are different in that:
A named constant must be initialized, and cannot change its stored value.
A variable may change its stored value as needed.
12 of 31
Expressions (1)
An is a composition of . An expression may be:
Type Correct: for each constituent operation, types of the operands are compatible with the corresponding operator.
e.g.,(1 + 2) * (23 % 5)
e.g., ‘‘Hello ’’ + ‘‘world’’ Not Type Correct
e.g., ‘‘46’’ % ‘‘4’’
expression
e.g., (‘‘YORK ’’ + ‘‘University’’) * (46 % 4) X ‘‘YORK’’ and ‘‘University’’ are both strings
LHS of * is type correct and is of type String X 46 and 4 are both integers
RHS of % is type correct and is of type int
X Types of LHS and RHS of * are not compatible
Overall the expression (i.e., a multiplication) is not type correct 13 of 31
operations
Assignments
An assignment designates a value for a variable, or initializes a named constant.
That is, an assignment replaces the old value stored in a
placeholder with a new value.
An is done using the assignment operator (=).
An has two operands:
The left operand is called the assignment target which must be a variable name
The right operand is called the assignment source
which must be an expression whose type is compatible with the declared type of assignment target
e.g., This is a valid assignment: String name1 = ‘‘Heeyeon’’;
e.g., This is an invalid assignment:
String name1 = (1 + 2) * (23 % 5);
assignment
assignment operator
14 of 31
Multiple Executions of Same Print Statement
Executing the same print statement multiple times may or may not output different messages to the console.
e.g., Print statements involving literals or named constants only:
final double PI = 3.14; /* a named double constant */ System.out.println("Pi is " + PI); /* str. lit. and num. const. */ System.out.println("Pi is " + PI);
e.g., Print statements involving variables:
String msg = "Counter value is "; /* a string variable */ int counter = 1; /* an integer variable */ System.out.println(msg + counter);
System.out.println(msg + counter);
counter = 2; /* re-assignment changes variable’s stored value */ System.out.println(msg + counter);
15 of 31
Case Study 1: Compute the Area of a Circle
Problem: declare two variables radius and area, initialize radius as 20, compute the value of area accordingly, and print out the value of area.
public class ComputeArea {
public static void main(String[] args) {
double radius; /* Declare radius */ double area; /* Declare area */
/* Assign a radius */
radius = 20; /* assign value to radius */ /* Compute area */
area = radius * radius * 3.14159;
/* Display results */
System.out.print("The area of circle with radius "); System.out.println(radius + " is " + area);
} }
It would be more flexible if we can let the user specify the inputs
via keyboard!
16 of 31
Input and Output
Reading input from the console enables user interaction.
import java.util.Scanner;
public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
/* Create a Scanner object */
Scanner input = new Scanner(System.in);
/* Prompt the user to enter a radius */ System.out.print("Enter a number for radius: "); double radius = input.nextDouble();
/* Compute area */
final double PI = 3.14169; /* a named constant for π */ double area = PI * radius * radius; /* area = πr2 */
/* Display result */
System.out.println(
"Area for circle of radius " + radius + " is " + area); }
}
There are two equivalent ways to reading user inputs:
X Via a physical keyboard [ Tester ]
X Via a GUI component (e.g., a text view) [ Controller ] 17 of 31
Useful Methods for Scanner
nextInt() which reads an integer value from the keyboard nextDouble() which reads a double value from the keyboard nextLine() which reads a string value from the keyboard
18 of 31
Variables: Common Mistakes (1)
Mistake: The same variable is declared more than once.
int counter = 1; int counter = 2;
Fix 1: Assign the new value to the same variable.
int counter = 1; counter = 2;
Fix 2: Declare a new variable (with a different name).
int counter = 1; int counter2 = 2;
Which fix to adopt depends on what you need!
19 of 31
Variables: Common Mistakes (2) Mistake: A variable is used before it is declared.
System.out.println("Counter value is " + counter); int counter = 1;
counter = 2;
System.out.println("Counter value is " + counter);
Fix: Move a variable’s declaration before its very first usage.
int counter = 1;
System.out.println("Counter value is " + counter); counter = 2;
System.out.println("Counter value is " + counter);
Remember, Java programs are always executed, line by line, from top to bottom .
20 of 31
Case Study 2: Display Time
Problem: prompt the user for an integer value of seconds, divide that value into minutes and remaining seconds, and print the results. For example, given an input 200, output “200 seconds is 3 minutes and 20 seconds”.
import java.util.Scanner; public class DisplayTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/* Prompt the user for input */ System.out.print("Enter an integer for seconds: "); int seconds = input.nextInt();
int minutes = seconds / 60; /* minutes */
int remainingSeconds = seconds % 60; /* seconds */ System.out.print(seconds + " seconds is "); System.out.print(" minutes and "); System.out.println(remainingSeconds + " seconds");
} }
21 of 31
Assignment Sources May Come From. . .
In tar = src, the assignment source src may come from:
A literal or a variable
An expression involving literals and variables
An input from the keyboard
int i = 23; /* RHS is a literal */ int j = i; /* RHS is a variable */
int i = 23;
int j = i * 2 /* RHS is a complex expression */;
Scanner input = new Scanner(System.in);
int i = input.nextInt(); /* RHS is from a keyboard input */ int j = i * 2;
An input from some GUI component, or some method call
String textWeight = getInputOfTextField(R.id.inputWeight); double weight = Double.parseDouble(textWeight);
22 of 31
Numerical Type Conversion: Coercion
X Implicit and automatic type conversion
X Java automatically converts an integer value to a real number
when necessary (which adds a fractional part).
X However, does the following work?
● RHSevaluatesto13.5duetocoercion.
● LHSdeclaresavariableforstoringintegers(withnofractionalparts).
Not compatible [ compile-time error ] Need a way to “truncate” the fractional part!
23 of 31
double value1 = 3 * 4.5; /* 3 coerced to 3.0 */
double value2 = 7 + 2; /* result of + coerced to 9.0 */
int value1 = 3 * 4.5;
Numerical Type Conversion: Casting
X Explicit and manual type conversion
X Usage 1: To assign a real number to an integer variable, you need
to use explicit casting (which throws off the fractional part).
X Usage 2: You may also use explicit casting to force precision. ●
∵ When both operands are integers, division evaluates to quotient. ●
System.out.println( ((double) 1) / 2 ); /* 0.5 */ System.out.println( 1 / ((double) 2) ); /* 0.5 */ System.out.println( ((double) 1) / ((double) 2) ); /* 0.5 */
∵ Either or both of the integers operands are cast to double type ●
∵ Casting has higher precedence than arithmetic operation. ●
∵ Order of evaluating division is forced, via parentheses, to occur first.
int value3 = (int) 3.1415926;
System.out.println(1 / 2); /* 0 */
24 of 31
System.out.println((double) 1 / 2); /* 0.5 */
System.out.println((double) (1 / 2)); /* 0.0 */
Numerical Type Conversion: Exercise
Consider the following Java code:
1 2 3 4 5 6 7 8
double d1 = 3.1415926; System.out.println("d1 is " + d1); double d2 = d1; System.out.println("d2 is " + d2); int i1 = (int) d1; System.out.println("i1 is " + i1); d2 = i1 * 5; System.out.println("d2 is " + d2);
Write the exact output to the console.
d1 is 3.1415926
d2 is 3.1415926
i1 is 3
d2 is 15.0
25 of 31
1 2 3 4
Expressions (2.1)
Consider the following Java code, is each line type-correct? Why and Why Not?
double d1 = 23; int i1 = 23.6; String s1 = ’ ’; char c1 = " ";
L1: YES L2: NO L3: NO L4: NO
[coercion] [cast assignment source, i.e., (int) 23.6] [cannot assign char to string] [cannot assign string to char]
26 of 31
1 2 3 4 5
Expressions (2.2)
Consider the following Java code, is each line type-correct? Why and Why Not?
int i1 = (int) 23.6;
double d1 = i1 * 3;
String s1 = "La ";
String s2 = s1 + "La Land"; i1 = (s2 * d1) + (i1 + d1);
L1: YES L2: YES L3: YES L4: YES L5: NO
[proper cast] [coercion] [string literal assigned to string var.] [type-correct string concat. assigned to string var.] [string number is undefined]
27 of 31
Augmented Assignments
You very often want to increment or decrement the value of a variable by some amount.
Java supports special operators for these:
Java supports operators for incrementing or decrementing by 1:
Confusingly, these increment/decrement assignment operators can be used in assignments:
i ++; j --;
int i = 0; int j = 0; int k = 0;
k = i ++; /* k is assigned to i’s old value */ k = ++ j; /* k is assigned to j’s new value */
28 of 31
balance = balance + deposit; balance = balance - withdraw;
balance += deposit; balance -= withdraw;
Beyond this lecture. . .
Create a tester in Android Studio.
Try out the examples give in the slides.
See https://docs.oracle.com/javase/tutorial/ java/nutsandbolts/datatypes.html for more information about data types in Java.
29 of 31
Index (1)
Learning Outcomes
Tester vs. Controller
Compile Time vs. Run Time
Compile Time Errors vs. Run Time Errors Literals (1)
Literals (2)
Escape Sequence
Operations
Java Data Types
Identifiers and Naming Conventions in Java Named Constants vs. Variables Expressions (1)
Assignments
Multiple Executions of Same Print Statement
30 of 31
Index (2)
Case Study 1: Compute the Area of a Circle Input and Output
Useful Methods for Scanner
Variables: Common Mistakes (1)
Variables: Common Mistakes (2)
Case Study 2: Display Time Assignment Sources May Come From. . . Numerical Type Conversion: Coercion Numerical Type Conversion: Casting Numerical Type Conversion: Exercise Expressions (2.1)
Expressions (2.2)
Augmented Assignments
Beyond this lecture. . . 31 of 31