SlideShare a Scribd company logo
COMPSCI 121: DATA TYPES & BRANCHING
FALL 19
BYTE FROM COMPUTING HISTORY
Alan Turing, also known as the father of
modern computing was a brilliant
mathematician and logician. He
developed the idea of the modern
computer and artificial intelligence.
Read about the Turing Machine.
2
GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• New data types
• Conditional branching
• Math methods and operators
3
LET’S DO SOME REVIEW
Website Java Visualizer:
https://cscircles.cemc.uwaterloo.ca/java_visualize/
Look at Basic Examples:
4
CLICKER QUESTION #1
REVIEW COMPOUND OPERATORS
What is the value of numCalories after executing
numCalories = 7;
numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5;
D. Same as numCalories = 7 + 5;
5
CLICKER QUESTION #1 ANSWER
6
zyBooks 2.6 Shorthand way to update a variable.
E.g. userAge++ or userAge += 1 is shorthand for
userAge = userAge + 1
Others -=, *=, /=, and %=.
What is the value of numCalories after executing
numCalories = 7; numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5; incorrect
D. Same as numCalories = 7 + 5;
CLICKER # 2 REVIEW: INSTANTIATING CLASS
Select the statement below that declares a variable named myCalculator
and assigns to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator;
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;
D. myCalculator = new SalaryCalculator(); 7
CLICKER # 2 ANSWER
Select the statement below that declares a variable named myCalculator and assigns
to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator; declares but does not assigns
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;missing ()
D. myCalculator = new SalaryCalculator();missing class type 8
CLICKER QUESTION #3 REVIEW METHOD CALLS
9
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6
B. 12
C. 0
D. 18
CLICKER QUESTION #3 ANSWER
10
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6 size of cheese pizza
B. 12 correct
C. 0 incorrect answer
D. 18 incorrect answer
EXPLANATION CLICKER QUESTION #3
There are 2 constructors.
public Pizza(int size){...}
public Pizza(int size, String type){...}
11
DATA TYPES IN JAVA
• Data is represented as “types” in programming.
• In Java, a data type is defined as a primitive or a class.
• “Primitive” Data types and their values:
•Numeric: int, whole numbers, 2, 400, -99
double, fractional numbers, 7.34, 8.01,
-100.00
•Character: char, alpha-numeric symbols, ‘a’, ‘G’, ‘&’ , ‘}’, ‘9’
(notice 9 is not a number but character 9).
•Boolean: boolean, true or false (these values are
keywords). 12
RELATIONAL OPERATORS
Check conditions: Result of boolean type: true or false
13
Two sides of a
relational operator
have to be
compatible types.
Note:
==
!=
CONDITIONAL IF-ELSE
14
if (<some boolean test>)
do something;
if (<some boolean test>)
   { do a bunch of things;}
if (<some boolean test>)
   {do a bunch of things;}
else
{do a bunch of other things;}
If no curly braces, only the first line after the if statement is executed.
<
>
<=
>=
Relational operators
Boolean evaluates to
TRUE / FALSE
CONDITIONALS - STYLE 1
15
if (x > 0) {
   System.out.println("x is positive");
}
else if (x < 0) {
   System.out.println("x is negative");
}
else {
   System.out.println("x is zero");
}
What is the answer if x = -2? See Demo from Java Visualizer:
ControlFlow
16
if (x == 0) {
   System.out.println("x is zero");
}
else {
   if (x > 0) {
      System.out.println("x is positive");
   }
   else {
      System.out.println("x is negative");
   }
}
CONDITIONALS - STYLE 2
USE OF CONDITIONALS
17
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer");
int number = scan.nextInt();
if (number < 0)
   System.out.println("Number entered isn't positive");
if (number > 0)
   System.out.println(number + " is positive");
else
   System.out.println(number + " is negative or zero");
Use conditionals for
user error checks!
A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
CLICKER QUESTION #4
18
int x = 5;
if (x > 0){
   System.out.println("x is positive");
}
System.out.println("x is not zero");
What is printed?
A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
int x = 5;
if (x > 0)
   {System.out.println("x is positive")};
System.out.println("x is not zero");
CLICKER QUESTION # 4 ANSWER
19
{Scope of if statement}
20
• +, -, * behave in standard way.
• Division / is different
• In the absence of parentheses,
*, /, have higher precedence than +, -
• So: (3 + 5 * 2)is 13
(7 - 4 / 2) is 5
JAVA ARITHMETIC OPERATORS
5/3
1
5.0/3
1.6666666666666667
5/3.0
1.6666666666666667
See Demo from Java Visualizer:
CmdLineArgs
21
Modulo mod operator %
With integers:
Gives integer remainder after repeated divisions of the
number by the modulus:
number % modulus
10 % 7 is 3
21 % 7 is 0
53 % 7 is 4
JAVA ARITHMETIC OPERATORS
22
1. * / % have higher priority and performed first.
2. For same priority, operators are applied from left to
right.
3. Integer division always rounds towards zero.
4. When one or more operands are double, Java
performs “floating-point” division.
Check the Java™ Tutorials:
https://docs.oracle.com/javase/tutorial/java/nutsandb
olts/datatypes.html
KEEP IN MIND
MATH OPERATOR RULES
• Dividing by zero gives error
Exception in thread "main"
java.lang.ArithmeticException: / by zero
• int-to-double conversion is automatic but
double-to-int conversion may lose precision.
• Use type casting to convert a value of one type to another
type. e.g.
myIntVar = (int)myDoubleVar
myDoubleVar = (double)myIntVar
23
CLICKER QUESTION # 5
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
24
CLICKER QUESTION #ANSWER
NOTE:
JAVA converts from int
to double automatically
so 5.0 assigned to
num2.
25
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
MATH METHODS - EXAMPLE
https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html 26
Static method: Independent of class object
REVIEW: METHODS AND PARAMETERS
Parameters refers to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method
is invoked.
When you invoke a method, the arguments used must match the
declaration's parameters in type and order. 27
double r = Math.max(3.5, 7.1);
ArgumentsReturn
From the
Java API,
Math class
max method
summary.Parameters
MATH METHOD EXAMPLES
28
double r = Math.max(3.5, 7.1); //7.1
double s = Math.sqrt(2.0);
//1.4142135623730951
double t = Math.sin(.7); //0.644217687237691
double u = Math.min(3.5, 7.1); //3.5
double v = Math.pow(2,5); //32.0
JGRASP DEBUGGER - TRY WITH LECTURE CODE
Arithmeticx.java
29
STRATEGIES FOR DEBUGGING
1. Set a breakpoint prior to the line of code where you
think the problem occurs.
2. When the program gets to the breakpoint, inspect the
variables for correct values.
3. Correct the error and repeat till the program runs
correctly.
30
TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
31
COMPSCI 121: DATA TYPES & BRANCHING
FALL 19
GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• Review conditional statements
• The Random method
• Characters & Strings
2
REVIEW: CONDITIONAL IF STATEMENTS
First evaluate (alpha > beta):
(2 > 1) TRUE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is TRUE so we
execute the true branch:
eta = alpha + 2 = 2 + 2 = 4
gamma = alpha + 5 = 2 + 5 = 7
3
int alpha = 2, beta = 1,
delta = 3, eta = 0, gamma = 0;
Think - Pair -Share
4
int alpha = 2;
int beta = 1,
int delta = 3,
int eta = 0,
int gamma = 0;
Evaluate these
statements and
determine the value of all
variables used.
EXPLANATION
For if statement, determine whether
true or false
First we evaluate (alpha > delta):
(2 > 3) FALSE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is FALSE so we follow
the else branch.
gamma = beta + 5 = 1 + 5 = 6
Next sequential statement is always
executed:
eta = beta + 2 = 1 + 2 = 3
5
CLICKER QUESTION 1
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2; 6
Evaluate the statements and
determine the value of eta
given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa
= 3.0;
A. 2
B. 3
C. 4
D. 5
CLICKER QUESTION 1 ANSWER
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2;
7
Evaluate the statements and
determine the value of eta given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa =
3.0;
A. 2
B. 3
C. 4
D. 5
FALSE
TRUE
To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns a random
number
8
call nextInt()
method
Import statement
New instance
To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns 10 possible values from 0 to 9 9
10
OTHER USES OF nextInt METHOD
Generates any 6 values starting at 10.
11
OTHER USES OF nextInt METHOD
With a specific seed, each program run will yield the same
sequence of pseudo-random numbers.
Set the seed
declare int variable
CLICKER QUESTION #2
Which of the following will work like flipping a coin
and getting us 0 and 1 (heads/tail)?
A. randGen.nextInt(0);
B. randGen.nextInt(1);
C. randGen.nextInt(2);
D. randGen.nextInt(3);
12
CLICKER QUESTION #2 ANSWER
Which of the following will work like flipping a coin?
A. randGen.nextInt(0);
Error: bound must be positive
B. randGen.nextInt(1);
Gives 0;
C. randGen.nextInt(2);
Gives 0/1 (heads/tails)
D. randGen.nextInt(3);
Gives 0, 1, or 2 13
CHARACTER DATA TYPE
14
String References 1INTRODUCTION TO REFERENCES
String greeting = new
String("hi");
String greeting2 = new
String("hello");
greeting = greeting2;
“hi"
:String
greeting
“hello"
:String
greeting2
greeting
:String
“hello"
:String
greeting2
15
REFERENCES WITH STRING LITERALS
String greeting = "bonjour";
String greeting2 = "bonjour";
“bonjour"
:String
greeting greeting2
16
IDENTITY vs EQUALITY (STRINGS)
== tests identity
input1==input2
false!
== is not true here (different objects)
"bye"
:String
"bye"
:String
input1
== ?
input2
String input1 = new String(”bye");
String input2 = new String(”bye");
17
IDENTITY VS EQUALITY (STRINGS)
equals tests equalityinput1.equals(input2)
TRUE!
Only use "==" to test if whole numbers or characters
are equal. For String use the method equals
"bye"
:String
input1
"bye"
:String
equals ?
input2
18
EQUALITY OPERATORS: SUMMARY
Checks whether two operands' values are the same
(==) or different (!=).
Evaluates to a Boolean value: TRUE or FALSE.
Also useful for checking expressions e.g.
19
CLICKER QUESTION #3
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
20
CLICKER QUESTION #3 ANSWER
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
Evaluate:
name1.equals(
name2)
Ans: TRUE
21
Scanner console = new Scanner(System.in);
Scanner object means: input from keyboard
console.nextInt()--- looking for int value
console.nextDouble()--- looking for double value
console.next() --- looking for String value
console.nextLine() --- looking for a whole line
https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html
REVIEW: SCANNER CLASS METHODS
22
CLICKER QUESTION #4
A. String phrase = sc.nextInt();
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase;
D. String phrase = sc.nextLine;
E. String phrase = sc.nextString();
Scanner sc = new Scanner(System.in);    
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
23
CLICKER QUESTION #4ANSWER
A. String phrase = sc.nextInt(); For ints
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase; No such method
D. String phrase = sc.nextLine; Missing ()
E. String phrase = sc.nextString(); No such
method
Scanner sc = new Scanner(System.in);    
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
24
TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
• Read ALL the exam instructions sent to
you.
25

More Related Content

PPT
Control statements in java programmng
PPT
04 control structures 1
PPTX
control statements of clangauge (ii unit)
PPTX
Operators in java
PPT
Control structure C++
PPTX
Chapter 5:Understanding Variable Scope and Class Construction
PPT
Control structures i
PDF
Dsp lab _eec-652__vi_sem_18012013
Control statements in java programmng
04 control structures 1
control statements of clangauge (ii unit)
Operators in java
Control structure C++
Chapter 5:Understanding Variable Scope and Class Construction
Control structures i
Dsp lab _eec-652__vi_sem_18012013

What's hot (20)

PPT
03a control structures
PPTX
07 flow control
PPT
Control structures ii
PPT
Control Structures: Part 1
PPT
Selection Control Structures
PPT
Control statments in c
PPTX
Java chapter 3
PPT
Control Structures
PPTX
operators and control statements in c language
PPT
Loops in matlab
PPTX
JavaScript Proven Practises
PPT
Control structure
PPTX
Java chapter 2
PPTX
Matlab Script - Loop Control
PPTX
Java if else condition - powerpoint persentation
PPT
Types of c operators ppt
PDF
Controls & Loops in C
PPTX
Control statements in c
03a control structures
07 flow control
Control structures ii
Control Structures: Part 1
Selection Control Structures
Control statments in c
Java chapter 3
Control Structures
operators and control statements in c language
Loops in matlab
JavaScript Proven Practises
Control structure
Java chapter 2
Matlab Script - Loop Control
Java if else condition - powerpoint persentation
Types of c operators ppt
Controls & Loops in C
Control statements in c
Ad

Similar to Week 4 (20)

PDF
Programming in Java: Control Flow
PPT
00_Introduction to Java.ppt
PDF
Chap 5 c++
PDF
[C++][a] tutorial 2
PPTX
Matlab Functions for programming fundamentals
PPT
Python Control structures
PPT
Java Tutorial | My Heart
ODP
Synapseindia reviews.odp.
PPT
Java Programmin: Selections
PPT
Lect 3-4 Zaheer Abbas
PPT
Java teaching ppt for the freshers in colleeg.ppt
PPT
Java_Tutorial_Introduction_to_Core_java.ppt
PPT
Java Tutorial
PPT
Javatut1
PPT
Java tut1 Coderdojo Cahersiveen
PPT
Java tut1
PPT
Java tut1
PPTX
Pi j1.3 operators
PPSX
Algorithms, Structure Charts, Corrective and adaptive.ppsx
Programming in Java: Control Flow
00_Introduction to Java.ppt
Chap 5 c++
[C++][a] tutorial 2
Matlab Functions for programming fundamentals
Python Control structures
Java Tutorial | My Heart
Synapseindia reviews.odp.
Java Programmin: Selections
Lect 3-4 Zaheer Abbas
Java teaching ppt for the freshers in colleeg.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Java Tutorial
Javatut1
Java tut1 Coderdojo Cahersiveen
Java tut1
Java tut1
Pi j1.3 operators
Algorithms, Structure Charts, Corrective and adaptive.ppsx
Ad

More from EasyStudy3 (20)

PDF
Week 7
PDF
Chapter 3
PDF
Week 6
PDF
2. polynomial interpolation
PDF
Chapter2 slides-part 2-harish complete
PDF
PDF
Chapter 5
PDF
Lec#4
PDF
Chapter 12 vectors and the geometry of space merged
PDF
Week 5
PDF
Chpater 6
PDF
Chapter 5
PDF
Lec#3
PDF
Chapter 16 2
PDF
Chapter 5 gen chem
PDF
Topic 4 gen chem guobi
PDF
Gen chem topic 3 guobi
PDF
Chapter 2
PDF
Gen chem topic 1 guobi
Week 7
Chapter 3
Week 6
2. polynomial interpolation
Chapter2 slides-part 2-harish complete
Chapter 5
Lec#4
Chapter 12 vectors and the geometry of space merged
Week 5
Chpater 6
Chapter 5
Lec#3
Chapter 16 2
Chapter 5 gen chem
Topic 4 gen chem guobi
Gen chem topic 3 guobi
Chapter 2
Gen chem topic 1 guobi

Recently uploaded (20)

PDF
Sports Quiz easy sports quiz sports quiz
PDF
Classroom Observation Tools for Teachers
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Lesson notes of climatology university.
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
GDM (1) (1).pptx small presentation for students
Sports Quiz easy sports quiz sports quiz
Classroom Observation Tools for Teachers
Pharmacology of Heart Failure /Pharmacotherapy of CHF
TR - Agricultural Crops Production NC III.pdf
Microbial diseases, their pathogenesis and prophylaxis
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Insiders guide to clinical Medicine.pdf
Institutional Correction lecture only . . .
Module 4: Burden of Disease Tutorial Slides S2 2025
Lesson notes of climatology university.
102 student loan defaulters named and shamed – Is someone you know on the list?
Anesthesia in Laparoscopic Surgery in India
Renaissance Architecture: A Journey from Faith to Humanism
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Final Presentation General Medicine 03-08-2024.pptx
GDM (1) (1).pptx small presentation for students

Week 4

  • 1. COMPSCI 121: DATA TYPES & BRANCHING FALL 19
  • 2. BYTE FROM COMPUTING HISTORY Alan Turing, also known as the father of modern computing was a brilliant mathematician and logician. He developed the idea of the modern computer and artificial intelligence. Read about the Turing Machine. 2
  • 3. GOALS FOR TODAY’S CLASS You are now familiar with Objects and Classes and writing programs to solve a problem. We now work with the “building blocks” or syntax of the Java programming language: • New data types • Conditional branching • Math methods and operators 3
  • 4. LET’S DO SOME REVIEW Website Java Visualizer: https://cscircles.cemc.uwaterloo.ca/java_visualize/ Look at Basic Examples: 4
  • 5. CLICKER QUESTION #1 REVIEW COMPOUND OPERATORS What is the value of numCalories after executing numCalories = 7; numCalories += 5; Select the incorrect answer A. Same as numCalories = numCalories + 5; B. Same as numCalories = 12; C. Same as numCalories = 5; D. Same as numCalories = 7 + 5; 5
  • 6. CLICKER QUESTION #1 ANSWER 6 zyBooks 2.6 Shorthand way to update a variable. E.g. userAge++ or userAge += 1 is shorthand for userAge = userAge + 1 Others -=, *=, /=, and %=. What is the value of numCalories after executing numCalories = 7; numCalories += 5; Select the incorrect answer A. Same as numCalories = numCalories + 5; B. Same as numCalories = 12; C. Same as numCalories = 5; incorrect D. Same as numCalories = 7 + 5;
  • 7. CLICKER # 2 REVIEW: INSTANTIATING CLASS Select the statement below that declares a variable named myCalculator and assigns to it a new object of type SalaryCalculator. A. SalaryCalculator myCalculator; B. SalaryCalculator myCalculator = new SalaryCalculator(); C. SalaryCalculator = new SalaryCalculator; D. myCalculator = new SalaryCalculator(); 7
  • 8. CLICKER # 2 ANSWER Select the statement below that declares a variable named myCalculator and assigns to it a new object of type SalaryCalculator. A. SalaryCalculator myCalculator; declares but does not assigns B. SalaryCalculator myCalculator = new SalaryCalculator(); C. SalaryCalculator = new SalaryCalculator;missing () D. myCalculator = new SalaryCalculator();missing class type 8
  • 9. CLICKER QUESTION #3 REVIEW METHOD CALLS 9 If the program prints 6 when line 6 is executed, what would the following statement print? System.out.println(yourTopping.getSize()); A. 6 B. 12 C. 0 D. 18
  • 10. CLICKER QUESTION #3 ANSWER 10 If the program prints 6 when line 6 is executed, what would the following statement print? System.out.println(yourTopping.getSize()); A. 6 size of cheese pizza B. 12 correct C. 0 incorrect answer D. 18 incorrect answer
  • 11. EXPLANATION CLICKER QUESTION #3 There are 2 constructors. public Pizza(int size){...} public Pizza(int size, String type){...} 11
  • 12. DATA TYPES IN JAVA • Data is represented as “types” in programming. • In Java, a data type is defined as a primitive or a class. • “Primitive” Data types and their values: •Numeric: int, whole numbers, 2, 400, -99 double, fractional numbers, 7.34, 8.01, -100.00 •Character: char, alpha-numeric symbols, ‘a’, ‘G’, ‘&’ , ‘}’, ‘9’ (notice 9 is not a number but character 9). •Boolean: boolean, true or false (these values are keywords). 12
  • 13. RELATIONAL OPERATORS Check conditions: Result of boolean type: true or false 13 Two sides of a relational operator have to be compatible types. Note: == !=
  • 14. CONDITIONAL IF-ELSE 14 if (<some boolean test>) do something; if (<some boolean test>)    { do a bunch of things;} if (<some boolean test>)    {do a bunch of things;} else {do a bunch of other things;} If no curly braces, only the first line after the if statement is executed. < > <= >= Relational operators Boolean evaluates to TRUE / FALSE
  • 15. CONDITIONALS - STYLE 1 15 if (x > 0) {    System.out.println("x is positive"); } else if (x < 0) {    System.out.println("x is negative"); } else {    System.out.println("x is zero"); } What is the answer if x = -2? See Demo from Java Visualizer: ControlFlow
  • 16. 16 if (x == 0) {    System.out.println("x is zero"); } else {    if (x > 0) {       System.out.println("x is positive");    }    else {       System.out.println("x is negative");    } } CONDITIONALS - STYLE 2
  • 17. USE OF CONDITIONALS 17 Scanner scan = new Scanner(System.in); System.out.println("Enter a positive integer"); int number = scan.nextInt(); if (number < 0)    System.out.println("Number entered isn't positive"); if (number > 0)    System.out.println(number + " is positive"); else    System.out.println(number + " is negative or zero"); Use conditionals for user error checks!
  • 18. A. x is positive B. x is not zero C. x is positive x is not zero D. Error CLICKER QUESTION #4 18 int x = 5; if (x > 0){    System.out.println("x is positive"); } System.out.println("x is not zero"); What is printed?
  • 19. A. x is positive B. x is not zero C. x is positive x is not zero D. Error int x = 5; if (x > 0)    {System.out.println("x is positive")}; System.out.println("x is not zero"); CLICKER QUESTION # 4 ANSWER 19 {Scope of if statement}
  • 20. 20 • +, -, * behave in standard way. • Division / is different • In the absence of parentheses, *, /, have higher precedence than +, - • So: (3 + 5 * 2)is 13 (7 - 4 / 2) is 5 JAVA ARITHMETIC OPERATORS 5/3 1 5.0/3 1.6666666666666667 5/3.0 1.6666666666666667 See Demo from Java Visualizer: CmdLineArgs
  • 21. 21 Modulo mod operator % With integers: Gives integer remainder after repeated divisions of the number by the modulus: number % modulus 10 % 7 is 3 21 % 7 is 0 53 % 7 is 4 JAVA ARITHMETIC OPERATORS
  • 22. 22 1. * / % have higher priority and performed first. 2. For same priority, operators are applied from left to right. 3. Integer division always rounds towards zero. 4. When one or more operands are double, Java performs “floating-point” division. Check the Java™ Tutorials: https://docs.oracle.com/javase/tutorial/java/nutsandb olts/datatypes.html KEEP IN MIND
  • 23. MATH OPERATOR RULES • Dividing by zero gives error Exception in thread "main" java.lang.ArithmeticException: / by zero • int-to-double conversion is automatic but double-to-int conversion may lose precision. • Use type casting to convert a value of one type to another type. e.g. myIntVar = (int)myDoubleVar myDoubleVar = (double)myIntVar 23
  • 24. CLICKER QUESTION # 5 int num1 = 5.1; double num2 = 5; What are the values? A. num1 has value 5.1; num2 has value 5 B. num1 has value 5; num2 has value 5.0 C. num1 has value 5; num2 has value 5 D. Error: incompatible types 24
  • 25. CLICKER QUESTION #ANSWER NOTE: JAVA converts from int to double automatically so 5.0 assigned to num2. 25 int num1 = 5.1; double num2 = 5; What are the values? A. num1 has value 5.1; num2 has value 5 B. num1 has value 5; num2 has value 5.0 C. num1 has value 5; num2 has value 5 D. Error: incompatible types
  • 26. MATH METHODS - EXAMPLE https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html 26 Static method: Independent of class object
  • 27. REVIEW: METHODS AND PARAMETERS Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order. 27 double r = Math.max(3.5, 7.1); ArgumentsReturn From the Java API, Math class max method summary.Parameters
  • 28. MATH METHOD EXAMPLES 28 double r = Math.max(3.5, 7.1); //7.1 double s = Math.sqrt(2.0); //1.4142135623730951 double t = Math.sin(.7); //0.644217687237691 double u = Math.min(3.5, 7.1); //3.5 double v = Math.pow(2,5); //32.0
  • 29. JGRASP DEBUGGER - TRY WITH LECTURE CODE Arithmeticx.java 29
  • 30. STRATEGIES FOR DEBUGGING 1. Set a breakpoint prior to the line of code where you think the problem occurs. 2. When the program gets to the breakpoint, inspect the variables for correct values. 3. Correct the error and repeat till the program runs correctly. 30
  • 31. TO-DO • Check your iClicker grades in Moodle. • Study zyBook chapter 1-3 (content for exam) • Communicate with us using only Moodle forum or Piazza. • Start Project 2 early - seek help in office hours. • Start zyBooks chapter 4 exercises. 31
  • 32. COMPSCI 121: DATA TYPES & BRANCHING FALL 19
  • 33. GOALS FOR TODAY’S CLASS You are now familiar with Objects and Classes and writing programs to solve a problem. We now work with the “building blocks” or syntax of the Java programming language: • Review conditional statements • The Random method • Characters & Strings 2
  • 34. REVIEW: CONDITIONAL IF STATEMENTS First evaluate (alpha > beta): (2 > 1) TRUE If true – follow true branch, if false – do nothing or follow else branch The condition is TRUE so we execute the true branch: eta = alpha + 2 = 2 + 2 = 4 gamma = alpha + 5 = 2 + 5 = 7 3 int alpha = 2, beta = 1, delta = 3, eta = 0, gamma = 0;
  • 35. Think - Pair -Share 4 int alpha = 2; int beta = 1, int delta = 3, int eta = 0, int gamma = 0; Evaluate these statements and determine the value of all variables used.
  • 36. EXPLANATION For if statement, determine whether true or false First we evaluate (alpha > delta): (2 > 3) FALSE If true – follow true branch, if false – do nothing or follow else branch The condition is FALSE so we follow the else branch. gamma = beta + 5 = 1 + 5 = 6 Next sequential statement is always executed: eta = beta + 2 = 1 + 2 = 3 5
  • 37. CLICKER QUESTION 1 if (omega > kappa) { if (alpha > delta) eta = 5; else eta = 4; } else if (alpha < delta) eta = 3; else eta = 2; 6 Evaluate the statements and determine the value of eta given: int alpha = 2, delta = 3, eta = 0; double omega = 2.5, kappa = 3.0; A. 2 B. 3 C. 4 D. 5
  • 38. CLICKER QUESTION 1 ANSWER if (omega > kappa) { if (alpha > delta) eta = 5; else eta = 4; } else if (alpha < delta) eta = 3; else eta = 2; 7 Evaluate the statements and determine the value of eta given: int alpha = 2, delta = 3, eta = 0; double omega = 2.5, kappa = 3.0; A. 2 B. 3 C. 4 D. 5 FALSE TRUE
  • 39. To generate random numbers- e.g., to simulate real-world situation, gaming, etc. see DiceRoll.java THE RANDOM CLASS Returns a random number 8 call nextInt() method Import statement New instance
  • 40. To generate random numbers- e.g., to simulate real-world situation, gaming, etc. see DiceRoll.java THE RANDOM CLASS Returns 10 possible values from 0 to 9 9
  • 41. 10 OTHER USES OF nextInt METHOD Generates any 6 values starting at 10.
  • 42. 11 OTHER USES OF nextInt METHOD With a specific seed, each program run will yield the same sequence of pseudo-random numbers. Set the seed declare int variable
  • 43. CLICKER QUESTION #2 Which of the following will work like flipping a coin and getting us 0 and 1 (heads/tail)? A. randGen.nextInt(0); B. randGen.nextInt(1); C. randGen.nextInt(2); D. randGen.nextInt(3); 12
  • 44. CLICKER QUESTION #2 ANSWER Which of the following will work like flipping a coin? A. randGen.nextInt(0); Error: bound must be positive B. randGen.nextInt(1); Gives 0; C. randGen.nextInt(2); Gives 0/1 (heads/tails) D. randGen.nextInt(3); Gives 0, 1, or 2 13
  • 46. String References 1INTRODUCTION TO REFERENCES String greeting = new String("hi"); String greeting2 = new String("hello"); greeting = greeting2; “hi" :String greeting “hello" :String greeting2 greeting :String “hello" :String greeting2 15
  • 47. REFERENCES WITH STRING LITERALS String greeting = "bonjour"; String greeting2 = "bonjour"; “bonjour" :String greeting greeting2 16
  • 48. IDENTITY vs EQUALITY (STRINGS) == tests identity input1==input2 false! == is not true here (different objects) "bye" :String "bye" :String input1 == ? input2 String input1 = new String(”bye"); String input2 = new String(”bye"); 17
  • 49. IDENTITY VS EQUALITY (STRINGS) equals tests equalityinput1.equals(input2) TRUE! Only use "==" to test if whole numbers or characters are equal. For String use the method equals "bye" :String input1 "bye" :String equals ? input2 18
  • 50. EQUALITY OPERATORS: SUMMARY Checks whether two operands' values are the same (==) or different (!=). Evaluates to a Boolean value: TRUE or FALSE. Also useful for checking expressions e.g. 19
  • 51. CLICKER QUESTION #3 String name1 = "Grace Hopper"; String name2 = new String("Grace Hopper"); Evaluate: name1 == name2 A. True B. False C. Maybe D. Don’t know 20
  • 52. CLICKER QUESTION #3 ANSWER String name1 = "Grace Hopper"; String name2 = new String("Grace Hopper"); Evaluate: name1 == name2 A. True B. False C. Maybe D. Don’t know Evaluate: name1.equals( name2) Ans: TRUE 21
  • 53. Scanner console = new Scanner(System.in); Scanner object means: input from keyboard console.nextInt()--- looking for int value console.nextDouble()--- looking for double value console.next() --- looking for String value console.nextLine() --- looking for a whole line https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html REVIEW: SCANNER CLASS METHODS 22
  • 54. CLICKER QUESTION #4 A. String phrase = sc.nextInt(); B. String phrase = sc.nextLine(); C. String phrase = sc.nextPhrase; D. String phrase = sc.nextLine; E. String phrase = sc.nextString(); Scanner sc = new Scanner(System.in);     System.out.println(”Enter first phrase"); Which choice retrieves all that is typed? 23
  • 55. CLICKER QUESTION #4ANSWER A. String phrase = sc.nextInt(); For ints B. String phrase = sc.nextLine(); C. String phrase = sc.nextPhrase; No such method D. String phrase = sc.nextLine; Missing () E. String phrase = sc.nextString(); No such method Scanner sc = new Scanner(System.in);     System.out.println(”Enter first phrase"); Which choice retrieves all that is typed? 24
  • 56. TO-DO • Check your iClicker grades in Moodle. • Study zyBook chapter 1-3 (content for exam) • Communicate with us using only Moodle forum or Piazza. • Start Project 2 early - seek help in office hours. • Start zyBooks chapter 4 exercises. • Read ALL the exam instructions sent to you. 25