SlideShare une entreprise Scribd logo
1  sur  22
Programming in Java
5-day workshop
Operators and
conditionals
Matt Collison
JP Morgan Chase 2021
PiJ1.2: Java Basics
Session overview
Operators
• Mathematical operators
• Assignment operators
• Relational and logic operators
Who uses Java?
• popularity TIOBE index
• Java history
Getting started with Java?
• Java download and versions
• The javac Java compiler
• A first Java program - Hello world
Operators
• Arithmetic operators (+, -, *, /, %)
double a = 7/2;
• Assignment operators (+=, -=, *=, /=, %=, ...)
x += 2; //equivalent to: x = x + 2;
• Relational operators (==, !=, >=, <=, >, <)
• if (grade != ’A’){...}
• Logical operators (||, &&)
• only on boolean expressions
• if ( (grade != ‘A’) && (year == 2019) ){...}
Operator precedence
1. Arithmetic operators – BODMAS or PEMDAS
2. Relational operators – equality testing
3. Logical operators – AND OR
4. Assignment operators
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
for full list see docs
BODMAS Operators
• The usual arithmetic operators are
available for numeric variables:
+ addition
- subtraction
* multiplication
/ division
% modulus
Math.pow() exponentiation
int a = 2*3 + 4
System.out.println(a)
>> 10
int b = a/2 -1
System.out.println(b)
>> 4
int c = (a + b)*8 – 64
System.out.println(c)
>> 48
double a = 12.0
double aCubed = Math.pow(a,3)
System.out.println(aCubed)
>> 1728.0
Incremental and decremental shorthand
• Incremental and decremental operators
• Postfix (x++, x--): The result is the value of x before incremental or
decremental.
• Prefix (++x, --x): The result is the value of x after incremental or decremental.
y=x++; //equivalent to: y=x; x=x+1;
y=++x; //equivalent to: x=x+1; y=x;
Incremental and decremental operators class
IncrementalOperators {
public static void main(String[] args) {
float x = 5.2f;
y = x++;
System.out.println("x = " + x + ", y = " + y);
int a = 10;
b = --a;
System.out.println("a = " + a + ", b = " + b);
}
}
Q: What is the output? x = 6.2, y = 5.2 a = 9, b = 9
Comparisons and Boolean operators
Comparisons - The result of a
comparison is a Boolean variable
which can have the values true or
false
• < less than
• > greater than
• == equals
• != not equal
• <= less than or equals
• >= greater than or equals
Boolean operators - Boolean variables
can be combined with Boolean
operators. In descending order of
priority:
• ! logical not
• && logical and
• || logical or
Arithmetic operators have higher
precedence than Boolean
comparisons and operators
Arithmetic operations > Boolean comparisons > Boolean operations
Order of evaluation
• Precedence: arithmetic operations are evaluated first, then Boolean
comparisons, then Boolean operations.
boolean example = 3*4 + 1 < Math.pow(4,2) -1 && 12 < 7
System.out.println(‘the answer is ‘ + example)
>>false
Conditional logic
if ( <boolean expression> ) {
block of statements;
} else if ( <boolean expression> ) {
block of statements;
} else if ( <boolean expression> ) {
block of statements;
} else {
block of statements;
}
Conditionals
• The block of statements immediately following only the first
condition that evaluates to true is executed
• No other block is executed
• else if and else clauses are optional
• The { … } are an integral part of the syntax although there are
shorthand versions
Example
• Example: Determine if an integer is an even or an odd number.
int a = 3;
if ( a%2 == 0 ) {
System.out.println( a + " is an even.” );
} else {
System.out.println( a + " is an odd.” );
}
Remember the mod
operator
Find max using for( int item : intArr ) { ... }
1. Set max to negative infinity
2. Iterate over each item in the list
1. If an item value is greater than max:
1. Set max to item value
Why might the this code fail?
// Find the maximum of int array intArr
int max = -999999999
for( int item : intArr ) {
if ( item > max ){
max = item
}
}
System.out.println( max )
Nicer max
• Why might the original
code fail?
• All the elements less
than -999999999
• The list were empty
• Where possible
program defensively
• anticipate what might
go wrong and protect
against it.
Challenge
• Write a program to decide on grades based on a percentage with the
following boundaries:
• A is 90-100%
• B is 80-89%
• C is 70-79%
• D is 60-69%
• E is 50-59%
• F under 50%
switch case syntax
switch(expression) {
case value1:
...
break; // optional
case value2:
...
break; // optional
// You can have any number of case statements.
default: // optional
...
}
switch case example
//A demo to output a comment based on the input grade.
public class SwitchApp {
public static void main(String args[]) {
char grade = ’C’;
switch(grade) {
case ’A’:
System.out.println("Excellent!");
break;
case ’B’ :
case ’C’ :
System.out.println("Well done");
break;
switch case example ctd.
case ’D’ :
System.out.println("You passed");
break;
case ’E’ :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
• Run through examples in IDE
switch case
• The expression can only be an integer (byte, short, int, long, char),
enumerated object, or String object.
• When the expression is equal to a case, the statements following that
case will execute until a break statement is reached.
• No break is needed in the default case.
• Q: In the above example, if the break-statement before the case ’D’: is
removed, what will the program output on the screen?
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java

Contenu connexe

Tendances

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 

Tendances (20)

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
White box testing
White box testingWhite box testing
White box testing
 
Variables and Data Types
Variables and Data TypesVariables and Data Types
Variables and Data Types
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 
Java 2
Java 2Java 2
Java 2
 
Comp102 lec 5.1
Comp102   lec 5.1Comp102   lec 5.1
Comp102 lec 5.1
 
Operators
OperatorsOperators
Operators
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Python ppt
Python pptPython ppt
Python ppt
 
11. java methods
11. java methods11. java methods
11. java methods
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Java method
Java methodJava method
Java method
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
Control statements
Control statementsControl statements
Control statements
 
Method of java
Method of javaMethod of java
Method of java
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 

Similaire à Pi j1.3 operators

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

Similaire à Pi j1.3 operators (20)

Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Core java
Core javaCore java
Core java
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
02basics
02basics02basics
02basics
 
05 operators
05   operators05   operators
05 operators
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java introduction
Java introductionJava introduction
Java introduction
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
Chapter3
Chapter3Chapter3
Chapter3
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise Applications
 

Plus de mcollison (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
 

Dernier

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Dernier (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

Pi j1.3 operators

  • 1. Programming in Java 5-day workshop Operators and conditionals Matt Collison JP Morgan Chase 2021 PiJ1.2: Java Basics
  • 2. Session overview Operators • Mathematical operators • Assignment operators • Relational and logic operators Who uses Java? • popularity TIOBE index • Java history Getting started with Java? • Java download and versions • The javac Java compiler • A first Java program - Hello world
  • 3. Operators • Arithmetic operators (+, -, *, /, %) double a = 7/2; • Assignment operators (+=, -=, *=, /=, %=, ...) x += 2; //equivalent to: x = x + 2; • Relational operators (==, !=, >=, <=, >, <) • if (grade != ’A’){...} • Logical operators (||, &&) • only on boolean expressions • if ( (grade != ‘A’) && (year == 2019) ){...}
  • 4. Operator precedence 1. Arithmetic operators – BODMAS or PEMDAS 2. Relational operators – equality testing 3. Logical operators – AND OR 4. Assignment operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html for full list see docs
  • 5. BODMAS Operators • The usual arithmetic operators are available for numeric variables: + addition - subtraction * multiplication / division % modulus Math.pow() exponentiation int a = 2*3 + 4 System.out.println(a) >> 10 int b = a/2 -1 System.out.println(b) >> 4 int c = (a + b)*8 – 64 System.out.println(c) >> 48 double a = 12.0 double aCubed = Math.pow(a,3) System.out.println(aCubed) >> 1728.0
  • 6. Incremental and decremental shorthand • Incremental and decremental operators • Postfix (x++, x--): The result is the value of x before incremental or decremental. • Prefix (++x, --x): The result is the value of x after incremental or decremental. y=x++; //equivalent to: y=x; x=x+1; y=++x; //equivalent to: x=x+1; y=x;
  • 7. Incremental and decremental operators class IncrementalOperators { public static void main(String[] args) { float x = 5.2f; y = x++; System.out.println("x = " + x + ", y = " + y); int a = 10; b = --a; System.out.println("a = " + a + ", b = " + b); } } Q: What is the output? x = 6.2, y = 5.2 a = 9, b = 9
  • 8. Comparisons and Boolean operators Comparisons - The result of a comparison is a Boolean variable which can have the values true or false • < less than • > greater than • == equals • != not equal • <= less than or equals • >= greater than or equals Boolean operators - Boolean variables can be combined with Boolean operators. In descending order of priority: • ! logical not • && logical and • || logical or Arithmetic operators have higher precedence than Boolean comparisons and operators Arithmetic operations > Boolean comparisons > Boolean operations
  • 9. Order of evaluation • Precedence: arithmetic operations are evaluated first, then Boolean comparisons, then Boolean operations. boolean example = 3*4 + 1 < Math.pow(4,2) -1 && 12 < 7 System.out.println(‘the answer is ‘ + example) >>false
  • 11. if ( <boolean expression> ) { block of statements; } else if ( <boolean expression> ) { block of statements; } else if ( <boolean expression> ) { block of statements; } else { block of statements; }
  • 12. Conditionals • The block of statements immediately following only the first condition that evaluates to true is executed • No other block is executed • else if and else clauses are optional • The { … } are an integral part of the syntax although there are shorthand versions
  • 13. Example • Example: Determine if an integer is an even or an odd number. int a = 3; if ( a%2 == 0 ) { System.out.println( a + " is an even.” ); } else { System.out.println( a + " is an odd.” ); } Remember the mod operator
  • 14. Find max using for( int item : intArr ) { ... } 1. Set max to negative infinity 2. Iterate over each item in the list 1. If an item value is greater than max: 1. Set max to item value Why might the this code fail? // Find the maximum of int array intArr int max = -999999999 for( int item : intArr ) { if ( item > max ){ max = item } } System.out.println( max )
  • 15. Nicer max • Why might the original code fail? • All the elements less than -999999999 • The list were empty • Where possible program defensively • anticipate what might go wrong and protect against it.
  • 16. Challenge • Write a program to decide on grades based on a percentage with the following boundaries: • A is 90-100% • B is 80-89% • C is 70-79% • D is 60-69% • E is 50-59% • F under 50%
  • 17. switch case syntax switch(expression) { case value1: ... break; // optional case value2: ... break; // optional // You can have any number of case statements. default: // optional ... }
  • 18. switch case example //A demo to output a comment based on the input grade. public class SwitchApp { public static void main(String args[]) { char grade = ’C’; switch(grade) { case ’A’: System.out.println("Excellent!"); break; case ’B’ : case ’C’ : System.out.println("Well done"); break;
  • 19. switch case example ctd. case ’D’ : System.out.println("You passed"); break; case ’E’ : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } • Run through examples in IDE
  • 20. switch case • The expression can only be an integer (byte, short, int, long, char), enumerated object, or String object. • When the expression is equal to a case, the statements following that case will execute until a break statement is reached. • No break is needed in the default case. • Q: In the above example, if the break-statement before the case ’D’: is removed, what will the program output on the screen?
  • 21. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 22. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java

Notes de l'éditeur

  1. From 1-4
  2. x = 6.2, y = 5.2 a = 9, b = 9
  3. true
  4. Well done You passed Your grade is B
  5. All resources hang from the ELE pages. How many of you have looked through them?