SlideShare une entreprise Scribd logo
1  sur  76
Computer Skills and
Programming Update
Institute of Informatics - Tallinn University
Fernando Loizides, Sonia Sousa, Romil Rõbtšenkov
2015
Outline
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
2
Expressions
• An expression is a combination of one or more
operators and operands
• Arithmetic expressions compute numeric results
and make use of the arithmetic operators:
Addition
Subtraction
Multiplication
Division
Remainder
+
-
*
/
%
• If either or both operands are floating point values,
then the result is a floating point value
3
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
4
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
5
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
= 6
= 6.0
= 2
= 2.5
= 0
= 0.4
= 0
= 1
= 0
6
Operator Precedence
• Operators can be combined into larger
expressions
result = total + count / max - offset;
• Operators have a well-defined precedence
which determines the order in which they are
evaluated
• Multiplication, division, and remainder are
evaluated before addition, subtraction, and string
concatenation
• Arithmetic operators with the same precedence
are evaluated from left to right, but parentheses
can be used to force the evaluation order
7
Quick Check
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?
8
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?
9
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
10
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;
11
Increment and Decrement
• The increment (++) and decrement (--)
operators use only one operand
• The statement
count++;
is functionally equivalent to
count = count + 1;
12
Increment and Decrement
• The increment and decrement operators can
be applied in postfix form:
count++
• or prefix form:
++count
• When used as part of a larger expression, the
two forms can have different effects
• Because of their subtleties, the increment and
decrement operators should be used with care
13
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;
14
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
15
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);
16
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 (+)
17
Outline
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
18
Data Conversion
• Sometimes it is convenient to convert data
from one type to another
• For example, in a particular situation we may
want to treat an integer as a floating point
value
• These conversions do not change the type
of a variable or the value that's stored in it –
they only convert a value as part of a
computation
19
Data Conversion
• Widening conversions are safest because they
tend to go from a small data type to a larger one
(such as a short to an int)
• Narrowing conversions can lose information
because they tend to go from a large data type
to a smaller one (such as an int to a short)
• In Java, data conversions can occur in three
ways:
– assignment conversion
– promotion
– casting
20
Data Conversion
Widening Conversions Narrowing Conversions
21
Assignment Conversion
• Assignment conversion occurs when a value
of one type is assigned to a variable of
another
• Example:
int dollars = 20;
double money = dollars;
• Only widening conversions can happen via
assignment
• Note that the value or type of dollars did
not change
22
Promotion
• Promotion happens automatically when
operators in expressions convert their
operands
• Example:
int count = 12;
double sum = 490.27;
result = sum / count;
• The value of count is converted to a
floating point value to perform the division
calculation
23
Casting
• Casting is the most powerful, and dangerous,
technique for conversion
• Both widening and narrowing conversions can
be accomplished by explicitly casting a value
• To cast, the type is put in parentheses in front
of the value being converted
int total = 50;
float result = (float) total / 6;
• Without the cast, the fractional part of the
answer would be lost
24
Outline
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
25
Interactive Programs
• Programs generally need input on which to
operate
• The Scanner class provides convenient
methods for reading input values of various
types
• A Scanner object can be set up to read input
from various sources, including the user typing
values on the keyboard
• Keyboard input is represented by the
System.in object
26
Reading Input
• The following line creates a Scanner object
that reads from the keyboard:
Scanner scan = new Scanner (System.in);
• The new operator creates the Scanner object
• Once created, the Scanner object can be
used to invoke various input methods, such as:
answer = scan.nextLine();
27
Reading Input
• The Scanner class is part of the
java.util class library, and must be
imported into a program to be used
• The nextLine method reads all of the input
until the end of the line is found
• See Echo.java
28
//********************************************************************
// 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 + """);
}
}
29
//********************************************************************
// 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?"
30
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
31
//********************************************************************
// 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
32
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);
}
}
33
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
34
Outline
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
35
Creating Objects
• Primitive data type vs objects
• Objects can be used effectively to represent
real-world entities
• For instance, an object might represent a
particular employee in a company
• Each employee object handles the
processing and data management related to
that employee
• It can be seen as an autonomous and closed
box which performs operations
36
Creating Objects
• An object has:
– state (attributes) - descriptive
characteristics
– behaviors - what it can do (or what
can be done to it)
• The state of a bank account includes
its account number and its current
balance
• The behaviors associated with a
bank account include the ability to
make deposits and withdrawals
• Note that the behavior of an object
might change its state
37
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 that contains the main method of a
Java program represents the entire program
• A class represents a concept, and an object
represents the embodiment of that concept
• Multiple objects can be created from the same
class
38
Class = Blueprint
• One blueprint to create several similar, but
different, houses:
39
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
40
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
41
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
title = new String ("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
42
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
43
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
"Steve Jobs"name1
num1 38
44
Assignment Revisited
• The act of assignment takes a copy of a
value and stores it in a variable
• For primitive types:
num1 38
num2 96
Before:
num2 = num1;
num1 38
num2 38
After:
45
Reference Assignment
• For object references, assignment copies
the address:
name2 = name1;
name1
name2
Before:
"Steve Jobs"
"Steve Wozniak"
name1
name2
After:
"Steve Jobs"
46
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
47
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
48
Outline
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
49
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
50
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
51
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
52
//********************************************************************
// 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
53
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());
}
}
54
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
55
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());
56
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
57
Outline
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Creating Objects
The String Class
The Random and Math Classes
58
Class Libraries
• A class library is a collection of classes that
we can use when developing programs
• The Java standard class library is part of any
Java development environment
• Its classes are not part of the Java language
per se, but we rely on them heavily
• Various classes we've already used (System
, Scanner, String) are part of the Java
standard class library
59
The Java API
• The Java class library is sometimes referred
to as the Java API
• API stands for Application Programming
Interface
• Clusters of related classes are sometimes
referred to as specific APIs:
– The Swing API
– The Database API
60
The Java API
• Get comfortable navigating the online Java
API documentation
http://docs.oracle.com/javase/6/docs/api/
61
Packages
• For purposes of accessing them, classes in
the Java API are organized into packages
• These often overlap with specific APIs
• Examples:
Package
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
javax.xml.parsers
Purpose
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities
Network communication
Utilities
XML document processing
62
The import Declaration
• When you want to use a class from a package,
you could use its fully qualified name
java.util.Scanner
• Or you can import the class, and then use just
the class name
import java.util.Scanner;
• To import all classes in a particular package,
you can use the * wildcard character
import java.util.*;
63
The import Declaration
• All classes of the java.lang package are
imported automatically into all programs
• It's as if all programs contain the following line:
import java.lang.*;
• That's why we didn't have to import the System
or String classes explicitly in earlier programs
• The Scanner class, on the other hand, is part
of the java.util package, and therefore must
be imported
64
The Random Class
• The Random class is part of the java.util
package
• It provides methods that generate
pseudorandom numbers
• A Random object performs complicated
calculations based on a seed value to produce a
stream of seemingly random values
• See RandomNumbers.java
65
//********************************************************************
// RandomNumbers.java Author: Lewis/Loftus
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
continued
66
continued
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
}
67
continued
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
}
Sample Run
A random integer: 672981683
From 0 to 9: 0
From 1 to 10: 3
From 20 to 34: 30
From -10 to 9: -4
A random float (between 0-1): 0.18538326
From 1 to 6: 3
68
Quick Check
Given a Random object named gen, what range of
values are produced by the following expressions?
gen.nextInt(25)
gen.nextInt(6) + 1
gen.nextInt(100) + 10
gen.nextInt(50) + 100
gen.nextInt(10) – 5
gen.nextInt(22) + 12
69
Quick Check
Given a Random object named gen, what range of
values are produced by the following expressions?
gen.nextInt(25)
gen.nextInt(6) + 1
gen.nextInt(100) + 10
gen.nextInt(50) + 100
gen.nextInt(10) – 5
gen.nextInt(22) + 12
Range
0 to 24
1 to 6
10 to 109
100 to 149
-5 to 4
12 to 33
70
Quick Check
Write an expression that produces a random integer
in the following ranges:
Range
0 to 12
1 to 20
15 to 20
-10 to 0
71
Quick Check
Write an expression that produces a random integer
in the following ranges:
gen.nextInt(13)
gen.nextInt(20) + 1
gen.nextInt(6) + 15
gen.nextInt(11) – 10
Range
0 to 12
1 to 20
15 to 20
-10 to 0
72
The Math Class
• The Math class is part of the java.lang
package
• The Math class contains methods that
perform various mathematical functions
• These include:
– absolute value
– square root
– exponentiation
– trigonometric functions
73
The Math Class
• The methods of the Math class are static
methods (also called class methods)
• Static methods are invoked through the class
name – no object of the Math class is
needed
value = Math.cos(90) + Math.sqrt(delta);
• See squarertandpower.java
74
75
//********************************************************************
// squarertandpower.java Author: Isaias Barreto da Rosa
//
// Demonstrates the use of Math Class methods
//********************************************************************
package squarertandpower;
import java.util.Scanner;
public class SquarertAndPower {
public static void main(String[] args) {
double x;
Scanner scan = new Scanner(System.in);
System.out.print(”Enter a number ");
x = scan.nextDouble();
System.out.println("The square route of "+ x +" is "+Math.sqrt(x));
System.out.println(x+” raised to the power of 2 is ”+Math.pow(x, 2));
}
}
//********************************************************************
// squarertandpower.java Author: Isaias Barreto da rosa
//
// Demonstrates the use of Math Class methods
//********************************************************************
package squarertandpower;
import java.util.Scanner;
public class SquarertAndPower {
public static void main(String[] args) {
double x;
Scanner scan = new Scanner(System.in);
System.out.print(”Enter a number ");
x = scan.nextDouble();
System.out.println("The square route of "+ x +" is "+Math.sqrt(x));
System.out.println(x+” raised to the power of 2 is ”+Math.pow(x, 2));
}
}
76
Sample Run
Enter a number: 4
The square route of 4.0 is 2.0
4.0 raised to the power of 2 is 16.0

Contenu connexe

Tendances

The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilationHuawei Technologies
 
8.2 approach in problem solving (9 hour)
8.2 approach in problem solving (9 hour)8.2 approach in problem solving (9 hour)
8.2 approach in problem solving (9 hour)Fiqry Suryansyah
 
Introduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonIntroduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonPriyankaC44
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Verilog data types -For beginners
Verilog data types -For beginnersVerilog data types -For beginners
Verilog data types -For beginnersDr.YNM
 
Creating queuing system simulations with enterprise architect sysml parametri...
Creating queuing system simulations with enterprise architect sysml parametri...Creating queuing system simulations with enterprise architect sysml parametri...
Creating queuing system simulations with enterprise architect sysml parametri...Pragmatic Cohesion Consulting, LLC
 
Simulation and modeling
Simulation and modelingSimulation and modeling
Simulation and modelingHabibur Rahman
 
Matlab-Data types and operators
Matlab-Data types and operatorsMatlab-Data types and operators
Matlab-Data types and operatorsLuckshay Batra
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5FabMinds
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and FlowchartsDeva Singh
 

Tendances (19)

Matlab tutorial 4
Matlab tutorial 4Matlab tutorial 4
Matlab tutorial 4
 
The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilation
 
Unit 1 psp
Unit 1 pspUnit 1 psp
Unit 1 psp
 
Flowcharts
FlowchartsFlowcharts
Flowcharts
 
8.2 approach in problem solving (9 hour)
8.2 approach in problem solving (9 hour)8.2 approach in problem solving (9 hour)
8.2 approach in problem solving (9 hour)
 
Introduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonIntroduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- Python
 
Chapter 7: Arithmetic and Relational Operators
Chapter 7:  Arithmetic and Relational Operators Chapter 7:  Arithmetic and Relational Operators
Chapter 7: Arithmetic and Relational Operators
 
Flowchart
FlowchartFlowchart
Flowchart
 
Arithmetic operator
Arithmetic operatorArithmetic operator
Arithmetic operator
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Verilog data types -For beginners
Verilog data types -For beginnersVerilog data types -For beginners
Verilog data types -For beginners
 
Creating queuing system simulations with enterprise architect sysml parametri...
Creating queuing system simulations with enterprise architect sysml parametri...Creating queuing system simulations with enterprise architect sysml parametri...
Creating queuing system simulations with enterprise architect sysml parametri...
 
CONTROL STRUCTURE
CONTROL STRUCTURECONTROL STRUCTURE
CONTROL STRUCTURE
 
Arithmetic & Logic Unit
Arithmetic & Logic UnitArithmetic & Logic Unit
Arithmetic & Logic Unit
 
Simulation and modeling
Simulation and modelingSimulation and modeling
Simulation and modeling
 
Matlab-Data types and operators
Matlab-Data types and operatorsMatlab-Data types and operators
Matlab-Data types and operators
 
java8
java8java8
java8
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and Flowcharts
 

Similaire à Class 2 variables, classes methods...

Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3sotlsoc
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
 
Basics of c programming cit r.sandhiya
Basics of c programming  cit r.sandhiyaBasics of c programming  cit r.sandhiya
Basics of c programming cit r.sandhiyaDr.Sandhiya Ravi
 
Lab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressionsLab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressionsAksharVaish2
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptxrinkugupta37
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 
ESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxAvijitChaudhuri3
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cSowmya Jyothi
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressionsmaznabili
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++Praveen M Jigajinni
 

Similaire à Class 2 variables, classes methods... (20)

Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Basics of c programming cit r.sandhiya
Basics of c programming  cit r.sandhiyaBasics of c programming  cit r.sandhiya
Basics of c programming cit r.sandhiya
 
Lab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressionsLab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressions
 
Lecture 05.pptx
Lecture 05.pptxLecture 05.pptx
Lecture 05.pptx
 
C program
C programC program
C program
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
python ppt
python pptpython ppt
python ppt
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptx
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
ESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptxESCM303 Introduction to Python Programming.pptx
ESCM303 Introduction to Python Programming.pptx
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
Operators
OperatorsOperators
Operators
 

Dernier

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Dernier (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Class 2 variables, classes methods...

  • 1. Computer Skills and Programming Update Institute of Informatics - Tallinn University Fernando Loizides, Sonia Sousa, Romil Rõbtšenkov 2015
  • 2. Outline Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 2
  • 3. Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + - * / % • If either or both operands are floating point values, then the result is a floating point value 3
  • 4. 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 4
  • 5. 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 5
  • 6. 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 = 6 = 6.0 = 2 = 2.5 = 0 = 0.4 = 0 = 1 = 0 6
  • 7. Operator Precedence • Operators can be combined into larger expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order 7
  • 8. Quick Check 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? 8
  • 9. 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? 9
  • 10. 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 10
  • 11. 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; 11
  • 12. Increment and Decrement • The increment (++) and decrement (--) operators use only one operand • The statement count++; is functionally equivalent to count = count + 1; 12
  • 13. Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count • When used as part of a larger expression, the two forms can have different effects • Because of their subtleties, the increment and decrement operators should be used with care 13
  • 14. 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; 14
  • 15. 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 15
  • 16. 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); 16
  • 17. 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 (+) 17
  • 18. Outline Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 18
  • 19. Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation 19
  • 20. Data Conversion • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways: – assignment conversion – promotion – casting 20
  • 21. Data Conversion Widening Conversions Narrowing Conversions 21
  • 22. Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • Example: int dollars = 20; double money = dollars; • Only widening conversions can happen via assignment • Note that the value or type of dollars did not change 22
  • 23. Promotion • Promotion happens automatically when operators in expressions convert their operands • Example: int count = 12; double sum = 490.27; result = sum / count; • The value of count is converted to a floating point value to perform the division calculation 23
  • 24. Casting • Casting is the most powerful, and dangerous, technique for conversion • Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted int total = 50; float result = (float) total / 6; • Without the cast, the fractional part of the answer would be lost 24
  • 25. Outline Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 25
  • 26. Interactive Programs • Programs generally need input on which to operate • The Scanner class provides convenient methods for reading input values of various types • A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard • Keyboard input is represented by the System.in object 26
  • 27. Reading Input • The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); • The new operator creates the Scanner object • Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine(); 27
  • 28. Reading Input • The Scanner class is part of the java.util class library, and must be imported into a program to be used • The nextLine method reads all of the input until the end of the line is found • See Echo.java 28
  • 29. //******************************************************************** // 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 + """); } } 29
  • 30. //******************************************************************** // 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?" 30
  • 31. 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 31
  • 32. //******************************************************************** // 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 32
  • 33. 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); } } 33
  • 34. 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 34
  • 35. Outline Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 35
  • 36. Creating Objects • Primitive data type vs objects • Objects can be used effectively to represent real-world entities • For instance, an object might represent a particular employee in a company • Each employee object handles the processing and data management related to that employee • It can be seen as an autonomous and closed box which performs operations 36
  • 37. Creating Objects • An object has: – state (attributes) - descriptive characteristics – behaviors - what it can do (or what can be done to it) • The state of a bank account includes its account number and its current balance • The behaviors associated with a bank account include the ability to make deposits and withdrawals • Note that the behavior of an object might change its state 37 BankAcount AccounNumber Name Balance Deposit Withrow Transfer
  • 38. 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 that contains the main method of a Java program represents the entire program • A class represents a concept, and an object represents the embodiment of that concept • Multiple objects can be created from the same class 38
  • 39. Class = Blueprint • One blueprint to create several similar, but different, houses: 39
  • 40. 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 40
  • 41. 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 41
  • 42. 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 title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object 42
  • 43. 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 43
  • 44. 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 "Steve Jobs"name1 num1 38 44
  • 45. Assignment Revisited • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After: 45
  • 46. Reference Assignment • For object references, assignment copies the address: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" 46
  • 47. 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 47
  • 48. 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 48
  • 49. Outline Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 49
  • 50. 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 50
  • 51. 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 51
  • 52. 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 52
  • 53. //******************************************************************** // 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 53
  • 54. 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()); } } 54
  • 55. 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 55
  • 56. 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()); 56
  • 57. 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 57
  • 58. Outline Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Creating Objects The String Class The Random and Math Classes 58
  • 59. Class Libraries • A class library is a collection of classes that we can use when developing programs • The Java standard class library is part of any Java development environment • Its classes are not part of the Java language per se, but we rely on them heavily • Various classes we've already used (System , Scanner, String) are part of the Java standard class library 59
  • 60. The Java API • The Java class library is sometimes referred to as the Java API • API stands for Application Programming Interface • Clusters of related classes are sometimes referred to as specific APIs: – The Swing API – The Database API 60
  • 61. The Java API • Get comfortable navigating the online Java API documentation http://docs.oracle.com/javase/6/docs/api/ 61
  • 62. Packages • For purposes of accessing them, classes in the Java API are organized into packages • These often overlap with specific APIs • Examples: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing 62
  • 63. The import Declaration • When you want to use a class from a package, you could use its fully qualified name java.util.Scanner • Or you can import the class, and then use just the class name import java.util.Scanner; • To import all classes in a particular package, you can use the * wildcard character import java.util.*; 63
  • 64. The import Declaration • All classes of the java.lang package are imported automatically into all programs • It's as if all programs contain the following line: import java.lang.*; • That's why we didn't have to import the System or String classes explicitly in earlier programs • The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported 64
  • 65. The Random Class • The Random class is part of the java.util package • It provides methods that generate pseudorandom numbers • A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values • See RandomNumbers.java 65
  • 66. //******************************************************************** // RandomNumbers.java Author: Lewis/Loftus // // Demonstrates the creation of pseudo-random numbers using the // Random class. //******************************************************************** import java.util.Random; public class RandomNumbers { //----------------------------------------------------------------- // Generates random numbers in various ranges. //----------------------------------------------------------------- public static void main (String[] args) { Random generator = new Random(); int num1; float num2; num1 = generator.nextInt(); System.out.println ("A random integer: " + num1); num1 = generator.nextInt(10); System.out.println ("From 0 to 9: " + num1); continued 66
  • 67. continued num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); } } 67
  • 68. continued num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); } } Sample Run A random integer: 672981683 From 0 to 9: 0 From 1 to 10: 3 From 20 to 34: 30 From -10 to 9: -4 A random float (between 0-1): 0.18538326 From 1 to 6: 3 68
  • 69. Quick Check Given a Random object named gen, what range of values are produced by the following expressions? gen.nextInt(25) gen.nextInt(6) + 1 gen.nextInt(100) + 10 gen.nextInt(50) + 100 gen.nextInt(10) – 5 gen.nextInt(22) + 12 69
  • 70. Quick Check Given a Random object named gen, what range of values are produced by the following expressions? gen.nextInt(25) gen.nextInt(6) + 1 gen.nextInt(100) + 10 gen.nextInt(50) + 100 gen.nextInt(10) – 5 gen.nextInt(22) + 12 Range 0 to 24 1 to 6 10 to 109 100 to 149 -5 to 4 12 to 33 70
  • 71. Quick Check Write an expression that produces a random integer in the following ranges: Range 0 to 12 1 to 20 15 to 20 -10 to 0 71
  • 72. Quick Check Write an expression that produces a random integer in the following ranges: gen.nextInt(13) gen.nextInt(20) + 1 gen.nextInt(6) + 15 gen.nextInt(11) – 10 Range 0 to 12 1 to 20 15 to 20 -10 to 0 72
  • 73. The Math Class • The Math class is part of the java.lang package • The Math class contains methods that perform various mathematical functions • These include: – absolute value – square root – exponentiation – trigonometric functions 73
  • 74. The Math Class • The methods of the Math class are static methods (also called class methods) • Static methods are invoked through the class name – no object of the Math class is needed value = Math.cos(90) + Math.sqrt(delta); • See squarertandpower.java 74
  • 75. 75 //******************************************************************** // squarertandpower.java Author: Isaias Barreto da Rosa // // Demonstrates the use of Math Class methods //******************************************************************** package squarertandpower; import java.util.Scanner; public class SquarertAndPower { public static void main(String[] args) { double x; Scanner scan = new Scanner(System.in); System.out.print(”Enter a number "); x = scan.nextDouble(); System.out.println("The square route of "+ x +" is "+Math.sqrt(x)); System.out.println(x+” raised to the power of 2 is ”+Math.pow(x, 2)); } }
  • 76. //******************************************************************** // squarertandpower.java Author: Isaias Barreto da rosa // // Demonstrates the use of Math Class methods //******************************************************************** package squarertandpower; import java.util.Scanner; public class SquarertAndPower { public static void main(String[] args) { double x; Scanner scan = new Scanner(System.in); System.out.print(”Enter a number "); x = scan.nextDouble(); System.out.println("The square route of "+ x +" is "+Math.sqrt(x)); System.out.println(x+” raised to the power of 2 is ”+Math.pow(x, 2)); } } 76 Sample Run Enter a number: 4 The square route of 4.0 is 2.0 4.0 raised to the power of 2 is 16.0