50

Comp102 lec 5.1

Embed Size (px)

Citation preview

Page 1: Comp102   lec 5.1
Page 2: Comp102   lec 5.1

Take the value from right hand side (rvalue) and copy it into left hand side (lvalue)

Rvalue Constant , variable or expression

Lvalue Distinct, named variable

Page 3: Comp102   lec 5.1

3

Operator Example Equivalent

+= i += 8 i = i + 8

-= f -= 8.0 f = f - 8.0

*= i *= 8 i = i * 8

/= i /= 8 i = i / 8

%= i %= 8 i = i % 8

Page 4: Comp102   lec 5.1

4

Syntax Errors Detected by the compiler

Runtime Errors Causes the program to abort

Logic Errors Produces incorrect result

Page 5: Comp102   lec 5.1

5

A pair of braces in a program forms a block that

groups components of a program.

public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Class block

Method block

Page 6: Comp102   lec 5.1

6

Eihter next-line or end-of-line style for braces.

Page 7: Comp102   lec 5.1

7

Specifier Output Example

%b a boolean value true or false

%c a character 'a'

%d a decimal integer 200

%f a floating-point number 45.460000

%e a number in standard scientific notation 4.556000e+01

%s a string "Java is cool"

int count = 5;

double amount = 45.56;

System.out.printf("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000

items

Page 8: Comp102   lec 5.1

8

Description Escape Sequence

Backspace \b

Tab \t

Linefeed \n

Carriage return \r

Backslash \\

Single Quote \'

Double Quote \"

Page 9: Comp102   lec 5.1

Java in two semesters by Quentin Charatan & Aaron Kans

Page 10: Comp102   lec 5.1

The order in which the instructions were executed was not under your control

Program starts by executing the first instruction in main method and then all executed instructions were in sequence

This order of execution is restrictive and one as programmer need more control over the order in which the instructions are executed

Page 11: Comp102   lec 5.1

Generates boolean resultEvaluates relationship between

values of the operands Produces TRUE if relationship is true Produces FALSE is relationship is untrue

Page 12: Comp102   lec 5.1

Operator Meaning

== Equal to

!= Not equal to

< Less than

> Greater than

>= Greater than or equal to

<= Less than or equal to

Page 13: Comp102   lec 5.1
Page 14: Comp102   lec 5.1

Whenever we need to make choice among different courses of action

Example A program processing requests for airline tickets

could have following choices to make Display the price os seats requested Display a list of alternative flights Display a message saying that no flights are available to

that destinationA program that can make choices can behave

differently each time it is run, whereas programs run in sequence behave the same way each time they are run

Unless otherwise mentioned, program instructions are executed in sequence

Page 15: Comp102   lec 5.1
Page 16: Comp102   lec 5.1

Some of the instruction need a guard so that they are executed only when appropriate JAVA if statement

Syntaxif(/* a test goes here*/){

// instruction (s) to be guarded go here}

The braces indicate the body of if statement If statement must follow the round brackets and

condition is placed inside these brackets Condition/expression gives a boolean result of true or

false

Page 17: Comp102   lec 5.1

import java.util.Scanner;public class Assignment1 {

public static void main(String[] args) {int x = 0;Scanner scan = new Scanner(System.in);x = scan.nextInt();if(x%2 == 0){

System.out.println("number is even");}

}}

Page 18: Comp102   lec 5.1

import java.util.Scanner;public class Assignment1 { public static void main(String[] args) {

int temperature = 0;Scanner scan = new Scanner(System.in);temperature = scan.nextInt();if(temperature<0){

System.out.println("its freezing");System.out.println("temperature is: "+temperature);System.out.println("Wear appropriate clothes");

} }}

Page 19: Comp102   lec 5.1

Single – branched instructionsThe if statement provides two choices

Execute the conditional instructions Condition is true

Do not execute the conditional instructions Condition is false Do nothing

Page 20: Comp102   lec 5.1

Double branched selectionAlternative course of actionChoices

Some instructions are executed if condition is true Some other instructions are executed if condition is

false

Page 21: Comp102   lec 5.1

import java.util.Scanner;public class Assignment1 {

public static void main(String[] args) {int x = 0;Scanner scan = new Scanner(System.in);x = scan.nextInt();if(x%2 == 0){

System.out.println("number is even");}else{

System.out.println("number is odd");}System.out.println(“good work");

}}

Page 22: Comp102   lec 5.1
Page 23: Comp102   lec 5.1

int n1 = 15; int n2 = 15;System.out.println(n1==n2);System.out.println(n1!=n2);

Page 24: Comp102   lec 5.1

Often it is necessary to join two or more tests together to create a complicated test

Consider a program that checks the temperature in laboratory. To have a successful experiment it is required that the temperature remain between 5 and 12

The test need to check Temperature is greater than or equal to 5

Temperature>=5 Temperature is less than or equal to 12

Temperature <=12 Both of these tests need to evaluate true in order to

provide the right environment

Page 25: Comp102   lec 5.1

Logical Operator Java CounterpartAND &&OR ||NOT !

Produces a boolean value of true or false based on logical relationship of arguments

Allowed in between of boolean values onlyConditions generate boolean result

Page 26: Comp102   lec 5.1

A = Result of 1st

Expression

A = Result of 2nd

Expression

A && B

True True TrueTrue False FalseFalse True FalseFalse False False

Page 27: Comp102   lec 5.1

A = Result of 1st

Expression

A = Result of 2nd

Expression

A || B

True True TrueTrue False True False True True False False False

Page 28: Comp102   lec 5.1

X !XTRUE FALSEFALSE TRUE

Page 29: Comp102   lec 5.1

import java.util.Scanner;public class Assignment1 { public static void main(String[] args) {

int temperature = 0;Scanner scan = new Scanner(System.in);temperature = scan.nextInt();if(temperature>=5 && temperature <=12){

System.out.println("environment is safe");}else{

System.out.println("environment is not safe");}

}}

Page 30: Comp102   lec 5.1

In JavaIf a value is zero, it can be used as the logical

value false.

If a value is not zero, it can be used as the logical value true.

Zero <===> False Nonzero <===> True

Page 31: Comp102   lec 5.1

Expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined

Latter parts of the logical expression might not be evaluated

Page 32: Comp102   lec 5.1

Expression Result Explanation

10>5 && 10>7 True Both results are true

10>5 && 10>20 False The second test is false

10>15 && 10>20 False Both tests are false

10>5 || 10>7 True At least one test is true

10>5 || 10>20 True At least one test is true

10>15 || 10>20 False Both tests are false

!(10>5) False Original test is true

!(10>15) True Original test is false

Page 33: Comp102   lec 5.1

Instructions within if and if…else statements can themselves be any legal java commands

It is also allowed that if statements contain other if/if-else statements Nesting Allows multiple choices to be processed

Page 34: Comp102   lec 5.1
Page 35: Comp102   lec 5.1

public static void main(String[] args) {

int marks = 0;Scanner scan = new Scanner(System.in);marks = scan.nextInt();if(marks <100){

if(marks>=80){

System.out.println("Grade = A");}else{

if(marks>=60){

System.out.println("Grade = B");}else{

System.out.println("Grade = F");}

}}

}

Page 36: Comp102   lec 5.1

public static void main(String[] args) {

int marks = 0;Scanner scan = new Scanner(System.in);marks = scan.nextInt();if(marks <100){

if(marks>=80){

System.out.println("Grade = A");}else if(marks>=60){

System.out.println("Grade = B");}else{

System.out.println("Grade = F");}

}}

Page 37: Comp102   lec 5.1

else is always paired with the most recent,

unpaired if

Page 38: Comp102   lec 5.1
Page 39: Comp102   lec 5.1
Page 40: Comp102   lec 5.1

40

Adding a semicolon at the end of an if clause is a common mistake.

if (radius >= 0);{ area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area);}This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style.

Page 41: Comp102   lec 5.1

Conditional operatorHas three operandsBoolean-exp? value0 : value1

import java.util.Scanner;public class Assignment1 { public static void main(String[] args) {

int marks = 0;Scanner scan = new Scanner(System.in);marks = scan.nextInt();System.out.println(marks>=50? "Pass":"Fail");

}}

Page 42: Comp102   lec 5.1
Page 43: Comp102   lec 5.1

public static void main(String[] args) {int value = 0;Scanner scan = new Scanner(System.in);value = scan.nextInt();switch(value){

case 1: System.out.println("We are in case 1");break;

case 2: System.out.println("We are in case 2");break;

case 3: System.out.println("We are in case 3");break;

default: System.out.println("We are in case default");//break;

}}

Page 44: Comp102   lec 5.1

Only one variable is being checked in each conditionCheck involves only specific values of that variable

and not ranges (>= or <= are not allowed)Switch statement condition carries the name of the

variable onlyThe variable is usually of type int or char but can also

be of type long, byte or shortbreak is optional command that forces the program to

skip the rest of switch statementDefault is optional (last case) that can be thought of as

an otherwise statement. Deal with the possibility if none of the cases above is true

Page 45: Comp102   lec 5.1
Page 46: Comp102   lec 5.1
Page 47: Comp102   lec 5.1

47

Consider the following statements:

byte i = 100;

long k = i * 3 + 4;

double d = i * 3.1 + k / 2;

Page 48: Comp102   lec 5.1

48

When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules:

 1. If one of the operands is double, the other is

converted into double.2. Otherwise, if one of the operands is float, the

other is converted into float.3. Otherwise, if one of the operands is long, the

other is converted into long.4. Otherwise, both operands are converted into

int.

Page 49: Comp102   lec 5.1

49

Implicit casting double d = 3; (type widening)

Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated)

What is wrong? int x = 5 / 2.0;

byte, short, int, long, float, double

range increases

Page 50: Comp102   lec 5.1

50

int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;