SlideShare a Scribd company logo
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

More Related Content

What's hot

Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
Jay Patel
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
ThamizhselviKrishnam
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
simarsimmygrewal
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
Templates
TemplatesTemplates
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
Palak Sanghani
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
Mohamed Krar
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
Vishnu Shaji
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 

What's hot (19)

Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Functions, classes & objects in c++
Functions, classes & objects in c++Functions, classes & objects in c++
Functions, classes & objects in c++
 
class and objects
class and objectsclass and objects
class and objects
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
C++ oop
C++ oopC++ oop
C++ oop
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Templates
TemplatesTemplates
Templates
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 

Viewers also liked

Lesson 16
Lesson 16Lesson 16
Lesson 16
Gene Babon
 
Html css workshop, lesson 0, how browsers work
Html css workshop, lesson 0, how browsers workHtml css workshop, lesson 0, how browsers work
Html css workshop, lesson 0, how browsers work
Albino Tonnina
 
Css ms megha
Css ms meghaCss ms megha
Css ms megha
Megha Gupta
 
Lesson 1
Lesson 1Lesson 1
Lesson 1
Slides4Victor
 
HTML Lesson 5
HTML Lesson 5HTML Lesson 5
HTML Lesson 5
Danny Ambrosio
 
HTML Lesson 1
HTML Lesson 1HTML Lesson 1
HTML Lesson 1
TonyC445
 
Lesson 04
Lesson 04Lesson 04
Lesson 04
Gene Babon
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
Sónia
 
Trust workshop
Trust workshopTrust workshop
Trust workshop
Sónia
 
Html tutorial.lesson5
Html tutorial.lesson5Html tutorial.lesson5
Html tutorial.lesson5
grassos
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction Design
Sónia
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
Gene Babon
 
Lesson 10
Lesson 10Lesson 10
Lesson 10
Gene Babon
 
CSS for designers - Lesson 1 - HTML
CSS for designers - Lesson 1 - HTMLCSS for designers - Lesson 1 - HTML
CSS for designers - Lesson 1 - HTML
Idan Segev
 
Lesson 15
Lesson 15Lesson 15
Lesson 15
Gene Babon
 
20 06-2014
20 06-201420 06-2014
20 06-2014
Sónia
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
Gene Babon
 
Ifi7174 lesson3
Ifi7174 lesson3Ifi7174 lesson3
Ifi7174 lesson3
Sónia
 
Lesson 11
Lesson 11Lesson 11
Lesson 11
Gene Babon
 
Lesson 15
Lesson 15Lesson 15
Lesson 15
Gene Babon
 

Viewers also liked (20)

Lesson 16
Lesson 16Lesson 16
Lesson 16
 
Html css workshop, lesson 0, how browsers work
Html css workshop, lesson 0, how browsers workHtml css workshop, lesson 0, how browsers work
Html css workshop, lesson 0, how browsers work
 
Css ms megha
Css ms meghaCss ms megha
Css ms megha
 
Lesson 1
Lesson 1Lesson 1
Lesson 1
 
HTML Lesson 5
HTML Lesson 5HTML Lesson 5
HTML Lesson 5
 
HTML Lesson 1
HTML Lesson 1HTML Lesson 1
HTML Lesson 1
 
Lesson 04
Lesson 04Lesson 04
Lesson 04
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
 
Trust workshop
Trust workshopTrust workshop
Trust workshop
 
Html tutorial.lesson5
Html tutorial.lesson5Html tutorial.lesson5
Html tutorial.lesson5
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction Design
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 10
Lesson 10Lesson 10
Lesson 10
 
CSS for designers - Lesson 1 - HTML
CSS for designers - Lesson 1 - HTMLCSS for designers - Lesson 1 - HTML
CSS for designers - Lesson 1 - HTML
 
Lesson 15
Lesson 15Lesson 15
Lesson 15
 
20 06-2014
20 06-201420 06-2014
20 06-2014
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Ifi7174 lesson3
Ifi7174 lesson3Ifi7174 lesson3
Ifi7174 lesson3
 
Lesson 11
Lesson 11Lesson 11
Lesson 11
 
Lesson 15
Lesson 15Lesson 15
Lesson 15
 

Similar to Ifi7184.DT lesson 2

02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
19c
19c19c
19csharp
19csharp19csharp
19csharp
Sireesh K
 
P1
P1P1
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
raksharao
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
ahmed abugharsa
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
ANURAG SINGH
 
02basics
02basics02basics
02basics
Waheed Warraich
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Introduction to c#
Introduction to c#Introduction to c#

Similar to Ifi7184.DT lesson 2 (20)

02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
19c
19c19c
19c
 
19csharp
19csharp19csharp
19csharp
 
P1
P1P1
P1
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
02basics
02basics02basics
02basics
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Templates
TemplatesTemplates
Templates
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Java introduction
Java introductionJava introduction
Java introduction
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 

More from Sónia

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)
Sónia
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1
Sónia
 
Workshop 1
Workshop 1Workshop 1
Workshop 1
Sónia
 
Ifi7184 lesson7
Ifi7184 lesson7Ifi7184 lesson7
Ifi7184 lesson7
Sónia
 
Ifi7184 lesson6
Ifi7184 lesson6Ifi7184 lesson6
Ifi7184 lesson6
Sónia
 
Ifi7184 lesson5
Ifi7184 lesson5Ifi7184 lesson5
Ifi7184 lesson5
Sónia
 
Ifi7184 lesson4
Ifi7184 lesson4Ifi7184 lesson4
Ifi7184 lesson4
Sónia
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4
Sónia
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
Sónia
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1
Sónia
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
Sónia
 
Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective
Sónia
 
IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languages
Sónia
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the course
Sónia
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluation
Sónia
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 Contextualization
Sónia
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7
Sónia
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6
Sónia
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3
Sónia
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
Sónia
 

More from Sónia (20)

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1
 
Workshop 1
Workshop 1Workshop 1
Workshop 1
 
Ifi7184 lesson7
Ifi7184 lesson7Ifi7184 lesson7
Ifi7184 lesson7
 
Ifi7184 lesson6
Ifi7184 lesson6Ifi7184 lesson6
Ifi7184 lesson6
 
Ifi7184 lesson5
Ifi7184 lesson5Ifi7184 lesson5
Ifi7184 lesson5
 
Ifi7184 lesson4
Ifi7184 lesson4Ifi7184 lesson4
Ifi7184 lesson4
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
 
Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective
 
IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languages
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the course
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluation
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 Contextualization
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
 

Ifi7184.DT lesson 2

  • 1. IFI7184.DT – Lesson 2 Variables and types @ slides adapted from Isaías da Rosa sources
  • 2. 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
  • 3. Outline Review Object-oriented concepts Variables and Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 3@ Sonia Sousa2015
  • 4. 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
  • 5. 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
  • 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 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 ); } }
  • 8. 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 ); }
  • 9. Outline Review Object-oriented concepts Variables and Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 9@ Sonia Sousa2015
  • 10. 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
  • 11. 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;
  • 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 • 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 );
  • 15. 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
  • 16. 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
  • 17. 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
  • 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 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
  • 21. 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
  • 22. Outline Review Object-oriented concepts Variables and Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 22@ Sonia Sousa2015
  • 23. 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
  • 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 • 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. Outline Review Object-oriented concepts Variables and 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 • 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
  • 35. 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
  • 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 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
  • 38. 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
  • 39. 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
  • 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 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 :)
  • 43. 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
  • 44. 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
  • 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 • 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
  • 48. Quick Check What are the results of the following expressions? Start with intValue =10 Calculate ++ -- +=5 -=5 /=5 ++ intValue -- intValue 48
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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 :)
  • 53. 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
  • 54. Outline Review Object-oriented concepts Variables and Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 54@ Sonia Sousa2015
  • 55. 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
  • 56. 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
  • 57. 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
  • 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 • 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
  • 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 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
  • 63. 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
  • 64. Outline Review Object-oriented concepts Variables and Types Variables and Assignment Primitive Data Types Data Conversion Expressions Interactive Programs Creating Objects 64@ Sonia Sousa2015
  • 65. 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
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. Class = Blueprint • One blueprint to create several similar, but different, houses: 69
  • 70. 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
  • 71. 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
  • 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'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
  • 74. 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
  • 75. 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:
  • 76. Reference Assignment • For object references, assignment copies the address: 76 name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs"
  • 77. 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
  • 78. 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
  • 79. 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
  • 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 • 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
  • 82. 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
  • 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 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
  • 85. 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
  • 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()); 86
  • 87. 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
  • 88. 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
  • 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