Using and Creating Objects

Declaring and Initializing Reference Variables

int num;
String myName;

num = 15;
name = new String("Mary");

                              ^^^ Invoking, or calling, the constructor of the String class to set up the String object.

Once an object has been instantiated, we use the dot operator to call its methods:

Ex: System.out.println("Yes, Sensei");

The dot appears right after the name of the object, and is followed by the name of the method which is being called. For example, the String class contains a length method, which returns the number of characters in a string:

Ex: int len = name.length();   // In this example, len is set to 4

Combining the declaration and initialization of an object variable
+ a shortcut for String objects

String author = new String("Cohoon and Davidson");

Since Strings are used so frequently, we can also use this shortcut:

String author = "Cohoon and Davidson";  // For Strings only, we have this shortcut for avoiding the use of new + constructor to create an object

Reassigning the 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.

Ex: What happens when these statements are executed?
int num1 = 33;
int num2 = 45;
num2 = num1;

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

Ex: What happens when these statements are executed?
String name1 = "Anakin";
String name2 = "R2D2";
name2 = name1;

Note: Now we have two references to the same object.

More on the String Class

Concatenation of Strings

String hey = "hello";
String you = "Mary";

String message = hey + " " + you;   // message refers to "hello Mary"

If you concatenate a string with a value that is not a string, the non-string is converted to a string:

Ex: String emergency = "Call " + 911;   // sets emergency to "Call 911"

Exercise: What is printed?
int x = 3;
int y = 2;
System.out.println(x + y + " friends are waiting for you.");
System.out.println("The number of friends waiting for you: " + x + y);


String artist = "Pink Floyd";
String first = artist.substring(0, 4);  // first refers to "Pink"

substring(1st index to include, 1st index to exclude)
substring(1st index to include)

String last = artist.substring(5);  // last refers to "Floyd"

Note that numbering of positions in the string begins at 0.

String Length and Characters within a String

String hey = "hello";
int len = hey.length(); // len is 5

Syntax: stringName.charAt(n)

int firstChar = hey.charAt(0); // firstChar is 'h'
int secondChar = hey.charAt(1);  // secondChar is 'e'
int thirdChar = hey.charAt(2);  // thirdChar is 'l'

String Conversions


String greeting = "Hello World";
String greetingLower = greeting.toLowerCase();  // "hello world"
String greetingUpper = greeting.toUpperCase();  // "HELLO WORLD"

String big = new String("    hello   ");
String little = big.trim();  // little refers to "hello"

String hey = "hello";
String hey2 = hey.replace('e', 'u');  // hey2 refers to "hullo"

Finding Substrings

String myString = "hello world hello";
int find = myString.indexOf("hello");   // find is 0

int find2 = myString.lastIndexOf("hello");  //find2 is 12

Converting Numeric Values to Strings

double x = 16.553;
String xStr = String.valueOf(x);  // xStr refers to "16.553"

Note that valueOf is a static method. We call it by prefixing the method name with the class name (instead of an object name).

Exercise: Write a program that reads a line of text from the user, and prints to the console window:
a) the original string
b)the length of the string
c) the position of the first occurrence of  the string "hello" in the input string
d) the string converted to uppercase
e) the string with all e's changed to a's
f) the part of the string from position 3 on.
g) the original string with the string "and all that jazz" added to the end

The Random Class

Sometimes you want numbers that are, or are nearly, random. For example, a game program might want a random number to simulate the roll of a die or the shuffle of a deck of cards. The Random class in package java.util implements a random number generator. To generate random numbers, you construct an object of class Random, and use the following methods.

Random generator = new Random();
int ran = generator.nextInt(6);  // ran is a random number between 0 and 5
int randomDiceThrow = ran + 1;  //  random throw of a 6 sided dice

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)