Top Banner
Chapter 2 types, variables, methods Pages 34-43 Horstmann
33

Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Dec 22, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Chapter 2

types, variables, methods

Pages 34-43 Horstmann

Page 2: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Types and Variables

• Every value has a type

• Variable declaration examples:

• Variables Store values Can be used in place of the objects they store

String greeting = "Hello, World!";PrintStream printer = System.out;int luckyNumber = 13;

int diameter = 20;Ball A;

‘out’ is a variable in the System class, that holds inside it an object from the PrintStream class.

Objects in PrintStream class contain methods print and println .

Page 3: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Variables

Variables are like shaped boxes….

Variables must be set up ("declared") before use

Each variable is of a certain datatype (int, float, double, String) and each variable has a name (an identifier).

Integer numbers go in integer-shaped variables (labelled int)

Real numbers go in real-number shaped ones (float, double)

Strings (“hello”) can go in string-shaped variables (String)

Page 4: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Declaring variables…….

<datatype> <variable name>;

int x; // a box called x that will hold an integer

double radius; /* a box called radius that will hold a floating point no. */

char ch; // ch can hold a single character

Int, double, float, char all begin with a lower case letter. String begins with a capital letter.

String myName; // myName holds a string of characters

Page 5: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Identifiers

• Identifier: name of a variable, method, or class

• Rules for identifiers in Java: Can be made up of letters, digits, and the underscore

(_) character Cannot start with a digit Cannot use other symbols such as ? or % Spaces are not permitted inside identifiers You cannot use reserved words They are case sensitive

Continued…

Page 6: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Identifiers

• By convention, variable names start with a lowercase letter

• By convention, class names start with an uppercase letter

Page 7: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Self Check

1. What is the type of the values 0 and "0"?

2. Which of the following are legal identifiers?

3. Define a variable to hold your name.

Greeting1gvoid101dalmatiansHello, World<greeting>

Page 8: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Answers

1. int and String

2. Only the first two are legal identifiers3.

String myName = "John Q. Public";

Page 9: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

The Assignment Operator

• Assignment operator is =

• Not used as a statement about equality

• Used to change the value of a variable

int luckyNumber = 13; luckyNumber = 12;

Figure 1:Assigning a New Value to a Variable

Page 10: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Uninitialized Variables

• Error:

Figure 2:An Uninitialized Object Variable

int luckyNumber;System.out.println(luckyNumber);   // ERROR - uninitialized variable

Page 11: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Shortcut: declare and initialize

Initialization: giving a variable a value for the first time

We can declare and initialize in the same line (good practice!)

int x = 20;

double d = 3.14;

Variables must be declared before usage!

myName = “Fintan”;

String myName; // NOPE!

String myName = “Fintan”;

Page 12: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Self Check

4. Is 12 = 12 a valid expression in the Java language?

5. How do you change the value of the greeting variable to "Hello, Nina!"?

Page 13: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Answers

4. No, the left-hand side of the = operator must be a variable

5.

Note that

is not the right answer–that statement defines a new variable called greeting

greeting = "Hello, Nina!";

String greeting = "Hello, Nina!";

Page 14: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Objects and Classes

• Object: entity that you can manipulate in your programs (by calling methods)

• Each object belongs to a class. For example, System.out belongs to the class PrintStream

Figure 3:Representation of the System.out object

We can look up the System class in the Java API at

http://java.sun.com/

(click on “api specifications”)

To find out what it contains.

Page 15: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Methods

• Method: Sequence of instructions that accesses the data of an object

• You manipulate objects by calling its methods

• Class: Set of objects with the same behavior

• Class determines legal methods

Continued…

Objects in the Ball class have methodsMove()HitsFloor()Bounce()

Page 16: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Methods

• Public Interface: Specifies what you can do with the objects of a class

• If a method in an object is declared ‘public’, we can use that method for that object.

• If a method is declared ‘private’, we cannot use that method.

Ball class methods were declared public, so theycould be used by the BouncingBallApplet class foranimation.

Page 17: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Representation of Two String Objects

Figure 4:A Representation of Two String Objects

Strings objects are members of the class String. They have various different useful methods.

We can look up the String class in the Java API athttp://java.sun.com/ ( “api specifications”) To see what it contains.

Page 18: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

String Methods

• length: counts the number of characters in

a string

Continued…

String greeting = "Hello, World!"; int n = greeting.length(); // sets n to 13

Page 19: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

String Methods

• toUpperCase: creates another String object that contains the characters of the original string, with lowercase letters converted to uppercase

Continued…

String river = "Mississippi"; String bigRiver = river.toUpperCase(); // sets bigRiver to "MISSISSIPPI"

We will see length() and toUpperCase() and other methods in the Java API entry for Stringhttp://java.sun.com/ ( “api specifications”)

Page 20: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

String Methods

• When applying a method to an object, make sure method is defined in the appropriate class

System.out.length(); // This method call is an error

Page 21: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Self Check

6. How can you compute the length of the string “mississippi"?

7. How can you print out the uppercase version of "Hello, World!"?

8. Is the following legal:

String river = “mississippi”;

river.println();

Why or why not?

Page 22: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Answers

6.

7.

8. It is not legal. The variable river has type String. The println method is not a method of the String class.

river.length() or “mississippi".length()

String greeting = “Hello World”;System.out.println(greeting.toUpperCase());

Page 23: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Implicit and Explicit Parameters

• Parameter (explicit parameter): Input to a method. Not all methods have explicit parameters.

• Implicit parameter: The object on which a method is invoked

Continued…

System.out.println(greeting) // greeting is an explicit parameter to println n =greeting.length() // length has no explicit parameter

n = greeting.length();System.out.println(greeting);

Page 24: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Implicit and Explicit Parameters

Figure 5:Passing a parameter to the println method

Page 25: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Return Values

• Return value: A result that the method has computed for use by the code that called it

Continued…

int n = greeting.length(); // return value stored in n

The Java API athttp://java.sun.com/ (click on “api specifications”)

Tells us what sort of thing is returned from a given method.

Page 26: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Passing Return Values

• You can also use the return value as a parameter of another method:

• Not all methods return values. Example:

Continued…

System.out.println(greeting.length());

println

Page 27: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

A More Complex Call

• replace method carries out a search-and- replace operation

• As Figure 8 shows, this method call has one implicit parameter: the string "Mississippi" two explicit parameters: the strings "issipp" and "our"

a return value: the string "Missouri"

Continued…

river.replace("issipp", "our") // constructs a new string ("Missouri")

Page 28: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

A More Complex Call

Figure 8:Calling the replace Method

Page 29: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Method Definitions

• Method definition specifies types of explicit parameters and return value

• Type of implicit parameter = current class; not mentioned in method definition

Continued…

Page 30: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Method Definitions

• Example: Class String defines public int length() // return type: int // no explicit parameter

public String replace(String target, String replacement) // return type: String; // two explicit parameters of type String

Page 31: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Method Definitions

• If method returns no value, the return type is declared as void

• A method name is overloaded if a class has more than one method with the same name (but different parameter types)

public void println(String output) // in class PrintStream

Most methods in the Ball class had a return type of void:public void move()

public void println(String output)public void println(int output)

Page 32: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Self Check

9. What are the implicit parameters, explicit parameters, and return values in the method call river.length()?

10. What is the result of the call river.replace("p", "s")?

11. What is the result of the call greeting.replace("World","Dave").length()?

12. How is the toUpperCase method defined in the String class?

Page 33: Chapter 2 types, variables, methods Pages 34-43 Horstmann.

Answers

9. The implicit parameter is river. There is no explicit parameter. The return value is 11

10. "Missississi"

11. 12

12. As public String toUpperCase(), with no explicit parameter and return type String.