Download presentation
Presentation is loading. Please wait.
1
Java LESSON 2 Operators & Conditionals
2
New stuff now…….. Last Lecture: How To…. declare chars
char aCharOfMine; char anotherChar= 'x'; read a char from the keyboard declaring a String aCharOfMine = UserInput.readChar(); read a String from the keyboard String myString; String yourString = "Hello World"; myString = UserInput.readString(); declaring constants with variables static final int FREEZING = 36; static final float CONV_FACTOR = 2.5f; New stuff now……..
3
Operators Operators come in different 'flavours':
arithmetic * / % ( ) incremental comparison < > == != >= <= logical && || !
4
( ) % * ARITHMETIC OPERATORS
5
Using Arithmetic Operators
Arithmetic operators are used as we know it from maths at school. Only difference: there may be variables or constants in the equation, too: What gets printed ? int a=5, b=6, c; static final int TAX = 20; c = a * b TAX; System.out.println("c is: " +c); 20
6
Operator Precedence The usual rules for "what gets calculated first" apply: 1. first everything in braces ( ) 2. then * and / and % 3. finally + and - int a=5, b=6, c; static final int TAX = 20; Therefore: c = a * b TAX; is different from: c = a * (b TAX); -20 = 5 * ( – 20 ) 20 = 5 * – 20
7
Quick Reminder When you see an assignment operator in a line:
the things on the right of the = calculated first c = a * b TAX; … and then copied into the variable to the left destination source
8
INCRIMENTAL OPERATORS
-- ++ INCRIMENTAL OPERATORS -- ++
9
Increment Operator Programmers are lazy.
In order to add 1 to an int you could write: int myIntegerVariable = 100; // declare and initialise myIntegerVariable = myIntegerVariable + 1; // add one The second line can be written in "shorthand": ++ myIntegerVariable; OR myIntegerVariable ++;
10
NO! -- myIntegerVariable; myIntegerVariable --; Decrement Operator
Similarly in order to subtract 1 you could write myIntegerVariable = myIntegerVariable - 1; -- myIntegerVariable; myIntegerVariable --; Could you subtract 2 by writing -- -- myIntegerVariable or myIntegerVariable -- --? NO!
11
Example int x = 5; // declare and initialise
System.out.println("x is " +x); // prints: x is 5 -- x; // decrement System.out.println("x is now " +x); // prints: x is now 4 ++ x; // increment System.out.println("x back to " +x); // x back to 5
12
Inc/Dec Compatible Data Types
Originally Java only allowed incrementing and decrementing of int variables. Java now allows the following data types to work with the ++ and -- operators. byte short int long Whole Numbers float double Decimal Numbers char String boolean Others Strings and booleans cannot be incremented
13
Inc / Decrementing Decimal Variables
The code is the same as with ints and the behaviour is similar.. double height =2.5; ++ height; System.out.println ( height ); float inches =3.21f; -- inches; 3.5 2.21
14
Inc / Decrementing a Char
The code is the same as with ints and the but the behaviour is very different.. char letter = ‘a’; char letter2 = ‘Z’; ++ letter; System.out.println ( letter); -- letter2; System.out.println ( letter2 ); b Y
15
Inc/ Decrimenting By More Than One
It is possible to increment by more than one by using += or -= operators. x = x + 2 X += 2
16
Inc/ Decrimenting By More Than One
It is possible to increment by more than one by using += or -= operators. x = x - 2 X -= 2
17
Examples int x = 5; x += 5; System.out.println("x is " +x);
double y = 2.2; x += 0.8; System.out.println(“y is " + y); double z = 0.5; z -= 2.0; System.out.println(“z is " +z); x is 10 y is 3.0 z is -1.5
18
More Examples char y = ‘a’; x += 2; System.out.println(“y is " + y);
int z = 1; int a = 5; z += a; System.out.println(“z is " +z); y is c z is 6
19
Check your knowledge now:
Spot the mistakes in the code: static final float tax = 0.78f; float income = £50.00; float netIncome; netIncome = income * TAX; ++ ++netIncome; TAX should be uppercase should be just 50.0 correct Can’t use two inc operators
20
Conditional Operators
arithmetic * / % ( ) incremental comparison < > == != >= <= logical && || !
21
Conditions Happen in our day to day lives They are logical arguments
Have true or false answers If your age is 17 or older then You can drive a car. If your licence points are more than 12 then You cannot drive a car. If thirsty then Take a drink
22
Conditions If age 18 or older then Allow night club entry.
23
Conditions If age 18 or older then { Allow night club entry.
If thirsty get a drink } Allow Nightclub Entry Thirsty? Get a drink
24
Three Steps to Conditional Heaven
Step 1: Comparison Operators (<, >, etc) Step 2: Logical Operators ( &&, ||, ! ) Step 3: 'if' statement structure
25
An expression with these operators is called a boolean expression
Comparison Operators An expression with these operators is called a boolean expression List of 6 operators: > greater than < smaller than >= greater or equal than <= smaller or equal than == equal to != not equal to 25
26
Comparison Operators cont..
Examples: int a = 5, b = 10, c = 5; Code English a > b a greater than b a < b a less than b a >= b a greater or equal to b a <= b a less or equal to b a == c a equal to c a != b a not equal to b False True False True True True
27
Comparison Operators Example (using an int named age):
Used in decisions and loops Compares two expressions Outcome is either true or false Example (using an int named age): if ( age >= 18 ) { System.out.println(“Welcome to the club“); } Age >= 18 “Welcome to the club”
28
Notes on '==' If ( x == 3.0 ) could be false!
Try to avoid using == on decimal variables ? a conditional expression That's an assignment, remember ? Notes on '==' It is a double '==' e.g. if (x == 10) Don't confuse with single '=' e.g. x=10; The trouble with using '==' on floats : The float x=3.0 may internally be stored as or , therefore the outcome of If ( x == 3.0 ) could be false!
29
Three Steps to Conditional Heaven
Step 1: Comparison Operators Step 2: Logical Operators ( &&, ||, ! ) Step 3: 'if' statement structure
30
Logical Operators With comparison operators alone we can say:
" if a is greater than b, then do …." But how can we say: " if a is greater than b AND c is greater than d, then do …. " Here is how : if ( ( condition ) && ( condition ) ) { // then do stuff here } Here is how : if ( ( a>b ) && ( c>d ) ) { // then do stuff here }
31
Logical Operators cont.
&& and || or ! not List of 3 operators: || is two of these
32
Logical Operators cont.
Logical Truth Tables: True && True = True False && True = False True && False = False False && False = False AND True || True = True False II True = True True II False = True False || False = False OR ! Adding a NOT Will invert the result. XOR study this in your own time 32
33
Logical Operators cont.
&& is evaluated before || Example: if ( (a>b) || (c>d) && (x==y) ) { // then do stuff here } 1 tab indentation
34
Logical Operators cont.
Another Example: if ( !(a>b) && !(x==y) ) { // then do stuff here } This is identical to: if ( (a<=b) && (x!=y) ) { // then do stuff here }
35
Three Steps to Conditional Heaven
Step 1: Comparison Operators Step 2: Logical Operators ( &&, ||, ! ) Step 3: 'if' statement structure
36
'if' Statements, version 1 of 4
simple ‘if’ 'if' statements can come in different forms The simplest form is this: Condition Go here only if true Continue here // program comes from here if (condition here ) { // go here if only true // execute lines coded here } // Continue here LINK
37
'if' Statements, version 2 of 4
‘if’ ’else’ The second version looks like this: // program comes from here if (condition here ) { // Go here if true // execute code written here } else // Go here if false // Continue here Condition Go here if true Go here if false Continue here LINK
38
'if' Statements, version 3 of 4
‘else if’ ’else’ The third version looks like this: Condition1 Condition2 Go here if cond1 true Else go here if cond2 true Else go here // program comes from here if (condition here ) { // Go here if true } else if ( another condition here ) //Go here if 1st condition false and 2nd true else // Go here if none of the above expressions true //Continue here
39
'if' Statements, version 4 of 4
‘else if’ : ’else’ 'if' Statements, version 4 of 4 1st Condition 2nd Condition 3rd Condition If 1st cond true do this If 2nd cond true do this If 3rd cond true do this else to this if (condition here ) { // Go here if first condition is true } else if (2nd condition here ) { // only if 1st condition is false // and the 2nd condition one is true else if (3rd condition here ) { // only if 1st and 2nd conditions are false // and the 3rd one true else { // if all the above conditions are false do this. //Continue here
40
Three Steps to Conditional Heaven
Step 1: Comparison Operators Step 2: Logical Operators ( &&, ||, ! ) Step 3: 'if' statement structure Done !
41
Check your knowledge now:
What is wrong here ? float premium, carValue=500.0; int driverAge=30; if ( (driverAge>=18) & (driverAge <30 ) ) { premium = 0.20; } else if (driverAge>30) && (driverAge <40) ) { premium = 0.10; else if { premium = 0.05; System.out.println("Premium is " +(premium*carValue) ); correct & should be && '(' missing what if driver is precisely 30? 'else if' but no boolean expr.
42
A Little Task Now…(5 min)
Write a “pub crawl” program: If you have more than 50 pounds: visit 1 pub if you have 1 hour or less visit 2 pubs if you have more than 1 hour but less than 2 visit 3 pubs if you have even more time If you have only 50 pounds or less you won't visit any pub. Use these variables: int pounds=55, hours=2, pubVisits;
43
int pounds=55, hours=2, pubVisits;
if ( pounds > 50 ) { // if you have more than 50 pounds // do one // of many // possible // pub visit // scenarios } else { // if you have 50 pounds or less pubVisits = 0; // forget it if( hours <= 1) { // if you have 1 hour or less pubVisits = 1; // visit 1 pub } else if ( hours < 2 ) { // if you have less than 2 pubVisits = 2; // visit 2 pubs else { // even more time pubVisits = 3; // visit 3 pubs
44
And Now Something New: Two ways of implementing program branches:
'if' statements 'switch' - 'case' statements
45
Structure of 'switch' - 'case'
int in; int x=5, y=2, z; in = UserInput.readInt(); switch( in ) { case 1 : z = x+y; break; case 2: z = x-y; default: System.out.println("Invalid input"); } The 'switch' - 'case' statement uses 4 keywords: case switch break default
46
Usage of 'switch' - 'case' Usually in 'menu' type applications:
This is a calculator program. Type: 'A' to add two numbers 'S' to subtract two numbers 'M' to multiply 'D' to divide
47
Implementation of the 'Calculator'
char in; in = UserInput.readChar(); switch( in ) { case 'A' : // code to prompt, read and add here break; case 'S': // prompt, read and subtract here case 'M': // prompt, read and multiply here case 'D': // prompt, read and divide here default: System.out.println("Invalid input"); } What happens if a lowercase letter is entered?
48
Catching Multiple Cases
If you want to catch multiple inputs write: char in; in = UserInput.readChar(); switch( in ) { case '+' : case 'a' : case 'A' : // prompt, read and add here break; case '-' : case 's' : case 'S': // prompt, read and subtract here
49
Do we Always Need a 'break' ?
Consider a programming IDE: step 1: edit step 2: compile step 3: run if you have just started you want the sequence: edit-compile-run if you already have an edited file you want: compile-run if you already have edited and compiled you just: run
50
Implementing the IDE 'menu'
char in; in = UserInput.readChar(); switch( in ) { case 'e' ; case 'E' : // start the editor here case 'c' : case 'C' : // start the compiler here case 'r' : case 'R': // run the programme here break; // this ‘break’ is required! default: System.out.println("Invalid input"); }
51
Check your knowledge now:
What is wrong here ? char input; input = UserInput.readString(); switch ( input ) case "+" : case "A" : // add here case '-' : case 'S': // subtract default System.out.println("wrong input"); } should be .readChar(); opening '{' missing char is in single quotes 'A', '+' 'possibly a 'break' missing definitely a 'break' missing ':' after default missing
52
Exercise Write a menu for a student lifestyle simulator program:
Menu points are: (G) Get up; (H) Have breakfast; (S) Skip lecture; start the sequence get up - have breakfast, if the user types a ‘g’ or a ‘G’ have only breakfast if ‘h’ or a ‘H’ is typed in, simulate skipping a lecture if a ‘s’ or ‘S’ has been entered. default behaviour (in the event of an unrecognised input ,i.e. no 'g', 'h' or 's' ) is a pub crawl.
53
Solution char usrIn = UserInput.readChar(); switch( usrIn ) {
case ‘g’: case ‘G’: // getting up code here case ‘h’: case ‘H’: // breakfast code here break; case ‘s’: case ‘S’: // lecture skipping code here default: // pub visit code here }
54
Summary 1 Today we have learned how to...
use arithmetic operators (+, -, %, *, / ) use incremental operators (++, --) build boolean expressions in conditional statements ('if') by using comparison operators (<,>, ==,…) using logical operators (&&, ||, ! ) apply the structure of the 'if' statement
55
Summary 2 Today we have ... revised 'if' statements
introduced 'switch' - 'case' the 4 keywords: switch, case, default, break catching multiple inputs: 'A', 'a', '+' where to 'break' and where not designing a 'menu' structure
56
END OF LESSON2
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.