IFI7184.DT – Lesson 2
Variables and types
@ slides adapted from Isaías da Rosa sources
Overview
• On todays lesson condition statements
– Variables and Types
• Variables and Assignment
– Primitive Data Types
– Complex data Types
– The Data Conversion
– Expressions
– Interactive Programs
– Creating Objects
22015 @ Sonia Sousa
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
3@ Sonia Sousa2015
Everything is an object
• In java as you design your applications
– You place your code inside of Class definitions
• Inside you add your Function
– Known as method
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
4
Executable code
Function
Class definition
Everything is an object
public class HelloWorld{
public static void main(String[] args) {
sayHello();
}
public static void sayHello() {
String w = new String("hello");
System.out.println( w );
}
}
5
Executable code
Function
Class definition
Executable code
Instance variable
Class instance
Object oriented Language
State
Variables (fields)
behaviours
functions (methods)
that allow to change the state
Function to change the gear (bicycle has 3 gears)
@ Sonia Sousa 62015
System.out.println( w );
String w = "hello";
What Is a Class?
• A Class represent 1 object (Myfirstprogram)
Instance
Of
class of objects
@ Sonia Sousa 72015
object
public class HelloWorld{
public static void main(String[] args) {
sayHello();
}
public static void sayHello() {
String w = new String("hello");
System.out.println( w );
}
}
What Is a Inheritance?
• Class of objects that inherit characteristics
of another object
inherit
characteristics
class of objects known as
Superclass of objects known
as specific characteristic
public class HelloWorld {
public static void main(String[] args) {
sayHello();
}
public static void sayHello() {
String w = "hello";
System.out.println( w );
}
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
9@ Sonia Sousa2015
Variables
• A variable is a name for a location in memory that holds a value
• Primitive data
– Numerical
• Integers: byte, short, int,
long
• Floating point decimals:
float, double
– Characters:
• Not complete strings: char
– Boolean values:
• Boolean: True or false
• Complex object
– Declare as instance of a
data class
• String
• Date
• Everything else
10
Declare variables
• You need to specify
– 3 parts:
• Data type
• Variable name
– Lower case or Underscore _
– not numerical
• Initial value
– optional
11
Type
Byte, short, int, long
Float, double
data type variable name
int total;
Variable Initialization
12
int sum = 0;
int base = 32, max = 149;
data type variable name Initiate variable
@ Sonia Sousa2015
Multiple variables can be created in one declaration
int count, temp, result;
Complex object
• Declaration
– Instance of a class
– Primitives we declare 3 parts
• Data type
• Variable name
• Initial value: build from class constructor
13
data type variable name Initiate variable from constructor
String w = new String(c);
Declare variables
• Inside the function
– Finish execute -> the variable goes away
• Outside the function
14
public static void sayHello() {
String w = "hello”;
System.out.println( w );
}
public static void sayHello() {
String w = "hello”;
}
System.out.println( w );
Characters
• A char variable stores a single character
• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' 'n'
• Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
• Note the difference between
– a primitive character variable, which holds only one
character, and
– a String object, which can hold multiple characters
2015 @ Sonia Sousa 15
Output character
public class Character {
public static void main(String[] args) {
char[] c = {'h','e','l','l','o'};
char c1 = 'h';
char c2 = ‘e';
char c3 = ‘l';
char c4 = ‘l';
char c5 = ‘o’;
System.out.println( c );
}
}
16
Boolean
• A boolean value represents a true or false
condition
• The reserved words true and false are
the only valid values for a boolean type
boolean done = false;
• A boolean variable can also be used to
represent any two states, such as a light bulb
being on or off
2015 @ Sonia Sousa 17
Boolean
public class Charecter {
public static void main(String[] args) {
boolean done1 = true;
boolean done2 = false;
boolean done3 = !done1;
System.out.println( "Did you finish the exercise? " + done1);
System.out.println( "The exercise is done " + done2);
System.out.println( "Is it done now? " + done3);
}
}
18
!Is a logical complement operator;
inverts the value of a boolean
Output primitive values
• Any value can be outputted as a string
– Using the concatenation value +
19
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.");
}
}
Output
A piano has 88 keys.
Output values
public static void main(String[] args) {
char charVal = 'c';
boolean booleanVal =true;
short shortVal = 127;
int intVal = 32000;
long longVal = 2000000L;
float floatval = 10000000f;
double doubleVal= 112321231221.23d;
System.out.println( "character value is " + charVal);
System.out.println(booleanVal);
System.out.println( "short value is " + shortVal);
System.out.println( "Integer value is " + intVal);
System.out.println( "long value is " + longVal);
System.out.println(doubleVal);
System.out.println(floatval + " float value " );
System.out.println( "double value is " + doubleVal);
} 20
Output
character value is c
true
short value is 127
Integer value is 32000
long value is 2000000
1.1232123122123E11
1.0E7 float value
double value is
1.1232123122123E11
Output complex objects
import java.util.Date;
public class Complex{
public static void main(String[] args) {
Date myDate = new Date();
String myString = new String("Hello");
System.out.println(myString);
System.out.println( "My date is " + myDate);
}
}
21
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
22@ Sonia Sousa2015
Data Conversion
• Sometimes it is convenient to convert data
– from one type to another
• For example,
– to treat an integer as a floating point value
– Or a short to an int
• You can do two type of conversions
– Downwards
• You don’t loose data
– Upwards
• You loose data
– Promotion
23
Data Conversion
Downwards Upwards
24
Type
double
float
long
int
short
byte
Type
double
float
long
int
short
byte
Numeric Primitive Data
• The difference between the numeric
primitive types is their size and the values
they can store:
2015 @ Sonia Sousa 25
Type
byte
short
int
long
float
double
Storage
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
Min Value
-128
-32,768
-2,147,483,648
< -9 x 1018
- 3.4 x 1038 3.4 x 1038
- 1.7 x 10308 1.7 x 10308
Max Value
127
32,767
2,147,483,647
> 9 x 1018
Upward Conversion
• Or Assignment conversion occurs
– when a value is assigned to a variable of
another
• Example:
int dollars = 20;
double money = dollars;
• Only Upward conversions can happen via
assignment
– the value or type of dollars did not change
26
Convert primitive data type
• From a data type to another (upward)
27
Type
double
float
long
int
short
byte
public class Converting{
public static void main(String[] args) {
int intVal=120;
double convertIn= intVal;
System.out.println( "Integer value is " + intVal);
System.out.println( "Double value is " +
convertIn);
}
}
Output
Integer value is 120
Double value is 120.0
Downwards conversion
• Casting or downwards conversion
– is the most powerful, and dangerous, technique for
conversion
– This conversions happen if you explicitly cast a value
• To cast, you put in parentheses in front of the value being
converted
– Example
double doubleVal= 3.99;
int convertVal= (int)doubleVal;
– You might lose information
28
Convert primitive data type
• From a data type to another (downward)
29
Type
double
float
long
int
short
byte
public class Converting{
public static void main(String[] args) {
double doubleVal= 3.99;
int convertVal= (int)doubleVal;
System.out.println( "Double value is " + doubleVal);
System.out.println( "Integer value is " + convertVal);
}
}
Output
Double value is 3.99
Integer value is 3
Convert primitive data type
• From a data type to another (downward)
30
Type
Double
byte
public class Converting{
public static void main(String[] args) {
double doubleVal= 128;
byte convertVal= (byte)doubleVal;
System.out.println( "Double value is " + doubleVal);
System.out.println( ”Byte value is " + convertVal);
}
}
Output
Double value is 128.0
Byte value is -128
Promotion
• Promotion happens automatically
– When you use 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
31
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
32@ Sonia Sousa2015
Simple calculation applications
• Type of operators
– Simple assignment
• Assignment values
– Complex assignment
• Combine assignment and
math in a single
expression
– Equality and relation
• Compare values to each
other
– Mathematical
• Execute common
mathematical processes
– Conditional operators
• Define complex
conditional processes
33
int count = 12;
double sum = 490.27;
result = sum / count;
data type variable name Simple assign
Complex assign
Math operators
• An expression is a combination of one or
more operators and operands
• Arithmetic or math expressions compute
numeric results:
34
Addition
Subtraction
Multiplication
Division
Remainder
+
-
*
/
%
• If either or both operands are floating point values,
then the result is a floating point value
Promotion
• Promotion happens automatically
– When you use 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
35
Division and Remainder
• If both operands to the division operator (/) are
integers
– the result is an integer (the fractional part is discarded)
14 / 3 equals 4
8 / 12 equals 0
• The remainder operator (%) returns the remainder after
dividing the first operand by the second
14 % 3 equals 2
8 % 12 equals 8
36
Quick Check
What are the results of the following expressions?
12 / 2
12.0 / 2.0
10 / 4
10 / 4.0
4 / 10
4.0 / 10
12 % 3
10 % 3
3 % 10
37
Quick Check
What are the results of the following expressions?
public static void main(String[] args) {
int valueDiv = 12;
double result1 =valueDiv/2;
double result2 = 12.0 / 2.0;
…
double result7 = 12 % 3;
double result8 = 10 % 3;
double result9 = 3 % 10;
System.out.println(result1);
System.out.println(result2);
…
System.out.println(result7);
System.out.println(result8);
System.out.println(result9);
System.out.println("The end :)");
}
38
Output
= 6
= 6.0
= 2
= 2.5
= 0
= 0.4
= 0
= 1
= 0
Operator Precedence
• Operators can be combined into larger expressions
result = total + count / max - offset;
• Operators have precedence
– determines the order in which they are evaluated
• First:
– Multiplication, division, and remainder
• Second:
– addition, subtraction, and string concatenation
• Same precedence
– left to right,
• Exception
– Using parentheses
• force the evaluation order
39
Quick Check
40
a + b + c + d + e a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
In what order are the operators evaluated in the
following expressions?
Values a =1; b = 12; c = 10; d =4; e = 3;
Quick Check
a + b + c + d + e a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
1 432 3 241
2 341
4 123
In what order are the operators evaluated in the
following expressions?
41
Quick Check
What are the results of the following expressions?
int a =1;
int b = 12;
int c = 10;
int d =4;
int e = 3;
double result1 =a+b+c+d+e;
double result2 =a + b * c - d / e;
double result3 =a / (b + c) - d % e;
double result4 = a / (b * (c + (d - e)));
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
System.out.println(result4);
System.out.println("The end :)"); }
42
Output
= 30.0
= 120.0
= -1.0
0.0The end :)
Assignment Revisited
• The assignment operator has a lower
precedence than the arithmetic operators
First the expression on the right hand
side of the = operator is evaluated
Then the result is stored in the
variable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
43
Assignment Revisited
• 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
Then the result is stored back into count
(overwriting the original value)
count = count + 1;
44
Increment and Decrement
• The increment (++) operator
– The statement
count++;
count = count + 1;
• The decrement (--) operator
count--;
count = count - 1;
45
Increment and Decrement
• Postfix syntax:
– Evaluated value first then make the mathematical operation
count++
• Prefix syntax:
– mathematical operation first then evaluated value
++count
• ! When used as part of a larger expression !
– the two forms can have different effects
• The subtleties, of increment and decrement operators
– should be used with care
46
Assignment Operators
• Often we perform an operation on a variable, and
then store the result back into that variable
• Java provides assignment operators to simplify
that process
• For example, the statement
num += count;
is equivalent to
num = num + count;
47
Quick Check
What are the results of the following expressions?
Start with intValue =10
Calculate
++
--
+=5
-=5
/=5
++ intValue
-- intValue
48
Assignment Operators
• The right hand side of an assignment
operator can be a complex expression
• The entire right-hand expression is evaluated
first, then the result is combined with the
original variable
• Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
49
Assignment Operators
• 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 (+)
50
Assignment Operators
• There are many assignment operators in
Java, including the following:
Operator
+=
-=
*=
/=
%=
Example
x += y
x -= y
x *= y
x /= y
x %= y
Equivalent To
x = x + y
x = x - y
x = x * y
x = x / y
x = x % y
51
Quick Check
What are the results of the following expressions?
int intValue =10;
int newValue1 =++ intValue;
int newValue2 =-- intValue;
System.out.println(intValue ++);
System.out.println(intValue --);
System.out.println(intValue +=5);
System.out.println(intValue -=5);
System.out.println(intValue /=5);
System.out.println(newValue1);
System.out.println(newValue2);
System.out.println("The end :)"); }
52
Output
= 10
= 11
= 15
= 10
= 2
= 11
= 10
The end :)
Comparative values
53
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for
if-then-else statement)
Be careful
When comparing strings
This will not work
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
54@ Sonia Sousa2015
Interactive Programs
• Programs generally need input on which to operate
• Scanner class
– provides the 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
• To read Keyboard input
– Use the System.in object
55
Reading Input
• Create 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();
56
Reading Input
• The Scanner class is part of the
– java.util class library
– Import class java.util library
• This class library 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
57
//********************************************************************
// 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 + """);
}
}
58
//********************************************************************
// 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
Enter a line of text:
You want fries with that?
You entered: "You want fries with that?"
59
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
60
//********************************************************************
// 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 based on values entered by the
// user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int miles;
double gallons, mpg;
Scanner scan = new Scanner (System.in);
continue
61
continue
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);
}
}
62
continue
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
Enter the number of miles: 328
Enter the gallons of fuel used: 11.2
Miles Per Gallon: 29.28571428571429
63
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
64@ Sonia Sousa2015
Creating Objects
• Primitive data type vs objects
– Objects can be used to represent real-world
entities (see the top slides)
• For instance, an object
– represent a particular employee in a company
» Each employee object
• handles specific information
• related to that employee
65
Creating Objects
• An object has:
– state (attributes)
• descriptive characteristics
– behaviors
• what it can do (or what can be done to it)
66
BankAcount
AccounNumber
Name
Balance
Deposit
Withrow
Transfer
State
behaviours
Creating Objects
• An object has:
– state (attributes) - bankAcount
– AccountNumber
– Name
– Balance
• descriptive characteristics
– behaviors (what he can do)
– Desposit
– Withrow
– Tranfer
• the ability to make deposits and withdrawals
• Note that the behavior of an object might change its
state 67
BankAcount
AccounNumber
Name
Balance
Deposit
Withrow
Transfer
Classes
• An object is defined by a class
– A class is the blueprint of an object
• The class uses methods
– to define the behaviors of the object
• The class contains the main method of a Java
program
– represents the entire program
• A class represents a concept
• An object represents the embodiment of that concept
• Multiple objects can be created from the same class
68
Class = Blueprint
• One blueprint to create several similar, but
different, houses:
69
Objects and Classes
Bank
Account
A class
(the concept)
John’s Bank Account
Balance: $5,257
An object
(the realization)
Bill’s Bank Account
Balance: $1,245,069
Mary’s Bank Account
Balance: $16,833
Multiple objects
from the same class
70
Creating Objects
• A variable holds either a primitive value or a
reference to an object
• A class name can be used as a type to
declare an object reference variable
String title;
• No object is created with this declaration
• An object reference variable holds the
address of an object
• The object itself must be created separately
71
Creating Objects
• Generally, we use the new operator to
create an object
• Creating an object is called instantiation
• An object is an instance of a particular
class
72
title = new String ("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
Invoking Methods
• We've seen that once an object has been
instantiated, we can use the dot operator
to invoke its methods
numChars = title.length()
• A method may return a value, which can
be used in an assignment or expression
• A method invocation can be thought of as
asking an object to perform a service
73
References
• Note that a primitive variable contains the
value itself, but an object variable contains
the address of the object
• An object reference can be thought of as a
pointer to the location of the object
• Rather than dealing with arbitrary addresses,
we often depict a reference graphically
74
"Steve Jobs"name1
num1 38
Assignment Revisited
• The act of assignment takes a copy of a
value and stores it in a variable
• For primitive types:
75
num1 38
num2 96
Before:
num2 = num1;
num1 38
num2 38
After:
Reference Assignment
• For object references, assignment copies
the address:
76
name2 = name1;
name1
name2
Before:
"Steve Jobs"
"Steve Wozniak"
name1
name2
After:
"Steve Jobs"
Aliases
• Two or more references that refer to the
same object are called aliases of each other
• That creates an interesting situation: one
object can be accessed using multiple
reference variables
• Aliases can be useful, but should be
managed carefully
• Changing an object through one reference
changes it for all of its aliases, because there
is really only one object
77
Garbage Collection
• When an object no longer has any valid
references to it, it can no longer be accessed
by the program
• The object is useless, and therefore is called
garbage
• Java performs automatic garbage collection
periodically, returning an object's memory to
the system for future use
• In other languages, the programmer is
responsible for performing garbage collection
78
Outline
Review Object-oriented concepts
Variables and Types
Variables and Assignment
Primitive Data Types
Data Conversion
Expressions
Interactive Programs
Creating Objects
String class
79@ Sonia Sousa2015
The String Class
• Because strings are so common, we don't
have to use the new operator to create a
String object
title = "Java Software Solutions";
• This is special syntax that works only for
strings
• Each string literal (enclosed in double quotes)
represents a String object
80
String Methods
• Once a String object has been created,
neither its value nor its length can be
changed
• Therefore we say that an object of the
String class is immutable
• However, several methods of the String
class return new String objects that are
modified versions of the original
81
String Indexes
• It is occasionally helpful to refer to a
particular character within a string
• This can be done by specifying the
character's numeric index
• The indexes begin at zero in each string
• In the string "Hello", the character 'H' is
at index 0 and the 'o' is at index 4
• See StringMutation.java
82
//********************************************************************
// StringMutation.java Author: Lewis/Loftus
//
// Demonstrates the use of the String class and its methods.
//********************************************************************
public class StringMutation
{
//-----------------------------------------------------------------
// Prints a string and various mutations of it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String phrase = "Change is inevitable";
String mutation1, mutation2, mutation3, mutation4;
System.out.println ("Original string: "" + phrase + """);
System.out.println ("Length of string: " + phrase.length());
mutation1 = phrase.concat (", except from vending machines.");
mutation2 = mutation1.toUpperCase();
mutation3 = mutation2.replace ('E', 'X');
mutation4 = mutation3.substring (3, 30);
continued
83
continued
// Print each mutated string
System.out.println ("Mutation #1: " + mutation1);
System.out.println ("Mutation #2: " + mutation2);
System.out.println ("Mutation #3: " + mutation3);
System.out.println ("Mutation #4: " + mutation4);
System.out.println ("Mutated length: " + mutation4.length());
}
}
84
continued
// Print each mutated string
System.out.println ("Mutation #1: " + mutation1);
System.out.println ("Mutation #2: " + mutation2);
System.out.println ("Mutation #3: " + mutation3);
System.out.println ("Mutation #4: " + mutation4);
System.out.println ("Mutated length: " + mutation4.length());
}
}
Output
Original string: "Change is inevitable"
Length of string: 20
Mutation #1: Change is inevitable, except from vending machines.
Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES.
Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS.
Mutation #4: NGX IS INXVITABLX, XXCXPT F
Mutated length: 27
85
Quick Check
What output is produced by the following?
String str = "Space, the final frontier.";
System.out.println (str.length());
System.out.println (str.substring(7));
System.out.println (str.toUpperCase());
System.out.println (str.length());
86
Quick Check
What output is produced by the following?
String str = "Space, the final frontier.";
System.out.println (str.length());
System.out.println (str.substring(7));
System.out.println (str.toUpperCase());
System.out.println (str.length());
26
the final frontier.
SPACE, THE FINAL FRONTIER.
26
87
Comparative values
88
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for
if-then-else statement)
Be careful
When comparing strings
This will not work
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
Example
String sting1 = new String("hello");
String sting2 = new String("hello");
int int1 = 1, int2 = 1;
if (int1 == int2){
System.out.println("true");
}
else{ System.out.println("not true”); }
if (sting1.equals(sting2)){
System.out.println("true");
}
else{ System.out.println("not true"); }
89

Ifi7184.DT lesson 2

  • 1.
    IFI7184.DT – Lesson2 Variables and types @ slides adapted from Isaías da Rosa sources
  • 2.
    Overview • On todayslesson condition statements – Variables and Types • Variables and Assignment – Primitive Data Types – Complex data Types – The Data Conversion – Expressions – Interactive Programs – Creating Objects 22015 @ Sonia Sousa
  • 3.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 3@ Sonia Sousa2015
  • 4.
    Everything is anobject • In java as you design your applications – You place your code inside of Class definitions • Inside you add your Function – Known as method public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello World"); } } 4 Executable code Function Class definition
  • 5.
    Everything is anobject public class HelloWorld{ public static void main(String[] args) { sayHello(); } public static void sayHello() { String w = new String("hello"); System.out.println( w ); } } 5 Executable code Function Class definition Executable code Instance variable Class instance
  • 6.
    Object oriented Language State Variables(fields) behaviours functions (methods) that allow to change the state Function to change the gear (bicycle has 3 gears) @ Sonia Sousa 62015 System.out.println( w ); String w = "hello";
  • 7.
    What Is aClass? • A Class represent 1 object (Myfirstprogram) Instance Of class of objects @ Sonia Sousa 72015 object public class HelloWorld{ public static void main(String[] args) { sayHello(); } public static void sayHello() { String w = new String("hello"); System.out.println( w ); } }
  • 8.
    What Is aInheritance? • Class of objects that inherit characteristics of another object inherit characteristics class of objects known as Superclass of objects known as specific characteristic public class HelloWorld { public static void main(String[] args) { sayHello(); } public static void sayHello() { String w = "hello"; System.out.println( w ); }
  • 9.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 9@ Sonia Sousa2015
  • 10.
    Variables • A variableis a name for a location in memory that holds a value • Primitive data – Numerical • Integers: byte, short, int, long • Floating point decimals: float, double – Characters: • Not complete strings: char – Boolean values: • Boolean: True or false • Complex object – Declare as instance of a data class • String • Date • Everything else 10
  • 11.
    Declare variables • Youneed to specify – 3 parts: • Data type • Variable name – Lower case or Underscore _ – not numerical • Initial value – optional 11 Type Byte, short, int, long Float, double data type variable name int total;
  • 12.
    Variable Initialization 12 int sum= 0; int base = 32, max = 149; data type variable name Initiate variable @ Sonia Sousa2015 Multiple variables can be created in one declaration int count, temp, result;
  • 13.
    Complex object • Declaration –Instance of a class – Primitives we declare 3 parts • Data type • Variable name • Initial value: build from class constructor 13 data type variable name Initiate variable from constructor String w = new String(c);
  • 14.
    Declare variables • Insidethe function – Finish execute -> the variable goes away • Outside the function 14 public static void sayHello() { String w = "hello”; System.out.println( w ); } public static void sayHello() { String w = "hello”; } System.out.println( w );
  • 15.
    Characters • A charvariable stores a single character • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' 'n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; • Note the difference between – a primitive character variable, which holds only one character, and – a String object, which can hold multiple characters 2015 @ Sonia Sousa 15
  • 16.
    Output character public classCharacter { public static void main(String[] args) { char[] c = {'h','e','l','l','o'}; char c1 = 'h'; char c2 = ‘e'; char c3 = ‘l'; char c4 = ‘l'; char c5 = ‘o’; System.out.println( c ); } } 16
  • 17.
    Boolean • A booleanvalue represents a true or false condition • The reserved words true and false are the only valid values for a boolean type boolean done = false; • A boolean variable can also be used to represent any two states, such as a light bulb being on or off 2015 @ Sonia Sousa 17
  • 18.
    Boolean public class Charecter{ public static void main(String[] args) { boolean done1 = true; boolean done2 = false; boolean done3 = !done1; System.out.println( "Did you finish the exercise? " + done1); System.out.println( "The exercise is done " + done2); System.out.println( "Is it done now? " + done3); } } 18 !Is a logical complement operator; inverts the value of a boolean
  • 19.
    Output primitive values •Any value can be outputted as a string – Using the concatenation value + 19 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."); } } Output A piano has 88 keys.
  • 20.
    Output values public staticvoid main(String[] args) { char charVal = 'c'; boolean booleanVal =true; short shortVal = 127; int intVal = 32000; long longVal = 2000000L; float floatval = 10000000f; double doubleVal= 112321231221.23d; System.out.println( "character value is " + charVal); System.out.println(booleanVal); System.out.println( "short value is " + shortVal); System.out.println( "Integer value is " + intVal); System.out.println( "long value is " + longVal); System.out.println(doubleVal); System.out.println(floatval + " float value " ); System.out.println( "double value is " + doubleVal); } 20 Output character value is c true short value is 127 Integer value is 32000 long value is 2000000 1.1232123122123E11 1.0E7 float value double value is 1.1232123122123E11
  • 21.
    Output complex objects importjava.util.Date; public class Complex{ public static void main(String[] args) { Date myDate = new Date(); String myString = new String("Hello"); System.out.println(myString); System.out.println( "My date is " + myDate); } } 21
  • 22.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 22@ Sonia Sousa2015
  • 23.
    Data Conversion • Sometimesit is convenient to convert data – from one type to another • For example, – to treat an integer as a floating point value – Or a short to an int • You can do two type of conversions – Downwards • You don’t loose data – Upwards • You loose data – Promotion 23
  • 24.
  • 25.
    Numeric Primitive Data •The difference between the numeric primitive types is their size and the values they can store: 2015 @ Sonia Sousa 25 Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 - 3.4 x 1038 3.4 x 1038 - 1.7 x 10308 1.7 x 10308 Max Value 127 32,767 2,147,483,647 > 9 x 1018
  • 26.
    Upward Conversion • OrAssignment conversion occurs – when a value is assigned to a variable of another • Example: int dollars = 20; double money = dollars; • Only Upward conversions can happen via assignment – the value or type of dollars did not change 26
  • 27.
    Convert primitive datatype • From a data type to another (upward) 27 Type double float long int short byte public class Converting{ public static void main(String[] args) { int intVal=120; double convertIn= intVal; System.out.println( "Integer value is " + intVal); System.out.println( "Double value is " + convertIn); } } Output Integer value is 120 Double value is 120.0
  • 28.
    Downwards conversion • Castingor downwards conversion – is the most powerful, and dangerous, technique for conversion – This conversions happen if you explicitly cast a value • To cast, you put in parentheses in front of the value being converted – Example double doubleVal= 3.99; int convertVal= (int)doubleVal; – You might lose information 28
  • 29.
    Convert primitive datatype • From a data type to another (downward) 29 Type double float long int short byte public class Converting{ public static void main(String[] args) { double doubleVal= 3.99; int convertVal= (int)doubleVal; System.out.println( "Double value is " + doubleVal); System.out.println( "Integer value is " + convertVal); } } Output Double value is 3.99 Integer value is 3
  • 30.
    Convert primitive datatype • From a data type to another (downward) 30 Type Double byte public class Converting{ public static void main(String[] args) { double doubleVal= 128; byte convertVal= (byte)doubleVal; System.out.println( "Double value is " + doubleVal); System.out.println( ”Byte value is " + convertVal); } } Output Double value is 128.0 Byte value is -128
  • 31.
    Promotion • Promotion happensautomatically – When you use 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 31
  • 32.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 32@ Sonia Sousa2015
  • 33.
    Simple calculation applications •Type of operators – Simple assignment • Assignment values – Complex assignment • Combine assignment and math in a single expression – Equality and relation • Compare values to each other – Mathematical • Execute common mathematical processes – Conditional operators • Define complex conditional processes 33 int count = 12; double sum = 490.27; result = sum / count; data type variable name Simple assign Complex assign
  • 34.
    Math operators • Anexpression is a combination of one or more operators and operands • Arithmetic or math expressions compute numeric results: 34 Addition Subtraction Multiplication Division Remainder + - * / % • If either or both operands are floating point values, then the result is a floating point value
  • 35.
    Promotion • Promotion happensautomatically – When you use 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 35
  • 36.
    Division and Remainder •If both operands to the division operator (/) are integers – the result is an integer (the fractional part is discarded) 14 / 3 equals 4 8 / 12 equals 0 • The remainder operator (%) returns the remainder after dividing the first operand by the second 14 % 3 equals 2 8 % 12 equals 8 36
  • 37.
    Quick Check What arethe results of the following expressions? 12 / 2 12.0 / 2.0 10 / 4 10 / 4.0 4 / 10 4.0 / 10 12 % 3 10 % 3 3 % 10 37
  • 38.
    Quick Check What arethe results of the following expressions? public static void main(String[] args) { int valueDiv = 12; double result1 =valueDiv/2; double result2 = 12.0 / 2.0; … double result7 = 12 % 3; double result8 = 10 % 3; double result9 = 3 % 10; System.out.println(result1); System.out.println(result2); … System.out.println(result7); System.out.println(result8); System.out.println(result9); System.out.println("The end :)"); } 38 Output = 6 = 6.0 = 2 = 2.5 = 0 = 0.4 = 0 = 1 = 0
  • 39.
    Operator Precedence • Operatorscan be combined into larger expressions result = total + count / max - offset; • Operators have precedence – determines the order in which they are evaluated • First: – Multiplication, division, and remainder • Second: – addition, subtraction, and string concatenation • Same precedence – left to right, • Exception – Using parentheses • force the evaluation order 39
  • 40.
    Quick Check 40 a +b + c + d + e a + b * c - d / e a / (b + c) - d % e a / (b * (c + (d - e))) In what order are the operators evaluated in the following expressions? Values a =1; b = 12; c = 10; d =4; e = 3;
  • 41.
    Quick Check a +b + c + d + e a + b * c - d / e a / (b + c) - d % e a / (b * (c + (d - e))) 1 432 3 241 2 341 4 123 In what order are the operators evaluated in the following expressions? 41
  • 42.
    Quick Check What arethe results of the following expressions? int a =1; int b = 12; int c = 10; int d =4; int e = 3; double result1 =a+b+c+d+e; double result2 =a + b * c - d / e; double result3 =a / (b + c) - d % e; double result4 = a / (b * (c + (d - e))); System.out.println(result1); System.out.println(result2); System.out.println(result3); System.out.println(result4); System.out.println("The end :)"); } 42 Output = 30.0 = 120.0 = -1.0 0.0The end :)
  • 43.
    Assignment Revisited • Theassignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 14 3 2 43
  • 44.
    Assignment Revisited • Theright and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count Then the result is stored back into count (overwriting the original value) count = count + 1; 44
  • 45.
    Increment and Decrement •The increment (++) operator – The statement count++; count = count + 1; • The decrement (--) operator count--; count = count - 1; 45
  • 46.
    Increment and Decrement •Postfix syntax: – Evaluated value first then make the mathematical operation count++ • Prefix syntax: – mathematical operation first then evaluated value ++count • ! When used as part of a larger expression ! – the two forms can have different effects • The subtleties, of increment and decrement operators – should be used with care 46
  • 47.
    Assignment Operators • Oftenwe perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count; 47
  • 48.
    Quick Check What arethe results of the following expressions? Start with intValue =10 Calculate ++ -- +=5 -=5 /=5 ++ intValue -- intValue 48
  • 49.
    Assignment Operators • Theright hand side of an assignment operator can be a complex expression • The entire right-hand expression is evaluated first, then the result is combined with the original variable • Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); 49
  • 50.
    Assignment Operators • Thebehavior 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 (+) 50
  • 51.
    Assignment Operators • Thereare many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y 51
  • 52.
    Quick Check What arethe results of the following expressions? int intValue =10; int newValue1 =++ intValue; int newValue2 =-- intValue; System.out.println(intValue ++); System.out.println(intValue --); System.out.println(intValue +=5); System.out.println(intValue -=5); System.out.println(intValue /=5); System.out.println(newValue1); System.out.println(newValue2); System.out.println("The end :)"); } 52 Output = 10 = 11 = 15 = 10 = 2 = 11 = 10 The end :)
  • 53.
    Comparative values 53 == Equalto != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Be careful When comparing strings This will not work https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
  • 54.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 54@ Sonia Sousa2015
  • 55.
    Interactive Programs • Programsgenerally need input on which to operate • Scanner class – provides the 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 • To read Keyboard input – Use the System.in object 55
  • 56.
    Reading Input • Createa 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(); 56
  • 57.
    Reading Input • TheScanner class is part of the – java.util class library – Import class java.util library • This class library 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 57
  • 58.
    //******************************************************************** // 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 + """); } } 58
  • 59.
    //******************************************************************** // 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 Enter a line of text: You want fries with that? You entered: "You want fries with that?" 59
  • 60.
    Input Tokens • Unlessspecified 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 60
  • 61.
    //******************************************************************** // 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 based on values entered by the // user. //----------------------------------------------------------------- public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue 61
  • 62.
    continue System.out.print ("Enter thenumber 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); } } 62
  • 63.
    continue System.out.print ("Enter thenumber 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 Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon: 29.28571428571429 63
  • 64.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 64@ Sonia Sousa2015
  • 65.
    Creating Objects • Primitivedata type vs objects – Objects can be used to represent real-world entities (see the top slides) • For instance, an object – represent a particular employee in a company » Each employee object • handles specific information • related to that employee 65
  • 66.
    Creating Objects • Anobject has: – state (attributes) • descriptive characteristics – behaviors • what it can do (or what can be done to it) 66 BankAcount AccounNumber Name Balance Deposit Withrow Transfer State behaviours
  • 67.
    Creating Objects • Anobject has: – state (attributes) - bankAcount – AccountNumber – Name – Balance • descriptive characteristics – behaviors (what he can do) – Desposit – Withrow – Tranfer • the ability to make deposits and withdrawals • Note that the behavior of an object might change its state 67 BankAcount AccounNumber Name Balance Deposit Withrow Transfer
  • 68.
    Classes • An objectis defined by a class – A class is the blueprint of an object • The class uses methods – to define the behaviors of the object • The class contains the main method of a Java program – represents the entire program • A class represents a concept • An object represents the embodiment of that concept • Multiple objects can be created from the same class 68
  • 69.
    Class = Blueprint •One blueprint to create several similar, but different, houses: 69
  • 70.
    Objects and Classes Bank Account Aclass (the concept) John’s Bank Account Balance: $5,257 An object (the realization) Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 Multiple objects from the same class 70
  • 71.
    Creating Objects • Avariable holds either a primitive value or a reference to an object • A class name can be used as a type to declare an object reference variable String title; • No object is created with this declaration • An object reference variable holds the address of an object • The object itself must be created separately 71
  • 72.
    Creating Objects • Generally,we use the new operator to create an object • Creating an object is called instantiation • An object is an instance of a particular class 72 title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object
  • 73.
    Invoking Methods • We'veseen that once an object has been instantiated, we can use the dot operator to invoke its methods numChars = title.length() • A method may return a value, which can be used in an assignment or expression • A method invocation can be thought of as asking an object to perform a service 73
  • 74.
    References • Note thata primitive variable contains the value itself, but an object variable contains the address of the object • An object reference can be thought of as a pointer to the location of the object • Rather than dealing with arbitrary addresses, we often depict a reference graphically 74 "Steve Jobs"name1 num1 38
  • 75.
    Assignment Revisited • Theact of assignment takes a copy of a value and stores it in a variable • For primitive types: 75 num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:
  • 76.
    Reference Assignment • Forobject references, assignment copies the address: 76 name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs"
  • 77.
    Aliases • Two ormore references that refer to the same object are called aliases of each other • That creates an interesting situation: one object can be accessed using multiple reference variables • Aliases can be useful, but should be managed carefully • Changing an object through one reference changes it for all of its aliases, because there is really only one object 77
  • 78.
    Garbage Collection • Whenan object no longer has any valid references to it, it can no longer be accessed by the program • The object is useless, and therefore is called garbage • Java performs automatic garbage collection periodically, returning an object's memory to the system for future use • In other languages, the programmer is responsible for performing garbage collection 78
  • 79.
    Outline Review Object-oriented concepts Variablesand Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects String class 79@ Sonia Sousa2015
  • 80.
    The String Class •Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; • This is special syntax that works only for strings • Each string literal (enclosed in double quotes) represents a String object 80
  • 81.
    String Methods • Oncea String object has been created, neither its value nor its length can be changed • Therefore we say that an object of the String class is immutable • However, several methods of the String class return new String objects that are modified versions of the original 81
  • 82.
    String Indexes • Itis occasionally helpful to refer to a particular character within a string • This can be done by specifying the character's numeric index • The indexes begin at zero in each string • In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 • See StringMutation.java 82
  • 83.
    //******************************************************************** // StringMutation.java Author:Lewis/Loftus // // Demonstrates the use of the String class and its methods. //******************************************************************** public class StringMutation { //----------------------------------------------------------------- // Prints a string and various mutations of it. //----------------------------------------------------------------- public static void main (String[] args) { String phrase = "Change is inevitable"; String mutation1, mutation2, mutation3, mutation4; System.out.println ("Original string: "" + phrase + """); System.out.println ("Length of string: " + phrase.length()); mutation1 = phrase.concat (", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); continued 83
  • 84.
    continued // Print eachmutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } } 84
  • 85.
    continued // Print eachmutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } } Output Original string: "Change is inevitable" Length of string: 20 Mutation #1: Change is inevitable, except from vending machines. Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS. Mutation #4: NGX IS INXVITABLX, XXCXPT F Mutated length: 27 85
  • 86.
    Quick Check What outputis produced by the following? String str = "Space, the final frontier."; System.out.println (str.length()); System.out.println (str.substring(7)); System.out.println (str.toUpperCase()); System.out.println (str.length()); 86
  • 87.
    Quick Check What outputis produced by the following? String str = "Space, the final frontier."; System.out.println (str.length()); System.out.println (str.substring(7)); System.out.println (str.toUpperCase()); System.out.println (str.length()); 26 the final frontier. SPACE, THE FINAL FRONTIER. 26 87
  • 88.
    Comparative values 88 == Equalto != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Be careful When comparing strings This will not work https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
  • 89.
    Example String sting1 =new String("hello"); String sting2 = new String("hello"); int int1 = 1, int2 = 1; if (int1 == int2){ System.out.println("true"); } else{ System.out.println("not true”); } if (sting1.equals(sting2)){ System.out.println("true"); } else{ System.out.println("not true"); } 89