C248_Chpt1_MT
Download
Report
Transcript C248_Chpt1_MT
COMP 248:
OBJECT ORIENTED PROGRAMMING I
TODAY…
Course outline/course web page “Quiz” using
your clicker
Start Chap. 1
2
ANY ????
Reminder: Course Website at
https://users.encs.concordia.ca/~mtaleb/COM
P248
Any questions on course outline?
ENCS login
3
QUESTION 1
My last name is?
A. Talbi
B. Talibe
C. Talebi
D. Taleb
E. Don’t know!
4
QUESTION 2
My office hours are on
which days?
A. Mon to Wed
B. Mon to Thu
C. By appointment
D. You have office hours? University students
don’t need office hours!
E. Don’t know!
5
QUESTION 3
How many assignments are there?
A. Assignments? None – We don’t need any
B. 3
C. 4
D. 5
E. Don’t know
6
QUESTION 4
How many term tests are there?
A. 1
B. 2
C. 3
D. 4
E. Don’t know!
7
QUESTION 5
How much of the course grade is the final exam
worth?
A. 60%
B. 55%
C. 45%
D. 30%
E. Don’t know!
8
QUESTION 6
Where can I get help/advise if I need it?
A. From my teacher
B. From my tutors
C. help4u
D. All of the above
E. I’m in University now!
I’m on my own
9
HOW TO SUCCEED IN THIS COURSE!
Keep up as material is cumulative
Program the examples in the slides and ‘play’
with them
Study in groups
You don’t understand something get help right
away from your tutor, study group member,
teacher as soon as possible.
10
GRAPHICS ON THE COURSE SLIDES
= the slides will be completed in
class
= clicker question
11
COMP 248: OBJECT ORIENTED
PROGRAMMING I
Chapter 1: A First Program
WHY DO PROGRAMMING?
Humans communicate in a natural language
Large vocabulary (10 000s words)
Complex syntax
Semantic ambiguity
The chair’s leg is broken.
The man saw the boy with the telescope.
Machines communicate in binary code / machine
language
Small vocabulary (2 words… 1, 0)
Simple syntax
No semantic ambiguity
13
SO?
Humans -- natural language
Machines -- binary language
Large vocabulary
Complex syntax
Semantic ambiguity
Programming
(COMP 248 + COMP 249)
Small vocabulary
Simple syntax
No semantic ambiguity
Compiler + Interpreter
Programming language
Ex: ???
Vocabulary: restricted
Syntax: small and restricted
Semantic: no ambiguity (almost)
14
ORIGINS OF THE JAVA LANGUAGE
Created by Sun Microsystems (1991)
Originally designed for programming home
appliances
Introduced in 1995 and its popularity has grown
quickly since
Is an object-oriented programming (OOP) language
15
COMPILERS
A compiler:
Usually (ex. C, C++)
is a software tool which translates source code into another
language
The compiler translates directly into machine language
But each type of CPU uses a different machine language
… so same executable file will not work on different
platforms
… need to re-compile the original source code on different
platforms
Java is different…
16
JAVA TRANSLATION
Java compiler:
Java source code --> bytecode
A machine language for a fictitious computer called the
Java Virtual Machine
Java interpreter:
Executes the Java Virtual Machine (JVM)
Java bytecode --> into machine language and executes it
Translating byte-code into machine code is relatively
easy compared to the initial compilation step
So the Java compiler is not tied to any particular machine
Once compiled to byte-code, a Java program can be used on
any computer, making it very portable
17
JAVA TRANSLATION
Java source
Code
MyProg.java
javac MyProg.java
Machine
Code
Java Bytecode
Java Interpreter
MyProg.class
java MyProg
Java Compiler
18
SOME DEFINITIONS
Algorithm:
Pseudocode:
A step-by-step process for solving a problem
Expressed in natural language
An algorithm expressed in a more formal language
Code-like, but does not necessarily follow a specific syntax
Program:
An algorithm expressed in a programming language
Follows a specific syntax
19
PROBLEM SOLVING
The purpose of writing a program is to solve a
problem
The general steps in problem solving are:
1.
2.
3.
4.
Understand the problem
Design a solution (find an algorithm)
Implement the solution (write the program)
Test the program and fix any problems
20
JAVA PROGRAM STRUCTURE
A java program:
is made up of one or more classes (collection of actions)
a class contains one or more methods (action)
a method contains program statements/instructions
A Java program always contains a method called
main
21
JAVA PROGRAM STRUCTURE
// comments about the class
public class MyProgram
class header
{
class body
}
MyProgram.java
22
JAVA PROGRAM STRUCTURE
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main (String[] args)
{
method body
method header
}
}
MyProgram.java
23
A SMALL JAVA PROGRAM
//********************************************************************
// Author: L. Kosseim
//
// Demonstrates the basic structure of a Java application.
//********************************************************************
public class Hello
{
//----------------------------------------------------------------// Prints a message on the screen
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("Hello World!!!");
}
}
Hello.java
Java is case sensitive!
extension of java programs
You will type and run this program in tutorial 1
24
SYNTAX AND SEMANTICS
Syntax rules
Semantics
define how we can put together symbols, reserved words,
and identifiers to make a valid program
define what a statement means
A program that is syntactically correct is not necessarily
logically (semantically) correct.
25
3 TYPES OF ERRORS
Compile-time (syntax) errors
The compiler will find syntax errors and other basic
problems
An executable version of the program is not created
Ex: ??
Run-time errors
A problem can occur during program execution
Causes the program to terminate abnormally
Ex: ??
26
3 TYPES OF ERRORS …
Logical (semantic) errors… aka a bug
A mistake in the algorithm
Compiler cannot catch them
A program may run, but produce incorrect results
Ex: ??
The process of eliminating bugs is called debugging
(who found the first bug?)
Grace Hooper (1906-1992)
American Computer Scientist
& US Navy Admiral
27
DETECTING ERRORS ….
The hardest kind of error to detect in a computer program is a:
A) Syntax error
B) Run-time error
C) Logic error
D) All of the above
C
Output
28
BASIC PROGRAM DEVELOPMENT
Edit and
save program
Compilation
errors
Compile program
Run-time &
logical
errors
Execute program and
evaluate results
29
DEVELOPMENT ENVIRONMENTS
Basic compiler & interpreter
Sun Java Development Kit (JDK) -- download from Sun
Compiler:
javac Hello.java
The result is a byte-code program called: Hello.class
Interpreter:
java Hello
30
DEVELOPMENT ENVIRONMENTS
IDE (Integrated Development Environment)
Eclipse
JCreator
Borland JBuilder
Microsoft Visual J++
… see course Web site to download them
In tutorial 1, you will edit, compile and run
Hello.java
31
TYPES OF JAVA PROGRAMS
In Java, we have 2 types of programs:
1. applications
"autonomous applications" or stand-alone program
executed by the local OS (through the Java Virtual
Machine)
can use graphics and GUI or just plain console I/O
must have a main method
what we will see in COMP 248
ex: FirstProgram.java
32
TYPES OF JAVA PROGRAMS …
2. applets
"internet applications"
executed by a Web browser (through the Java Virtual
Machine)
must be inserted into an HTML page
must use a GUI
ex: PocketCalc.java + Calculator.html
33
CHAP 1: JAVA FUNDAMENTALS
COMP 248:
Object Oriented Programming I
TOPICS …
1. Comments
2. Identifiers
3. Indentation
4. Primitive Types
5. Variables
6. Output
7. Assignment
8. Arithmetic Expressions
9. More Assignment Operators
10. Assignment Compatibility
11. Strings
35
TEMPLATE OF A SIMPLE JAVA PROGRAM
//**************************************************
// comments on the program (authors, purpose, …)
//**************************************************
public class SomeIdentifier
{
//----------------------------------------------// comments on the main method
//----------------------------------------------public static void main (String[] args)
{
// declarations of variables and constants
// statements of the main method
}
}
SomeIdentifier.java
36
1- COMMENTS
also called inline documentation
used to explain the purpose of the program and describe
processing steps (the algorithm)
do not affect how a program works (are ignored by the
compiler)
can take 3 forms:
// this comment runs to the end of the line
/*
this comment runs to the terminating
symbol, even across line breaks
*/
/** this is a javadoc comment
*/
37
2- IDENTIFIERS
are the words a programmer uses in a program to name
variables, classes, methods, …
Rules to create an identifier:
can be made up of:
letters,
digits,
the underscore character (_),
and the dollar sign ($)
cannot begin with a digit
cannot be a reserved word
no limit on length
38
VALID IDENTIFIER?
Which of the following is not a valid identifier?
A) abc
B) ABC
C) Abc
D) aBc
E
E) a bc
Output
39
VALID IDENTIFIER?
Which of the following is not a valid identifier?
A) a_bc
B) A$BC
C) _Abc
D) 1AbC
D
E) $abc
Output
40
IDENTIFIERS
Guidelines:
give a significant name!
avoid
by
'$‘
convention:
class
names --> use title case
ex: MyClass, Lincoln
constants
ex: MAXIMUM
variables,
--> use upper case
methods, … --> start with lowercase
ex: aVar, a_var
41
IDENTIFIERS
Avoid Predefined identifiers:
Although they can be redefined, it is confusing and
dangerous
System
String
println
Remember: Java is case sensitive
42
JAVA RESERVED WORDS
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
43
EXAMPLES
Identifier
GST
Correct or not?
PriceBeforeTax
Correct
Student_3
Correct
student#3
Not Correct
Shipping&HandlingFee
Not Correct
Class
Correct
__123
Correct
the account
Not Correct
1floor
Not Correct
Correct
44
3- INDENTATION
Spaces, blank lines, and tabs are called white space
White space is used to separate words and symbols in a
program
Extra white space is ignored
Programs should be formatted to enhance readability,
using consistent indentation
45
EXAMPLE 1: BAD INDENTATION
//******************************************************
// Lincoln2.java
// Demonstrates a poorly formatted, though valid,
// Program.
//******************************************************
public class Lincoln2{public static void
main(String[]args){
System.out.println("A quote by Abraham Lincoln:");
System.out.println("Whatever you are, be a good one.");}}
46
EXAMPLE 2: BAD INDENTATION
//********************************************************************
// Lincoln3.java
// Demonstrates another valid program that is poorly formatted.
//********************************************************************
public
class
Lincoln3
{
public
static
void
main
(
String
[]
args
)
{
System.out.println
(
"A quote by Abraham Lincoln:"
)
;
System.out.println
(
"Whatever you are, be a good one."
)
;
}
}
47
EXAMPLE 3: GOOD INDENTATION
//*****************************************************
// Lincoln3.java
// Demonstrates a properly formatted program.
//*****************************************************
public class Lincoln3
{
public static void main(String[]args)
{
System.out.println("A quote by Abraham Lincoln:");
System.out.println("Whatever you are, be a good one.");
}
}
48
4- PRIMITIVE TYPES
8 primitive data types in Java
Numeric
4
types to represent integers (ex. 3, -5):
2
byte, short, int, long
types to represent floating point numbers (ex. 3.5):
float, double
Characters
(ex. 'a')
char
Boolean
values (true/false)
boolean
49
NUMERICAL TYPES
The difference between:
byte, short, int, long AND float, double
is their size (so the values they can store)
50
NUMERICAL TYPES …
The difference between:
byte, short, int, long AND float, double
is their size (so the values they can store)
51
PITFALL: ROUND-OFF ERRORS IN FLOATINGPOINT NUMBERS
Floating point numbers are only approximate
quantities
Mathematically, the floating-point number 1.0/3.0 is
equal to 0.3333333. . .
A computer may store 1.0/3.0 as something like
0.3333333333
52
CHARACTERS
A char stores a single character
delimited by single quotes:
'a'
'X'
'7'
'$'
','
'\n'
characters are ordered according to a character set
each character corresponds to a unique number code
Java uses the Unicode character set
16 bits per character, so 65,536 possible characters
Unicode is an international character set, containing
symbols and characters from languages with different
alphabets
53
CHARACTERS
The ASCII character set is older and smaller than Unicode, but is still
popular
The ASCII characters are a subset of the Unicode character set,
including:
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
’A’, ’B’, ’C’, …
’a’, ’b’, ’c’, …
’. ’, ’; ’, …
’0’, ’1’, ’2’, …
’&’, ’|’, ’\’, …
’\n’, ’\t’, …
54
BOOLEANS
A boolean value represents a true or false expression
The reserved words true and false are the only
valid values for a boolean type
NOT… 0 and 1
55
5- VARIABLES
a name for a location in memory
used to store information (ex. price, size, …)
must be declared before it is used
indicate the variable's name
indicate the type of information it will contain
declaration can be anywhere in the program (but before its first
access)
variable name
data type
int total;
int count, temp, result;
Multiple
variables can
be created in
one declaration
56
TIP: INITIALIZE VARIABLES
A variable that has been declared but has not yet been
given a value is said to be uninitialized
In certain cases an uninitialized variable is given a default
value
It is best not to rely on this
Explicitly initialized variables have the added benefit of
improving program clarity
57
INITIALIZATION AT DECLARATION
A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;
When a variable is used in a program, its current value
is used
58
EXAMPLE
//************************************************************
// PianoKeys.java
//
// Demonstrates the declaration and initialization of an
// integer variable.
//***********************************************************
public class PianoKeys
{
// Prints the number of keys on a piano.
public static void main (String[] args)
{
int keys = 88;
System.out.println("A piano has " + keys + “ keys.");
}
}
filename??
A piano has 88 keys.
Output
59
CONSTANTS
similar to a variable but can only hold one value while the
program is active
the compiler will issue an error if you try to change the value of a
constant during execution
use the final modifier
final int MIN_AGE = 18;
Constants:
give names to otherwise unclear literal values
facilitate updates of values used throughout a program
prevent inadvertent attempts to change a value
60
6- OUTPUT
System.out.print
Displays what is in parenthesis
System.out.println
Displays what is in parenthesis
Advances to the next line
System.out.print("hello");
System.out.print("you");
helloyouhello
you
System.out.println("hello");
System.out.println("you");
50L
Output
System.out.println();
int price = 50;
System.out.print(price);
char initial = 'L';
System.out.println(initial);
61
MULTIPLE OUTPUT
System.out.println("hello" + "you");
double price = 9.99;
int nbItems = 5;
System.out.println("total = " + price*nbItems + "$");
Helloyou
Total = 49,95$
Output
in print and println, + is the concatenation…
you need parenthesis for the + to be addition
int x = 1, y = 2;
System.out.println("x+y="+x+y);
System.out.println("x+y="+(x+y));
x+y=3
x+y=3
Output
62
MULTIPLE OUTPUT …
cannot cut a string over several lines
System.out.println("this is a
long string"); // error!
System.out.println("this is a" +
"long string"); // ok
63
ESCAPE SEQUENCES
System.out.println ("I said "Hi" to her.");
to print a double quote character
Syntax error on token "Hi",
invalid Assignment Operator
Use an escape sequence
Output
sequence is a series of characters that represents a special
character
begins with a backslash character (\)
considered as 1 single character
System.out.println ("I said \"Hi\" to her.");
I said "Hi" to her
Output
64
ESCAPE SEQUENCES
Some Java escape sequences:
Escape Sequence
Meaning
\b
\t
\n
\"
\'
\\
backspace
tab
newline
double quote
single quote
backslash
65
YOU TRY
What will the following statement output?
System.out.print("one\ntwo\nthree\n");
A) one two three
B) one\ntwo\nthree\n
C) "one\ntwo\nthree\n"
D) one
two
three
E) onetwothree
D
Output
66
YOU TRY
What statement will result in the following output?
Read the file "c:\windows\readme.txt"
D
Output
System.out.print
A) ("Read the file "c:\windows\readme.txt");//Error
B) ("Read the file "c:\windows\readme.txt"");//Error
C) ("Read the file "c:\\windows\\readme.txt");//Error
D) ("Read the file \"c:\\windows\\readme.txt\""); //OK
E) ("Read the file \"c:\windows\readme.txt\"");//Error
F) Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
67
7- ASSIGNMENT (P. 16)
Used to change the value of a variable
The assignment operator is the = sign
total = 55;
Syntax: Variable = Expression;
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
68
EXAMPLE
public class Geometry
{
// Prints the number of sides of
public static void main (String[]
{
int sides = 7; // declaration
System.out.println("A heptagon
several geometric shapes.
args)
with initialization
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???
A heptagon has 7 sides
A decagon has 10 sides
A dodecagon has 12 sides
Output
69
DIFFERENCE WITH THE MATH =
In Java, = is an operator
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;
70
EXAMPLES
Declarations:
int x;
int y = 10;
char c1 = ’a’;
char c2 = ’b’;
Statements:
x = 20+5;
y = x;
c1 = ’x’;
c2 = c1;
71
SWAP CONTENT OF 2 VARIABLES
Write a series of declarations & statements to swap the value
of 2 variables…
int x = 10; int y = 20;
A) x = y; y = x; // x=20; y=20 Swap is not correct
B) y = x; x = y; // y=20; x=20 Swap is not correct
C) Both A) & B) will work
D) Neither A) nor B) will work
D
Output
72
8- ARITHMETIC EXPRESSIONS
An expression is a combination of one or more
operands and their operators
Arithmetic operators:
Addition
Subtraction
Multiplication
Division
Remainder
+
*
/
%
73
DIVISION AND REMAINDER …
the division operator (/) can be:
Integer division
if
both operands are integers
10 / 8
8 / 12
equals?
equals?
1
0
Real division
otherwise
10.0 / 8
8 / 12.0
equals?
equals?
1.25
0.6667
74
DIVISION AND REMAINDER
the remainder operator (%)
returns the remainder after the integer division
10 % 8
8 % 12
equals?
equals?
2
8
(10÷8 = 1 remainder 2)
75
OPERATOR PRECEDENCE (P 24)
Operators can be combined into complex expressions
result
=
total + count / max - offset;
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
76
OPERATOR ASSOCIATIVITY
Unary operators of equal precedence are grouped right-toleft
+-+rate is evaluated as +(-(+rate))
Binary operators of equal precedence are grouped left-toright
base + rate + hours is evaluated as
(base + rate) + hours
Exception: A string of assignment operators is grouped
right-to-left
n1 = n2 = n3; is evaluated as n1 = n2 = n3;
77
EXAMPLE
What is the order of evaluation in the following
expressions?
a + b + c + d + e
a + b * c - d / e
(a)
(b)
a / (b + c) - d % e
(c)
a / (b * (c + (d - e)))
(d)
(d) (c) (b) (a)
Output
78
ASSIGNMENT REVISITED
The assignment operator has a lower precedence than
the arithmetic operators
First the expression on the RHS is evaluated
answer
=
4
sum / 4 + MAX * lowest;
2
3
1
Then the result is stored in the
variable on the LHS
79
YOU TRY
What is stored in the integer variable num1 after this statement?
num1 = 2 + 3 * 5 - 5 * 2 / 5 + 10 ;
1
2
3
4
5
6
A) 0
B) 18
C) 25
D) 10
C
Output
80
LET’S PUT IT ALL TOGETHER
Purpose:
Algorithm:
1.
2.
3.
Conversion of degrees Fahrenheit in degrees Celsius
Assign the temperature in Fahrenheit (ex. 100 degrees)
Calculate the temperature un Celsius (1 Celsius = 5/9 (Fahr – 32)
Display temperature in Celsius
Variables and constants:
Data
Identifier
Type
var or const?
Temperature in Fahrenheit
fahr
double
var
Temperature in celsius
celsius
double
var
81
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
double fahr, celsius;
Scanner sc = new Scanner(System.in);
// step 1: Assign the temperature in Fahrenheit (100)
System.out.println("Enter temperatue in Fahrenheit = ");
fahr = sc.nextInt(); // OR fahr = 100;
// step2: Calculate the temperature un Celsius
celsius = ((fahr - 32)*5)/9;
// step3: Display temperature in Celsius
System.out.println("Temperatue in Celsius = " + celsius);
}
}
filename???
82
9- MORE ASSIGNMENT OPERATORS
in addition to =
often we perform an operation on a variable, and then store the
result back into that variable
Java has shortcut assignment operators:
variable = variable operator expression;
variable operator= expression;
Operator
+=
-=
*=
/=
%=
Example
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
Equivalent To
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
83
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);
84
ASSIGNMENT OPERATORS
The behavior of some assignment operators depends on
the types of the operands
ex: the +=
If the operands are strings, += performs string
concatenation
The behavior of += is consistent with the behavior of the
"regular" +
85
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
15
100.0
hellobye
The operator *= is undefined for the
argument type(s) java.lang.String
86
INCREMENT AND DECREMENT
In Java, we often add-one or subtract-one to a variable…
2 shortcut operators:
The increment operator (++) adds one to its operand
The decrement operator (--) subtracts one from its
operand
The statement: count++;
is functionally equivalent to: count = count+1;
The statement: count--;
is functionally equivalent to: count = count-1;
87
INCREMENT AND DECREMENT
The increment and decrement operators can be in:
1.
in prefix form - ex: ++count;
1.
2.
2.
the variable is incremented/decremented by 1
the value of the entire expression is the new value of the
variable (after the incrementation/decrementation)
in postfix form: - ex: count++;
1.
2.
the variable is incremented/decremented by 1
the value of the entire expression is the old value of the
variable (before the incrementation/decrementation)
88
EXAMPLE
int nb = 50;
++nb;
nb = 51
int nb = 50;
nb++;
value of nb
value of nb
int nb = 50;
int x;
x = ++nb;
nb = 51
x = 51
nb = 50
int nb = 50;
int x;
x = nb++;
x = 50
nb = 51
value of nb & x
value of nb & x
int nb = 50;
int x;
x = nb++ + 10;
x = 60
nb = 51
value of nb & x
89
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
D
Output
90
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
// q = 2 *10+3 x = 2; y = 9; z = 4
D) No idea???
C
Output
91
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 1 + 1
B) a = 1, c = 3
C) a = 3, c = 3
D) No idea???
A
Output
92
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 //a=1 + a=2 + 2*b=1 + 3/b=1
C) 8.5
D) No idea???
B
Output
93
SUMMARY OF ++ AND - Expression Operation
Value Used in Expression
count++
add 1
++count
add 1
count-- subtract 1
--count subtract 1
old value
new value
old value
new value
94
10 - ASSIGNMENT COMPATIBILITY
In general, the value of one type cannot be stored in a
variable of another type
int intVariable = 2.99; //Illegal
However, there are exceptions to this
double doubleVariable = 2;
For example, an int value can be stored in a double type
95
ASSIGNMENT COMPATIBILITY
an expression has a value and a type
2 / 4
(value = 0, type = int)
2 / 4.0 (value = 0.5, type = double)
the type of the expression depends on the type of its
operands
In Java, type conversions can occur in 3 ways:
arithmetic promotion
assignment conversion
casting
96
ARITHMETIC PROMOTION
happens automatically, if the operands of an expression are
of different types
aLong + anInt * aDouble
operands are promoted so that they have the same type
promotion rules:
if 1 operand is of type… the others are promoted to…
double
float
long
double
float (double)
long
short, byte and char are always converted to int
97
EXAMPLES
(aByte + anotherByte)
--> int
(aLong + anInt * aDouble) --> double
(aFloat - aBoolean)
--> The operator - is undefined for the
argument type(s) int, boolean
value and type of these expressions?
2 / 4
int / int
int
2/4
0
98
EXAMPLES
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)
B
Output
99
EXAMPLES
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)
D
Output
100
ASSIGNMENT CONVERSIONS
occurs when an expression of one type is assigned to a variable of
another type
var = expression;
widening conversion
if the variable has a wider type than the expression
then, the expression is widened automatically
long aVar;
aVar =
5+5;
byte aByte;
int anInt;
anInt = aByte;
double aDouble;
int anInt = 10;
aDouble = anInt;
integral & floating point types are compatible
boolean are not compatible with any type
101
ASSIGNMENT CONVERSIONS
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? No cannot convert double to int
int aVar;
aVar = 10/4; ok? Yes = 2
int aVar;
aVar = 10.0/4; ok?No cannot convert from double to int
102
CASTING
the programmer can explicitly force a type conversion
syntax: (desired_type) expression_to_convert
int aVar;
aVar = (int)3.7;
(aVar is 3… not 4!)
byte aByte;
int anInt = 75;
aByte = anInt; // ok? No, cannot convert from int to byte
aByte = (byte)anInt; // ok? Yes
double d;
d = 2/4; // d is 0.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…
103
EXAMPLES
Which of the following assignment statements are valid?
byte b1 = 1, b2 = 127, b3;
b3 = b1 + b2; // statement a) : cannot convert from int to byte
Solution : b3 = (byte) (b1 + b2);
b3 = 1 + b2; // statement b) : cannot convert from int to byte
Solution : b3 = (byte) (1 + b2);
b3 = (byte)1 + b2; // statement c) cannot convert from int to byte
Solution : b3 = (byte) ((byte)1 + b2);
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
E
Output
104
11- STRINGS
so far we have seen only primitive types
a variable can be either:
a primitive type
or a reference to an object
ex: int, float, boolean, …
ex: String, Array, …
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
105
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
106
DECLARING STRINGS
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";
These special syntax works only for strings
107
STRINGS
once a string is created, its value cannot be modified (the object
is immutable)
cannot lengthen/shorten it
cannot modify its content
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 p. 38
…
108
STRING INDEXES START AT ZERO
109
EXAMPLE
public class StringTest {
public static void main (String[] args) {
String string1 = new String ("This is a string");
String string2 = "";
String string3, string4, string5;
System.out.println("Content of string1 :
System.out.println("Length of string1 :
System.out.println("Content of string2 :
System.out.println("Length of string2 :
\"" + string1 + "\"");
" + string1.length());
\"" + string2 + "\"");
" + string2.length());
Output
Content of string1 : "This is a string"
Length of string1 : 16
Content of string2 : ""
Length of string2 : 0
110
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);
System.out.println(string3);
System.out.println(string4);
System.out.println(string5);
} }
Output
This is a string hello
THIS IS A STRING HELLO
THIS IS A STRING HXLLO
S IS A
111