Building Java Programs: Parameters and Objects
Building Java Programs: Parameters and Objects
Chapter 3
Parameters and Objects
*************
*******
***********************************
**********
* *
**********
*****
* *
* *
*****
4
A redundant solution
public class Stars1 {
public static void main(String[] args) {
lineOf13();
lineOf7(); • This code is redundant.
lineOf35();
box10x3();
box5x4(); • Would variables help?
}
Would constants help?
public static void lineOf13() {
for (int i = 1; i <= 13; i++) {
System.out.print("*"); • What is a better solution?
}
System.out.println(); – line - A method to draw a
}
public static void lineOf7() {
line of any number of stars.
for (int i = 1; i <= 7; i++) { – box - A method to draw a
System.out.print("*");
} box of any size.
System.out.println();
}
public static void lineOf35() {
for (int i = 1; i <= 35; i++) {
System.out.print("*");
}
System.out.println();
}
...
5
Parameterization
• parameter: A value passed to a method by its caller.
7
mai lin ******
n e *
1 lin ************
3 e *
6
Declaring a parameter
Stating that a method requires a parameter in order to run
• Example:
public static void sayPassword(int code) {
System.out.println("The password is: " + code);
}
7
Passing a parameter
Calling a method and specifying values for its parameters
name (expression);
• Example:
public static void main(String[] args) {
sayPassword(42);
sayPassword(12345);
}
Output:
The password is 42
The password is 12345
8
Parameters and loops
• A parameter can guide the number of repetitions of a loop.
public static void main(String[] args) {
chant(3);
}
Output:
Just a salad...
Just a salad...
Just a salad...
9
How parameters are passed
• When the method is called:
– The value is stored into the parameter variable.
– The method's code executes using that value.
11
Stars solution
// Prints several lines of stars.
// Uses a parameterized method to remove redundancy.
public class Stars2 {
public static void main(String[] args) {
line(13);
line(7);
line(35);
}
12
Multiple parameters
• A method can accept multiple parameters. (separate by , )
– When calling it, you must pass values for each parameter.
• Declaration:
public static void name (type name, ..., type name) {
statement(s);
}
• Call:
methodName (value, value, ..., value);
13
Multiple params example
public static void main(String[] args) {
printNumber(4, 9);
printNumber(17, 6);
printNumber(8, 0);
printNumber(0, 8);
}
public static void printNumber(int number, int count) {
for (int i = 1; i <= count; i++) {
System.out.print(number);
}
System.out.println();
}
Output:
444444444
171717171717
00000000
16
Value semantics
• value semantics: When primitive variables (int, double) are
passed as parameters, their values are copied.
– Modifying the parameter will not affect the variable passed in.
mystery(z, y, x);
mystery(y, x, z);
}
– Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";
19
Strings as parameters
public class StringParameters {
public static void main(String[] args) {
sayHello("Marty");
String teacher = "Bictolia";
sayHello(teacher);
}
public static void sayHello(String name) {
System.out.println("Welcome, " + name);
}
}
Output:
Welcome, Marty
Welcome, Bictolia
...
21
Stars solution, cont'd.
...
• Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot); // 11.0
System.out.println(Math.min(3, 7) + 2); // 5
- Math.abs(-
42 42)
4
mai 2
n 2.7
1
3
Math.round(2.71
)
26
Math questions
• Evaluate the following expressions:
– Math.abs(-1.23)
– Math.pow(3, 2)
– Math.pow(10, -2)
– Math.sqrt(121.0) - Math.sqrt(256.0)
– Math.round(Math.PI) + Math.round(Math.E)
– Math.ceil(6.022) + Math.floor(15.9994)
– Math.abs(Math.min(-3, -5))
• Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) Math.pow(10, 3); // 1000
29
More about type casting
• Type casting has high precedence and only casts the item
immediately next to it.
– double x = (double) 1 + 1 / 2; // 1
– double y = 1 + (double) 1 / 2; // 1.5
30
Returning a value
public static type name(parameters) {
statements;
...
return expression;
}
• Example:
// Returns the slope of the line between the given points.
public static double slope(int x1, int y1, int x2, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
return dy / dx;
}
public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}
33
Fixing the common error
• Instead, returning sends the variable's value back.
– The returned value must be stored into a variable or used in an
expression to be useful to the caller.
public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}
34
Objects and Classes;
Strings
Classes and objects
• class: A program entity that represents either:
1. A program / module, or
2. A type of objects.
36
Objects
• object: An entity that contains data and behavior.
– data: variables inside the object
– behavior: methods inside the object
• You interact with the methods;
the data is hidden in the object.
37
Blueprint analogy
iPod blueprint/factory
state:
current song
volume
battery life
behavior:
power on/off
change station/song
change volume
choose random song
creates
38
Strings
• string: An object storing a sequence of text characters.
– Unlike most other objects, a String is not created with new.
– Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";
39
Indexes
• Characters of a string are numbered with 0-based indexes:
String name = "R. Kelly";
index 0 1 2 3 4 5 6 7
character R . K e l l y
40
String methods
Method name Description
indexOf(str) index where the start of the given string appears
in this string (-1 if not found)
length() number of characters in this string
substring(index1, index2) the characters in this string from index1
or (inclusive) to index2 (exclusive);
substring(index1) if index2 is omitted, grabs till end of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters
42
Modifying strings
• Methods like substring and toLowerCase build and return
a new string, rather than modifying the current string.
String s = "lil bow wow";
s.toUpperCase();
System.out.println(s); // lil bow wow
43
Interactive Programs with
Scanner
Input and System.in
• interactive program: Reads input from the console.
– While the program runs, it asks the user to type input.
– The input typed by the user is stored in variables in the code.
45
Scanner syntax
• The Scanner class is found in the java.util package.
import java.util.*; // so you can use Scanner
– Example:
Scanner console = new Scanner(System.in);
46
Scanner methods
Method Description
nextInt() reads an int from the user and returns it
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user
Output:
What is your age? Timmy
java.util.InputMismatchException
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...
50
Strings as user input
• Scanner's next method reads a word of input as a String.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
name = name.toUpperCase();
System.out.println(name + " has " + name.length() +
" letters and starts with " + name.substring(0, 1));
Output:
What is your name? Chamillionaire
CHAMILLIONAIRE has 14 letters and starts with C
51
Strings question
• Write a program that outputs a person's "gangsta name."
– first initial
– Diddy
– last name (all caps)
– first name
– -izzle
Example Output:
Type your name, playa: Marge Simpson
Your gangsta name is "M. Diddy SIMPSON Marge-izzle"
52
Strings answer
// This program prints your "gangsta" name.
import java.util.*;
53