76
Computer Skills and Programming Update Institute of Informatics - Tallinn University Fernando Loizides, Sonia Sousa, Romil Rõbtšenkov 2015

Class 2 variables, classes methods

Embed Size (px)

Citation preview

Page 1: Class 2   variables, classes methods

Computer Skills and Programming Update

Institute of Informatics - Tallinn UniversityFernando Loizides, Sonia Sousa, Romil Rõbtšenkov

2015

Page 2: Class 2   variables, classes methods

2

Outline

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 3: Class 2   variables, classes methods

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:

AdditionSubtractionMultiplicationDivisionRemainder

+-*/%

• If either or both operands are floating point values, then the result is a floating point value

Page 4: Class 2   variables, classes methods

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 48 / 12 equals 0

• The remainder operator (%) returns the remainder after dividing the first operand by the second

14 % 3 equals 28 % 12 equals 8

Page 5: Class 2   variables, classes methods

5

Quick CheckWhat 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

Page 6: Class 2   variables, classes methods

6

Quick CheckWhat 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

Page 7: Class 2   variables, classes methods

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

Page 8: Class 2   variables, classes methods

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?

Page 9: Class 2   variables, classes methods

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?

Page 10: Class 2   variables, classes methods

10

Assignment Revisited• The assignment operator has a lower

precedence than the arithmetic operators

First the expression on the right handside of the = operator is evaluated

Then the result is stored in thevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 11: Class 2   variables, classes methods

11

Assignment Revisited• The right and left hand sides of an assignment

statement can contain the same variable

First, one is added to theoriginal value of count

Then the result is stored back into count(overwriting the original value)

count = count + 1;

Page 12: Class 2   variables, classes methods

12

Increment and Decrement• The increment (++) and decrement (--)

operators use only one operand

• The statement

count++;

is functionally equivalent to

count = count + 1;

Page 13: Class 2   variables, classes methods

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

Page 14: Class 2   variables, classes methods

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;

Page 15: Class 2   variables, classes methods

15

Assignment Operators• There are many assignment operators in

Java, including the following:

Operator

+=-=*=/=%=

Example

x += yx -= yx *= yx /= yx %= y

Equivalent To

x = x + yx = x - yx = x * yx = x / yx = x % y

Page 16: Class 2   variables, classes methods

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);

Page 17: Class 2   variables, classes methods

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 (+)

Page 18: Class 2   variables, classes methods

18

Outline

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 19: Class 2   variables, classes methods

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

Page 20: Class 2   variables, classes methods

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

Page 21: Class 2   variables, classes methods

21

Data Conversion

Widening Conversions Narrowing Conversions

Page 22: Class 2   variables, classes methods

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

Page 23: Class 2   variables, classes methods

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

Page 24: Class 2   variables, classes methods

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

Page 25: Class 2   variables, classes methods

25

Outline

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 26: Class 2   variables, classes methods

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

Page 27: Class 2   variables, classes methods

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();

Page 28: Class 2   variables, classes methods

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

Page 29: Class 2   variables, classes methods

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 + "\""); }}

Page 30: Class 2   variables, classes methods

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?"

Page 31: Class 2   variables, classes methods

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

Page 32: Class 2   variables, classes methods

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

Page 33: Class 2   variables, classes methods

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); }}

Page 34: Class 2   variables, classes methods

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: 328Enter the gallons of fuel used: 11.2Miles Per Gallon: 29.28571428571429

Page 35: Class 2   variables, classes methods

35

OutlineExpressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 36: Class 2   variables, classes methods

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

Page 37: Class 2   variables, classes methods

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

BankAcount

AccounNumberName

Balance

Deposit

Withrow

Transfer

Page 38: Class 2   variables, classes methods

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

Page 39: Class 2   variables, classes methods

39

Class = Blueprint• One blueprint to create several similar, but

different, houses:

Page 40: Class 2   variables, classes methods

40

Objects and Classes

Bank Account

A class(the concept)

John’s Bank AccountBalance: $5,257

An object(the realization)

Bill’s Bank AccountBalance: $1,245,069

Mary’s Bank AccountBalance: $16,833

Multiple objectsfrom the same class

Page 41: Class 2   variables, classes methods

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

Page 42: Class 2   variables, classes methods

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 isa special method that sets up the object

Page 43: Class 2   variables, classes methods

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

Page 44: Class 2   variables, classes methods

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

Page 45: Class 2   variables, classes methods

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 96Before:

num2 = num1;

num1 38

num2 38After:

Page 46: Class 2   variables, classes methods

46

Reference Assignment• For object references, assignment copies

the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

Page 47: Class 2   variables, classes methods

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

Page 48: Class 2   variables, classes methods

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

Page 49: Class 2   variables, classes methods

49

OutlineVariables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 50: Class 2   variables, classes methods

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

Page 51: Class 2   variables, classes methods

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

Page 52: Class 2   variables, classes methods

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

Page 53: Class 2   variables, classes methods

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

Page 54: Class 2   variables, classes methods

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()); }}

Page 55: Class 2   variables, classes methods

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()); }}

OutputOriginal string: "Change is inevitable"Length of string: 20Mutation #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 FMutated length: 27

Page 56: Class 2   variables, classes methods

56

Quick CheckWhat 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());

Page 57: Class 2   variables, classes methods

57

Quick CheckWhat 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());

26the final frontier.SPACE, THE FINAL FRONTIER.26

Page 58: Class 2   variables, classes methods

58

OutlineVariables and Assignment

Primitive Data Types

Expressions

Data Conversion

Interactive Programs

Creating Objects

The String Class

The Random and Math Classes

Page 59: Class 2   variables, classes methods

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

Page 60: Class 2   variables, classes methods

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

Page 61: Class 2   variables, classes methods

61

The Java API• Get comfortable navigating the online Java

API documentation http://docs.oracle.com/javase/6/docs/api/

Page 62: Class 2   variables, classes methods

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.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing

Page 63: Class 2   variables, classes methods

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.*;

Page 64: Class 2   variables, classes methods

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

Page 65: Class 2   variables, classes methods

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

Page 66: Class 2   variables, classes methods

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

Page 67: Class 2   variables, classes methods

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); }}

Page 68: Class 2   variables, classes methods

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 RunA random integer: 672981683From 0 to 9: 0From 1 to 10: 3From 20 to 34: 30From -10 to 9: -4A random float (between 0-1): 0.18538326From 1 to 6: 3

Page 69: Class 2   variables, classes methods

69

Quick CheckGiven 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

Page 70: Class 2   variables, classes methods

70

Quick CheckGiven 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

Page 71: Class 2   variables, classes methods

71

Quick CheckWrite an expression that produces a random integer in the following ranges:

Range

0 to 12

1 to 20

15 to 20

-10 to 0

Page 72: Class 2   variables, classes methods

72

Quick CheckWrite 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

Page 73: Class 2   variables, classes methods

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

Page 74: Class 2   variables, classes methods

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

Page 75: Class 2   variables, classes methods

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)); }}

Page 76: Class 2   variables, classes methods

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)); }}

Sample RunEnter a number: 4The square route of 4.0 is 2.04.0 raised to the power of 2 is 16.0