objects and classes plan for today - we will learn about: the difference between objects and...

23
Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some specific types of objects: Strings Scanner objects Random objects

Upload: madeleine-bishop

Post on 11-Jan-2016

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Objects and ClassesPlan for Today - we will learn about:

• the difference between objects and primitive values

• how to create (or construct) objects

• some specific types of objects: Strings Scanner objects Random objects

Page 2: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Using and Creating Objects• We already know about:

variables - store data methods - carry out operations and represent behavior types - categories of data (double, int, char, etc)

• Object: an entity in programs that ties together data and operations.

• An object contains: Variables that store its data Methods that carry out its actions

• Example: a RockStar class• Data/Variables: tourSchedule, bandName, monthlyEarnings,

musicStyle• Methods/actions: tour(), perform(), record()

Page 3: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Objects• Manipulate an object by calling methods on it:

System.out is an object - manipulate it by calling method print() or println(): System.out.println(“Hello World”); The identifier out is an object stored in the System class, and

println() is a method we can call on the object out.

• Create an object by using the new operator and a special method called a constructor.

Scanner scan; // set aside memory to hold address of Scanner object

scan = new Scanner(System.in); // new operator + invoking constructor

Page 4: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Variables in Java• In Java, a variable name represents either:

a primitive value, or an object

• Reference variables, which represent objects, hold a reference (an address in memory) to objects (or the value null to indicate that no object is referenced).

• Unlike variables of a primitive type, references do not hold values directly. They hold pointers (ie, memory addresses).

RockStar lennon = new RockStar(“John Lennon”);

1024lennon

bandName tourSchedule...

1024

Page 5: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Declaring Reference Variables• Declaration of object variables looks similar to declarations of

primitive variables:

• double num; // creates variable that holds a real number

• String myName; // creates a String variable that will hold the address in memory of a String.

• To initialize these variables: num = 15; myName = new String(“Mary”);

15

nummyName

2048memory address2048

“Mary”

Page 6: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Creating a New Object• To create a new object, declare a variable of the reference type to

store the object’s location, and construct the new object by using the new operator and invoking the constructor. Assign the new object’s address to the reference variable:

<refType> <varName> = new <refType> (<arguments>);

Examples:

Point origin = new Point(0, 0);

String teacher = new String(“Sensei”);

Scanner reader = new Scanner(System.in);

Page 7: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Shortcut: For Creating String Objects• Strings are used very frequently, so we have this shortcut for

creating a new String object without using the new operator and constructor:

String author = “Reges and Stepp”;

• This is for Strings only, and is equivalent to:

String author = new String(“Reges and Stepp”);

Page 8: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Reassigning Value of a Reference Variable• Since an object variable holds an address, assigning the value of one

object variable to another is different from the same sort of assignment with primitive type variables.

Example: What happens?

int num1 = 33;

int num2 = 45;

num2 = num1;

Note: num1 and num2 still refer to different locations in memory.

Example: What happens? (Hint: 2 references to same object)

String name1 = “Anakin”;

String name2 = “R2D2”;

name2 = name1;

Page 9: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Strings• A String object represents a sequence of characters

String literals are enclosed in double quotes

• String creation: String <varName> = “<your text here>”; String <varName> = new String(“<your text here>”);

• Calling methods on a String:String myName = “Al Gore”;int len = myName.length(); // len is 7int anotherLength = “Charlie Boy”.length(); // anotherLength is

11• To call a method on an object:

<varName>.<methodName>(<arguments>); Methods that are part of an object are not static methods.

Page 10: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

String Indexing• The characters in a String each have an index or position, starting

with index 0 for the first character.

String greet = “so long”;

greet

• Each character in a String is of type char.

• To get the character at a specified position in a String, use the method charAt():

• char firstChar = greet.charAt(0); // firstChar is ‘s’

• char secondChar = greet.charAt(1); // secondChar is ‘o’

‘s’ ‘o’ ‘ ‘ ‘l’ ‘o’ ‘n’ ‘g’

0 1 2 3 4 5 6

Page 11: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

String MethodsSome useful String methods:

Method Name Description

charAt(index) returns character at specific index

substring(index1, index2)

returns substring, indices index1 through index2-1

substring(index) returns substring that starts at position index

length() returns number of characters in the string

toLowerCase() returns a new string with all lowercase letters

toUpperCase()

indexOf(s) returns index of first occurrence of s or -1 if s doesn’t occur

lastIndexOf(s) returns index of last occurrence of s or -1 if s doesn’t occur

replace(c1, c2) returns new string with all occurrences of c1 replaced by c2

indexOf(s, startPos) returns index of 1st occurrence of s starting from startPos

Page 12: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Calling String Methods: Some Examples• Substrings

String artist = “Pink Floyd”; String first = artist.substring(0, 4); // first refers to “Pink” String last = artist.substring(5); // last refers to “Floyd”

• String Length String hey = “hello!!”; int len = hey.length(); // len is 7

• Grab a character

• char first = hey.charAt(0); // first is ‘h’

• char last = hey.charAt(6); // last is ‘!’

Page 13: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

String Conversion• Convert to uppercase or lowercase

String greeting = “Hello World!”; String lowGreet = greeting.toLowerCase(); // “hello world!” String upGreet = greeting.toUpperCase(); // “HELLO WORLD!”

• Remove leading and trailing whitespace String big = new String(“ hello “); String little = big.trim(); // “hello”

• Replace one character with another String hey = “hello there”; String hey2 = hey.replace(‘e’, ‘u’); // ”hullo thuru”

Page 14: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

More String Method Calls• Finding Substrings

String myString = “hello world hello!”; int find = myString.indexOf(“hello”); // find is 0 int find2 = myString.lastIndexOf(“hello”); // find2 is 12 int find3 = myString.indexOf(“hello”, 2); // find3 is 12

• Converting Numeric Values to Strings

• The valueOf() method is static - we call is by prefixing the method name with the class name, String.

• double x = 16.533;

• String xStr = String.valueOf(x); // xStr refers to “16.533”

Page 15: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Scanner: Reading User Input• Create a Scanner object to read console input:

Scanner console = new Scanner(System.in);

• To use Scanner, you must include this import statement at the beginning of your program:

• import java.util.*;

• Think of the object System.in as a data source, associated with the keyboard.

Page 16: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Tokens• The user’s input is a sequence of tokens, separated by whitespace

(blank spaces, tabs, new lines).

• Example: If the user types:

hello 2.7 11 8

22.1 There are 6 tokens. The Scanner object positions its cursor at the

beginning of the user input. Each time a token is read, the cursor advances to the next token. Tokens are read by calling Scanner methods (next(), nextLine(), nextInt(), nextDouble()).

String x = console.next(); // “hello” double y = console.nextDouble(); // 2.7 int z = console.nextInt(); // 11 double t = console.nextDouble(); // 8.0 (could have used nextInt() String r = console.next(); // “22.1” (could have used nextDouble())

Page 17: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Scanner Example• Write Java code that reads 5 integers from the user and prints

their sum.

Scanner reader = new Scanner(System.in);

System.out.print(“Please enter 5 integers: “); // prompt the user

// cumulative sum variable must be created and initialized to

// 0 outside the loop

int sum = 0; // as we read each number, we’ll add it to sum

for(int i = 1; i <= 5; i++) {

int num = reader.nextInt();

sum += num;

}

System.out.println(“Sum is “ + sum);

Page 18: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Scanner Exercises• Write a program that asks the user how many integers they want

to enter, and then computes and prints the average of the entered numbers.

• Write a program that reads a line of text from the user, and prints:

a) the line converted to uppercase

b) the string with all e’s replaced with a’s

c) the part of the string from index 3 on

d) the length of the string

e) the original string with the string “ and all that jazz” added to the end

Page 19: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Random Objects• Sometimes you want numbers that are, or are nearly, random.

• game program simulating roll of a die or shuffling a deck of cards

• Random - in package java.util - implements a random number generator

• Construct a Random object, and use these methods: nextInt(): returns a random integer nextInt(n): returns a random integer in the interval [0, n) nextDouble(): returns a random floating-point number in the

interval [0, 1)

• Example:

Random generator = new Random();

int ran = generator.nextInt(6); // ran is a random # between 0 & 5

int randomDiceThrow = ran + 1; // random throw, 6 sided dice

Page 20: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Exercise• Write a program that prints:

a) a random integer

b) a random integer from 0 to 9

c) a random integer from 1 to 10

d) a random floating-point number in the interval [0, 1)

Page 21: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Objects as Parameters• Recall: When a method has a primitive type parameter, changes made

to the parameter inside the method have no effect on variables in the calling method.

public static void main(String[] args) {

int x = 3;

strange(x); // the value 3 is copied to strange() method’s parameter

System.out.println(x);

}

public static void strange(int x) {

x = 17; // parameter’s value set to 17 (variable x in main unchanged)

}

Page 22: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Objects as Parameters• A reference type variable stores the address of an object, not the

object itself. So when an object is passed to a method, the address of the object is assigned to the method’s parameter. So the method can change the object.

public static void main(String[] args) {

Point q = new Point(0, 0);

System.out.println(q.toString()); // print q’s coords

strange(q);

System.out.println(q.toString());

}

public static void strange(Point p) {

System.out.println(p.toString());

p.move(1, 2); // change to point (1, 2)

}

q

p(0, 0)

Page 23: Objects and Classes Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct) objects some

Outputjava.awt.Point[x=0, y=0]

java.awt.Point[x=0, y=0]

java.awt.Point[x=1, y=2]