0% found this document useful (0 votes)
12 views63 pages

Slides 2 - Input, Assignment, Arithmetic Expressions, Strings

The document covers key concepts in Object-Oriented Programming I, focusing on input, assignment, arithmetic expressions, and strings in Java. It introduces the Scanner class for console input, explains assignment operators, arithmetic expressions, and provides examples of using these concepts in Java code. Additionally, it discusses operator precedence, shorthand assignment statements, and increment/decrement operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views63 pages

Slides 2 - Input, Assignment, Arithmetic Expressions, Strings

The document covers key concepts in Object-Oriented Programming I, focusing on input, assignment, arithmetic expressions, and strings in Java. It introduces the Scanner class for console input, explains assignment operators, arithmetic expressions, and provides examples of using these concepts in Java code. Additionally, it discusses operator precedence, shorthand assignment statements, and increment/decrement operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

COMP 248:

OBJECT ORIENTED
PROGRAMMING I

Slides 2: Input, Assignment, Arithmetic


Expressions, Strings

The content on these slides was originally provided by


Dr. Nora Houari.
Topics …
7. Numeric Console Input
8. Assignment
9. Arithmetic Expressions
10. More Assignment Operators
11. Assignment Compatibility
12. Strings
13. String Console Input

n 2
7. Numeric Console Input
Class Libraries & Packages
■ A class library (ex: Java standard class library) is a
collection of classes that we can use when developing
programs
■ The classes of the Java standard class library are
organized into packages
Package Purpose

java.lang General support


java.text Format text for output
java.applet Creating applets for the web
java.awt Graphics and graphical user interfaces
java.util Utilities
n 3
The import Declaration
q to use a class from a package
– you can import only the class DecimalFormat from the
package java.text
import java.text.DecimalFormat;

– or import all classes from the package java.text


import java.text.*;

q All classes of the java.lang package are imported


automatically into all programs

q That's why we didn't have to import the System or


String classes explicitly

n 4
Console Input
q since Java 5.0, use the Scanner class

q the keyboard is represented by the System.in object

1. import java.util.Scanner;
2. Scanner myKeyboard = new Scanner(System.in);

n 5
To read from a scanner
qto read tokens, use a nextSomething() method
– nextBoolean(),
– nextByte(), tokens are delimited by
whitespaces (blank spaces,
– nextInt(),
tabs, and line breaks)
– nextFloat(),
– nextDouble(),
– next(), Will see later in the chapter
– nextLine() Will see later in the chapter
– …
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Your name:");
String name = myKeyboard.next();
System.out.println("Welcome " + name + " Enter your age:");
int age = myKeyboard.nextInt();

n 6
Example 1: ScannerDemo1.java
//*****************************************************
// Author: W. Savitch (modified by N. Acemian)
//
// This program demonstrates how to read numeric tokens from
// the console with the Scanner class
//*****************************************************
import java.util.Scanner; // we need to import this class

public class ScannerDemo1


{
public static void main(String[] args)
{
// let's declare our scanner
Scanner keyboard = new Scanner(System.in);

n 7
Example 1: ScannerDemo1.java
// let's ask the user for some input
System.out.println("Enter the number of pods followed by");
System.out.println("the number of peas in a pod:");
// let's read the user input (2 integers that we assign to 2
// variables)
int numberOfPods = keyboard.nextInt( );
int peasPerPod = keyboard.nextInt( );
int totalNumberOfPeas = numberOfPods*peasPerPod;

n 8
Example 1: ScannerDemo1.java
// let's display some output
System.out.print(numberOfPods + " pods and ");
System.out.println(peasPerPod + " peas per pod.");
System.out.println("The total number of peas = "
+ totalNumberOfPeas);
// close the Scanner
keyboard.close();
} // end of main()
} // end of class ScannerDemo1

n 9
Example 2: ScannerDemo2.java
//*******************************************************
// Author: W. Savitch (modified by N. Acemian)
//
// This program demonstrates how to read various types
// of token with the Scanner class
//*******************************************************
import java.util.Scanner;
public class ScannerDemo2
{
public static void main(String[] args)
{
// let's try to read integers
int n1, n2; // let's declare 2 variables for our tests
// let's declare our scanner object
Scanner scannerObject = new Scanner(System.in);

n 10
Example 2: ScannerDemo2.java
// let’s read two whole numbers (integers)
System.out.println("Enter two whole numbers ");
System.out.println("separated by one or more spaces:");

// we read 1 integer and assign it to n1


n1 = scannerObject.nextInt( );

// we read another integer and assign it to n2


n2 = scannerObject.nextInt( );

System.out.println("You entered " + n1 + " and " + n2);

n 11
Example 2: ScannerDemo2.java
System.out.println("Next enter two numbers with a decimal
point.");
System.out.println("Decimal points are allowed.");
// let's try to read doubles now
double d1, d2;
d1 = scannerObject.nextDouble( );
d2 = scannerObject.nextDouble( );
System.out.println("You entered " + d1 + " and " + d2);
// close the Scanner
scannerObject.close();
} // end of main()
} // end of class ScannerDemo2

n 12
close() method
qGood habit to close a Scanner object, at the end of your
program
qEx:
Say created a Scanner object called keyIn as follows

Scanner keyIn = new Scanner(System.in);


Good habit to include the following statement just before the
last } for the main method
keyIn.close();

Will keep Eclipse happy!


8- Assignment
q Used to change the value of a variable
q The assignment operator is the = sign
total = 55;

q Syntax: Variable = Expression;

q Semantics:
1. the expression on the right is evaluated
2. the result is stored in the variable on the left (overwrite
any previous value)
3. The entire assignment expression is worth the value of
the RHS
n 14
Example
public class Geometry
{
// Prints the number of sides of several geometric shapes.
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println("A heptagon has " + sides + " sides.");

sides = 10; // assignment statement


System.out.println("A decagon has " + sides + " sides.");
sides = 10+2;
System.out.println("A dodecagon has " + sides + " sides.");
}
}
filename???
???

Output
n 15
Difference with the math =
q In Java, = is an operator
q In math, = is an equality relation
In math… a+6 = 10 ok
In Java… a+6 = 10;

In math… a = a+1 always false


In Java… a = a+1;

In math… a = b and b = a same thing!


In Java… a = b; and b = a;

n 16
Examples
q Declarations:
int x;
int y = 10;
char c1 = ’a’;
char c2 = ’b’;
q Statements:
x = 20+5;
y = x;
c1 = ’x’;
c2 = c1;
n 17
Swap content of 2 variables
q Write a series of declarations & statements to swap the
value of 2 variables…

int x = 10; int y = 20;

A) x = y; y = x;
B) y = x; x = y;
C) Both A) & B) will work
D) Neither A) nor B) will work

n 18
9 - Arithmetic Expressions
q An expression is a combination of one or more
operands and their operators
q Arithmetic operators:

Addition +
Subtraction -
Multiplication *
Division /
Remainder %

n 19
Division and Remainder …
the division operator (/) can be:
qInteger division
• if both operands are integers
10 / 8 equals? 1
8 / 12 equals? 0

q Real division
• otherwise 10.0 / 8 equals? 1.25
8 / 12.0 equals? 0.6667

n 20
Division and Remainder

The remainder operator (%) returns the remainder after the


integer division

10 % 8 equals? 2 (10÷8 = 1 remainder 2)


8 % 12 equals? 8

n 21
Operator Precedence
q Operators can be combined into complex expressions
result = total + count / max - offset;

q Precedence determines the order of evaluation


– 1st: expressions in parenthesis
– 2nd: unary + and -
– 3rd: multiplication, division, and remainder
– 4th: addition, subtraction, and string concatenation
– 5th: assignment operator

n 22
Operator Associativity
q Unary operators of equal precedence are grouped
right-to-left
+-+rate is evaluated as +(-(+rate))

q Binary operators of equal precedence are grouped


left-to-right
base + rate + hours is evaluated as
(base + rate) + hours
q Exception: A string of assignment operators is
grouped right-to-left
n1 = n2 = n3; is evaluated as n1 = n2 = n3;

n 23
Example
q What is the order of evaluation in the following
expressions?

a + b + c + d + e a + b * c - d / e

a / (b + c) - d % e a / (b * (c + (d - e)))

n 24
Assignment Revisited
q The assignment operator has a lower precedence than
the arithmetic operators
First the expression on the RHS is evaluated

answer = sum / 4 + MAX * lowest;


4 1 3 2

Then the result is stored in the


variable on the LHS

n 25
You try

What is stored in the integer variable num1 after this


statement?
num1 = 2 + 3 * 5 - 5 * 2 / 5 + 10 ;

A) 0
B) 18
C) 25
D) 10

n 26
Let’s put it all together
q Purpose:
– Conversion of degrees Fahrenheit in degrees Celsius
q Algorithm:
1. Assign the temperature in Fahrenheit (ex. 100 degrees)
2. Calculate the temperature un Celsius (1 Celsius = 5/9 (Fahr – 32)
3. Display temperature in Celsius
q Variables and constants:
Data Identifier Type var or const?
Temperature in Fahrenheit fahr double

n 27
The Java program
//**********************************************************
// Temperature.java Author: your name
// A program to convert degrees Fahrenheit in degrees Celsius.
//**********************************************************
public class Temperature {
public static void main (String[] args)
{
// Declaration of variables and constants

// step 1: Assign the temperature in Fahrenheit (100)

// step2: Calculate the temperature un Celsius

// step3: Display temperature in Celsius

}
}
filename???
n28
10 - More assignment operators
q in addition to =
q often we perform an operation on a variable, and then
store the result back into that variable
q Java has shortcut assignment operators:
variable = variable operator expression;
variable operator= expression;

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
n 29
Shorthand Assignment Statements
Example: Equivalent To:
count += 2; count = count + 2;

sum -= discount; sum = sum – discount;

bonus *= 2; bonus = bonus * 2;

time /= rushFactor; time = time / rushFactor;

change %= 100; change = change % 100;

amount *= count1 + count2; amount = amount * (count1 + count2);

n 30
Assignment operators
q The behavior of some assignment operators
depends on the types of the operands
q ex: the +=
• If the operands are strings, += performs string
concatenation

• The behavior of += is consistent with the


behavior of the "regular" +

n 31
Example
int amount = 10;
amount += 5;
System.out.println(amount);

double temp = 10;


temp *= 10;
System.out.println(temp);

String word = "hello";


word += "bye";
System.out.println(word);
word *= "bye"; // ???
Output
n 32
Increment and Decrement
q In Java, we often add-one or subtract-one to a
variable…
q 2 shortcut operators:
• The increment operator (++) adds one to its
operand
• The decrement operator (--) subtracts one
from its operand
q The statement: count++;
is functionally equivalent to: count = count+1;
q The statement: count--;
is functionally equivalent to: count = count-1;

n 33
Increment and Decrement
The increment and decrement operators can be in:
q in prefix form - ex: ++count;
1. the variable is incremented/decremented by 1
2. the value of the entire expression is the new
value of the variable (after the
incrementation/decrementation)
q in postfix form: - ex: count++;
1. the variable is incremented/decremented by 1
2. the value of the entire expression is the old value
of the variable (before the
incrementation/decrementation)
n 34
Example
int nb = 50; int nb = 50;
++nb; nb++;
value of nb value of nb

int nb = 50; int nb = 50;


int x; int x;
value of nb & x value of nb & x
x = ++nb; x = nb++;

int nb = 50;
int x; value of nb & x
x = nb++ + 10;

n 35
Example
int nb = 50; int nb = 50;
int x; int x;
x = ++nb + nb; x = nb++ + nb;

value of nb & x value of nb & x

n 36
You try
What is stored in the integer variables num1, num2 and
num3 after the following statements?
int num1 = 1, num2 = 0;
int num3 = 2 * num1++ + --num2 * 5;

A) num1 = 1, num2 = 0, num3 = 2


B) num1 = 1, num2 = 0, num3 = -1
C) num1 = 2, num2 = -1, num3 = 2
D) num1 = 2, num2 = -1, num3 = -3
E) num1 = 2, num2 = -1, num3 = -1
n 37
You try
What is stored in the integer q after the following statements?
int x = 1, y = 10, z = 3;
int q = ++x * y-- + z++;

A) 13
B) 20
C) 23
D) No idea???

n 38
You try
What is stored in the integers a and c after the following
statements?
int a = 1;
int c = a++ + a--;

A) a = 1, c = 2
B) a = 1, c = 3
C) a = 3, c = 3
D) No idea???

n 39
You try
What is stored in the integer c after the following statements?
int a = 1, b = 2;
int c = a++ + a + 2*(-- b) + 3/b--;

A) 7
B) 8
C) 8.5
D) No idea???

n 40
Summary of ++ and - -

Expression Operation Value Used in Expression


count++ add 1 old value
++count add 1 new value
count-- subtract 1 old value
--count subtract 1 new value

n 41
11 - Assignment Compatibility
q In general, the value of one type cannot be stored in a
variable of another type
int intVariable = 2.99; //Illegal

q However, there are exceptions to this


double doubleVariable = 2;

• For example, an int value can be stored in a double


type

n 42
Assignment Compatibility
q an expression has a value and a type
2 / 4 (value = 0, type = int)
2 / 4.0 (value = 0.5, type = double)

q the type of the expression depends on the type of its


operands

q In Java, type conversions can occur in 3 ways:


• arithmetic promotion
• assignment conversion
• casting

n 43
Arithmetic promotion
q happens automatically, if the operands of an expression are
of different types
aLong + anInt * aDouble
q operands are promoted so that they have the same type
q promotion rules:
• if 1 operand is of type… the others are promoted to…
double double
float float (double)
long long
• short, byte and char are always converted to int

n 44
Examples
(aByte + anotherByte) --> int
(aLong + anInt * aDouble) --> ??
(aFloat - aBoolean) --> ??

■ value and type of these expressions?


2 / 4
int / int 2/4
int 0

n 45
Examples
q What is the value and type of this expression?
2 / 4 * 1.0

A) 0 (int)
B) 0.0 (double)
C) 0.5 (int)
D) 0.5 (double)

n 46
Examples
q What is the value and type of this expression?
1.0 * 2 / 4

A) 0 (int)
B) 0.0 (double)
C) 0.5 (int)
D) 0.5 (double)

n 47
Assignment conversions
q occurs when an expression of one type is assigned to a variable of
another type
var = expression;

q widening conversion
• if the variable has a wider type than the expression
• then, the expression is widened automatically

long aVar; byte aByte; double aDouble;


aVar = int anInt; int anInt = 10;
5+5; anInt = aByte; aDouble = anInt;

• integral & floating point types are compatible


• boolean are not compatible with any type

n 48
Assignment conversions
q narrowing conversion
• if the variable has a smaller type than the
expression then, compilation error, because
possible loss of information

int aVar;
aVar = 3.7; ok?

int aVar; int aVar;


aVar = 10/4; ok? aVar = 10.0/4; ok?

n 49
Casting
q the programmer can explicitly force a type conversion
q syntax: (desired_type) expression_to_convert
int aVar; byte aByte;
aVar = (int)3.7; int anInt = 75;
(aVar is 3… not 4!) aByte = anInt; // ok?
aByte = (byte)anInt; // ok?

double d;
d = 2/4; // d is 0
d = (double)2/4; // d is 0.5
// 2.0 / 4
d = (double)(2/4); // d is 0.0
Casting can be dangerous! you better know what you're
doing…
n 50
Examples
q Which of the following assignment statements are valid?
byte b1 = 1, b2 = 127, b3;
b3 = b1 + b2; // statement a)
b3 = 1 + b2 // statement b)
b3 = (byte)1 + b2 // statement c)

A) Statements a), b) and c) are valid


B) Only statements a) and b) are valid
C) Only statements b) and c) are valid
D) Only statements a) and c) are valid
E) None of the Java statements are valid

n 51
Examples
q Which of the following assignment statements are valid?
byte b1 = 1, b2 = 127, b3;
b3 = b1 + b2; // statement a)
b3 = 1 + b2; // statement b)
b3 = (byte)1 + b2; // statement c)

A) Statements a), b) and c) are valid


B) Only statements a) and b) are valid
C) Only statements b) and c) are valid
D) Only statements a) and c) are valid
E) None of the Java statements are valid

n 52
12- Strings
q so far we have seen only primitive types
q a variable can be either:
• a primitive type
- ex: int, float, boolean, …

• or a reference to an object
- ex: String, Array, …

q A character string:
• is an object defined by the String class
• delimited by double quotation marks ex: "hello", "a"
- System.out.print("hello"); // string of characters
- System.out.print('a'); // single character
n 53
Declaring Strings
1. declare a reference to a String object
String title;

2. declare the object itself (the String itself)


title = new String("content of the string");

This calls the String constructor, which is


a special method that sets up the object

n 54
Declaring Strings
q Because strings are so common, we don't have to use the
new operator to create a String object
String title;
title = new String("content of the string");

String title = new String("content of the string");

String title;
title = "content of the string";

String title = "content of the string";

q These special syntax works only for strings

n 55
Strings
q once a string is created, its value cannot be modified (the object
is immutable)
• cannot lengthen/shorten it
• cannot modify its content

q the String class offers:


• the + operator (string concatenation)
- ex: String solution = "The answer is " + "yes";

• many methods to manipulate strings, a string variable calls …


- length() // returns the nb of characters in a string
- concat(str) // returns the concatenation of the string and str
- toUpperCase() // returns the string all in uppercase
- replace(oldChar, newChar) // returns a new string
// where all occurrences of character oldChar have been replaced by character newChar
- … see textbook

n 56
String indexes start at zero

n 57
Example – StringTest.java
public class StringTest {
public static void main (String[] args) {
String string1 = new String ("This is a string");
String string2 = ""; ???

String string3, string4, string5;

Output
System.out.println("Content of string1: \"" + string1 + "\"");
System.out.println("Length of string1: " + string1.length());
System.out.println("Content of string2: \"" + string2 + "\"");
System.out.println("Length of string2: " + string2.length());

n 58
Example …
// String string1 = new String ("This is a string");
// String string2 = "";

string2 = string1.concat(" hello");


string3 = string2.toUpperCase();
string4 = string3.replace('E', 'X');
string5 = string4.substring(3, 10);

System.out.println(string2); Output
???
System.out.println(string3);
System.out.println(string4);
System.out.println(string5);
} }
n 59
Example 3: ScannerDemo3.java
//************************************************************
// Author: W. Savitch (modified by N. Acemian)
//
// This program demonstrates how to read String tokens with
// the Scanner class
//************************************************************
import java.util.Scanner;
public class ScannerDemo3
{
public static void main(String[] args) {
//Let's declare our Scanner object
Scanner scannerObject = new Scanner(System.in);
// let's try to read 2 "words" now
System.out.println("Next enter two words:");
String word1 = scannerObject.next( );
String word2 = scannerObject.next( );
System.out.println("You entered \"" + word1 + "\" and \""
+ word2 + "\"");
n 60
Example 3: ScannerDemo3.java
//To get rid of '\n‘

String junk = scannerObject.nextLine( );


// let's try to read an entire line
System.out.println("Next enter a line of text:");
String line = scannerObject.nextLine( );
System.out.println("You entered: \"" + line + "\"");

// Close Scanner
scannerObject.close();
} // end of main()
}// end of class ScannerDemo3

n 61
A note on readLine

q nextLine reads the remainder of a line of text starting where the last reading left
off
q This can cause problems when combining it with different methods for reading
from the keyboard such as nextInt
q ex:
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
String s1 = keyboard.nextLine();
String s2 = keyboard.nextLine();
input: need an extra invocation
2 of nextLine to get rid of
Heads are better than the end of line character
1 head.
after the 2
what are the values of n, s1, and s2?

n 62
close() method

q Good habit to close a Scanner object, at the end of your program


q Ex:
Say created a Scanner object called keyIn as follows

Scanner keyIn = new Scanner(System.in);


Good habit to include the following statement just before the last }
for the main
method
keyIn.close();

Will keep Eclipse happy!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy