0% found this document useful (0 votes)
59 views36 pages

Data and Expression 3

This document discusses Java data types, variables, expressions, data conversion, and interactive programs. It covers Java arithmetic expressions and operator precedence, data type conversions including assignment conversion, promotion, and casting. It also introduces the Scanner class for reading user input in interactive Java programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views36 pages

Data and Expression 3

This document discusses Java data types, variables, expressions, data conversion, and interactive programs. It covers Java arithmetic expressions and operator precedence, data type conversions including assignment conversion, promotion, and casting. It also introduces the Scanner class for reading user input in interactive Java programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

data and

expressions III
Outline
Java Data Types
Variables and Assignment
Expressions
Data Conversion
Interactive Programs
expressions combination of one or more
operators and operands

Arithmetic Expressions
expressions rules

If either or both operands


compute numeric are floating point values,
results using then the result is a floating
arithmetic point value
operators.
If both operands to the
division operator (/) are
Addition +
integers, the result is an
Subtraction - integer (the fractional part is 14 / 3 = 4
Multiplication * discarded)
Division / 8 / 12 = 0
Remainder %
The remainder operator (%)
returns the remainder after
dividing 14 % 3 = 2
8 % 12 = 8
Quick Check

What are the results of the following expressions?

12 / 2 = 6
12.0 / 2.0 = 6.0
10 / 4 = 2
10 / 4.0 = 2.5
4 / 10 = 0
4.0 / 10 = 0.4
12 % 3 = 0
10 % 3 = 1
3 % 10 = 3
op. precedence
operators of the same eg.
precedence are evaluated 3 + 4 * 5
Operator from left to right. (3 + 4 ) * 5

precedence In a mixed expression


rules arithmetic operators are
evaluated in precedence
order.

Order Group Operator


Operator subexpression ( )
precedence High
unary operator - , +
order multiplicative *, /, %
operator
Low additive operator +, -
operator precedence
Operators Precedence
postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !


multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Examples : precedence

What’s the value of variable c:

int c = 9 + 6 - 3 * 6 / 2;
use parentheses to
avoid subtle semantic
errors.

Evaluate: 9 + 6 - 3 * 6 / 2
Step 1. 9 + 6 - (3 * 6) / 2
5/3/2.0 // 0.5
Step 2. 9 + 6 - (18 / 2 )
5/(3/2.0) // 3.33
Step 3. (9 + 6) - 9
Step 4. ( 15 - 9 )
Step 5. 6
Quick Check
In what order are the operators evaluated in the following
expressions?

a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2

a / (b + c) - d % e a / (b * (c + (d - e)))
2 1 4 3 4 3 2 1
expression trees
• The evaluation of a particular expression
can be shown using an expression tree

• The operators lower in the tree have


higher precedence for that expression

a /

a + (b – c) / d
- d

b c
assignment revisited
assignment operator has a lower
precedence than the arithmetic operators

First the expression on the right hand


side of the = operator is evaluated answer = sum / 4 + MAX * lowest;
4 1 3 2
Then the result is stored in the
variable on the left hand side

The right and left hand sides of an assignment


statement can contain the same variable
First, one is added to the
original value of count

count = count + 1;

Then the result is stored back into count


(overwriting the original value)
increment/decrement

The increment (++) and decrement (--) operators use only one operand
e.g count++; // count = count + 1;

The increment and decrement operators can be

postfix form: count++; When used as part of a larger


expression, the two forms can have
different effects … use them with
prefix form: ++count; care !

Expression Operation Interpretation


j = ++k; Preincrement k = k + 1; j = k;
j = k++; Postincrement j = k; k = k + 1;
j = --k; Predecrement k = k – 1; j = k;
j = k--; Postdecrement j = k; k = k – 1;
ternary operator
"If someCondition is true, assign the value of value1 to result.
Otherwise, assign the value of value2 to result."
assignment operators
Often we perform an operation on a variable, and then store the
result back into that variable. Short cut in java …
num += count; is equivalent to num = num + count;

Operator Example Equivalent To

+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

result /= (total-MIN) % num; is equivalent to

result = result / ((total-MIN) % num);

The behavior of some assignment operators depends on the types of the operands

If the operands to the += operator are strings, the assignment operator performs string concatenation

The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding
operator (+)
the math class
• Math class: contains methods like sqrt and pow
• To compute xn, you write Math.pow(x, n)
• However, to compute x2 it is significantly more efficient simply to compute x * x
• To take the square root of a number, use the Math.sqrt; for example, Math.sqrt(x)

In Java,

(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)


Java mathematical methods
Math.sqrt(x) square root

Math.pow(x, y) power xy

Math.exp(x) ex

Math.log(x) natural log

Math.sin(x), Math.cos(x), sine, cosine, tangent (x in radian)


Math.tan(x)
Math.round(x) closest integer to x

Math.min(x, y), Math.max(x, y) minimum, maximum


analyzing an expression
Java Data Types
Variables and Assignment
Expressions
Data Conversion
Interactive Programs
data conversion
• Sometimes it is convenient to convert data from one type to another,
e.g. treating integer as floating point

• conversions do not change the type of a variable or the value that's


stored in it – they only convert a value during computation

Widening conversions are safe (go from a small data type to a larger one
(such as a short to an int) - Narrowing conversions can lose information
(from a large data type to a smaller one (such as an int to a short)

Widening Conversions Narrowing Conversions


Types of data conversion

In Java, data conversions can occur in


three ways:

• assignment conversion
• promotion
• casting
assignment conversion

• Assignment conversion occurs when a value of one type is assigned


to a variable of another
• Example:
int dollars = 20;
double money = dollars;

• Only widening conversions can happen via assignment


• Note that the value or type of dollars did not change
Promotion
• Promotion happens automatically when operators in expressions convert
their operands
• Example:
int count = 12;
double sum = 490.27;
result = sum / count;

• The value of count is converted to a floating point value to perform the


division calculation
Casting
• Casting is the most powerful, and dangerous, technique for
conversion
• Both widening and narrowing conversions can be accomplished
by explicitly casting a value
• To cast, the type is put in parentheses in front of the value
being converted
int total = 50;
float result = (float) total / 6;
• Without the cast, the fractional part of the answer would be
lost
Outline
Java Data Types
Variables and Assignment
Expressions
Data Conversion
Interactive Programs
Interactive Programs
• Programs generally need input on which to operate
• The Scanner class provides convenient methods for
reading input values of various types
• A Scanner object can be set up to read input from
various sources, including the user typing values on the
keyboard
• Keyboard input is represented by the System.in object
reading input

• The following line creates a Scanner object that reads from


the keyboard:

Scanner scan = new Scanner (System.in);


• The new operator creates the Scanner object
• Once created, the Scanner object can be used to invoke
various input methods, such as:

answer = scan.nextLine();
Reading Input
• The Scanner class is part of the java.util class
library, and must be imported into a program to be
used
• The nextLine method reads all of the input until
the end of the line is found
• See Echo.java
• The details of object creation and class libraries are
discussed further in Chapter 3
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************

import java.util.Scanner;

public class Echo


{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);

System.out.println ("Enter a line of text:");

message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\"");


}
}
Sample Run
//********************************************************************
// Echo.java Author: Lewis/Loftus
// Enter a line of text:
You want
// Demonstrates thefries with
use of the that?
nextLine method of the Scanner class
// to read a string from the user.
You entered: "You want fries with that?"
//********************************************************************

import java.util.Scanner;

public class Echo


{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);

System.out.println ("Enter a line of text:");

message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\"");


}
}
Input Tokens
• Unless specified otherwise, white space is used to separate the elements
(called tokens) of the input
• White space includes space characters, tabs, new line characters
• The next method of the Scanner class reads the next input token and
returns it as a string
• Methods such as nextInt and nextDouble read data of particular
types
• See GasMileage.java
//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//// Demonstrates the use of the Scanner class to read numeric data.
//********************************************************************

import java.util.Scanner;
public class GasMileage
{
//-----------------------------------------------------------------
// Calculates fuel efficiency on values entered by the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int miles;
double gallons, mpg;

Scanner scan = new Scanner (System.in);


System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;

System.out.println ("Miles Per Gallon: " + mpg);


}
}
Sample Run
//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//// Demonstrates the use of the Scanner class to read numeric data.
Enter the number of miles: 328
//********************************************************************
Enter the gallons of fuel used: 11.2
import java.util.Scanner;
Miles Per Gallon: 29.28571428571429
public class GasMileage
{
//-----------------------------------------------------------------
// Calculates fuel efficiency on values entered by the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int miles;
double gallons, mpg;

Scanner scan = new Scanner (System.in);


System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;

System.out.println ("Miles Per Gallon: " + mpg);


}
}
import java.util.Scanner;
public class ChangeMaker
{
public static void main(String[] args)
{
int amount, originalAmount,
quarters, dimes, nickels, pennies;
System.out.println("Enter a whole number from 1 to 99.");
System.out.println("I will find a combination of coins");
System.out.println("that equals that amount of change.");

Scanner keyboard = new Scanner(System.in);


amount = keyboard.nextInt();
originalAmount = amount;
quarters = amount / 25;
amount = amount % 25;
dimes = amount / 10;
amount = amount % 10;
nickels = amount / 5;
amount = amount % 5;
pennies = amount;

System.out.println(originalAmount +" cents in coins can be given as:");


System.out.println(quarters + " quarters");
System.out.println(dimes + " dimes");
System.out.println(nickels + " nickels and");
System.out.println(pennies + " pennies");
}
}
Exercises

1.Create a small program that defines some fields. Try


creating some illegal field names and see what kind of
error the compiler produces. Use the naming rules and
conventions as a guide.

2.In the program you created in Exercise 1, try leaving the


fields uninitialized and print out their values. Try the same
with a local variable and see what kind of compiler errors
you can produce. Becoming familiar with common
compiler errors will make it easier to recognize bugs in your
code.

You might also like