Objects in Java, String
objects and String instance methods , Dot notation
Compsci 101 Lecture 07
Course Book: Chapter 7
Revision
What is the output from the following code?
public class MyProgram { public void start() {
int num1 = Math.min(15,7);
int num2 = num1 * 2 / 9;
double num3 = num1 + 10.4;
int num4 = ((int)Math.random())*6;//0<=rndm<1 System.out.println( "num1: " + num1 );
System.out.println( "num2: " + num2 );
System.out.println( "num3: " + num3 );
System.out.println( "num4: " + num4 );
}}
Java is object oriented
•Java is an object oriented programming language.
•Our programs as comprising many objects which pass requests to, and receive requests from, other objects.
•In particular, Strings are objects. Which is why we need to know about objects now
•Strings, have many special properties so that, although objects, we can treat them like primitive variable in the main
•However, now we have to see the object-like properties of Strings to make progress
Objects and classes
•Any data in Java is either:
– of primitive type, or – of object type.
•We have already looked at the primitive types – ints, doubles etc. All other data in Java are of object type.
•Every object of a particular class – is said to be an instance of the class.
•A class definition describes the data in the objects of the class, how an object is to be created, and, importantly, provides methods that are associated with such objects.
Declaring variables of object type
All variables must have a type. We have seen how to declare variables of primitive type:
int count;
double yourMoney;
Declaring variables of an object type is done the same way, except the type is the name of some class:
e.g. String s;
Point middle;
type of the variable variable name (class name) (identifier)
Class Names
•For example:
String s;
Point p;
Horse myHorse;
Names of object types should begin with a capital letter - this is just a convention.
•There are thousands of predefined class types we can use from the Java libraries.
•We can also design our very own classes - we will study this later.
Initialising object variables
•To initialise a primitive variable, we first declare the variable and then assign some value to it:
int i;
i = 10;
•To initialise an object variable, we must construct a new object using the keyword new:
<identifier> = new <Classname>();
•For example:
String s;
Point p;
s = new String( "Hello World" );
p = new Point( 4, 7 );
•However, Strings are very special objects in Java
Creating String objects
We previously have used Strings inside our System.out.println() statements:
System.out.println( "Hi World" );
Strings are are the only type of object that can be used without first having to be explicitly created with new.
They are treated in this special way because they are such common objects - when the compiler comes across a String literal, such as "Hello" it automatically replaces the literal with code that constructs a new String object:
System.out.println(new String("Hello"));
Instance methods
We have seen how a class like Math provides us with a swag of static or class methods. With classes that actually have objects Java provides a different sort of method. We get things to happen in our programs by calling instance methods on the objects we have created - this is also done using dot notation:
<objectName>.<methodName>() or
<objectName>.<methodName>()( <actualparameters> )
The difference between an instance method and static method is the use of an object identifier instead of a class identifier.
Math.min(34,65) // static class method String s;
s.substring(1,5); // instance method
Meaning of instance methods
<objectName>.<methodName>() or
<objectName>.<methodName>()( <actualparameters> )
This causes the specified method to be carried out on the specified object, using the parameters, if any.
String s = new String( "A few words" );
int len = s.length();
The method call s.length() causes the String method length() to operate on s itself, and to find and return as value the number of characters the String s contains. The number that is returned by the length() method is then assigned to the int variable len. After the assignment statement, the variable len will store the int value 11, in this case.
Java API revisited
The instance methods that are available depend on the object’s type or class. For any class, you can get a complete list of the methods available from the Java API (Application Programmer's Interface).
A link to the API reference page can be found on the Resources page of the CompSci 101 website. You can even download the entire API so you can view it locally on your computer (a download of the API is available on the Computer Science CD).
Strings: some instance methods
length() returns the length of this String
toUpperCase() returns a new String with all the
characters of this String converted to upper case.
replace(char oldChar, char newChar) returns a new String that is like this String with ALL the occurrences in the String of oldChar replaced by newChar.
replaceFirst(String oldie, String newie) returns a new String that is like this String with the first
occurrence in the String of oldie replaced by newie.
trim() returns a new String that is like this String with all spaces removed from the start and the end .
concat(String s) returns a String that concatenates (joins, appends) a copy of s to the end of a copy of this
String (same as +).
Using String instance methods
The following code calls a selection of the instance methods on a String object:
public class MyProgram { public void start() {
String word = new String("Bytes");
System.out.println(word);
System.out.println(word.toUpperCase());
System.out.println(word.toLowerCase());
System.out.println(word.length());
System.out.println(word.replace('t','k'));
word = new String(" Class ");
System.out.println(word);
System.out.println(word.trim());
System.out.println(word.concat(" 101"));
System.out.println(word.replace(' ','&' ));
System.out.println(word.replace('l','r'));
Strings: index value
Other methods work with the positions of individual characters in the String. Every character in a String has a unique index number, starting at 0, as shown below:
String s = new String( "Hello" );
s
Strings: instance methods
charAt( int positionChar ) returns the char which is in the positionCharth position in the String.
substring( int start, int end ) returns a copy of the part of this String that starts at the startth character and ends immediately before the endth character
substring( int start ) returns a copy of the part of this String that starts at the startth character and ends at the last character
indexOf( char c ) returns the position (an int) of the first occurrence of the character c in the String.
indexOf( String s ) returns the position (an int) of
Strings: Example 2
The following code calls a selection of the instance methods on a String:
public class MyProgram { public void start() {
String word = new String(" fire fox ");
System.out.println(word.substring(1,5));
System.out.println(word.substring(2,5));
System.out.println(word.substring(6));
System.out.println(word.charAt(1));
System.out.println(word.charAt(8));
System.out.println(word.replace('f','s'));
word = word.trim();
System.out.println( word.indexOf('e'));
System.out.println( word.indexOf("f"));
System.out.println( word.indexOf("ox"));
System.out.println( word.indexOf("p"));
}
Assigning returned values
The indexOf()method returns an int. So, when we call indexOf(), we can assign the result to an int variable.
String greeting = "Hello Hello";
int position = greeting.indexOf( "ell" );
The charAt()instance method returns a char. So, when we call charAt(), we can assign the result to a char variable:
char letter = s.charAt( 0 );// 1st letter The toLowerCase()instance method returns a String:
String lowerCaseWord = word.toLowerCase();
Exercise
s.substring(0, 1) returns the first character in the String s as a String. Complete the code below which prints out the last two letters of the word referred to by variable, word, in upper case. You can assume that word always contains two or more characters. Your code should work correctly even if the actual word is changed.
/*Your program must work for any word, without having to alter your code */
public class ProgramClassL07 { public void start() {
String word = new String( "Bait" ); //may change System.out.println( "The word is: " + word);
System.out.println
("The last two letters are: ");
}
The concatenation operator, +
We have seen the + sign used to concatenate two Strings:
String s = "Hello" + " World";
-It’s the same as:
String s = "Hello".concat(" World");
String s = (new String("Hello")).concat(" World");
–pronounced it “is joined to” or “is appended to”
–it creates a new String formed from the two parts
–if one of the operands is a String and the other operand is a primitive type, the primitive value is converted automatically to a String value
Exercise
Complete the following code which prints out a person's number and name. You must use a single
System.out.println() statement. It should print the number, title, then the initial of the first name with a full stop, then the surname.
public class ProgramClassL07 { public void start() {
// display 45. Ms. F. Fish int number = 45;
String title = "Ms";
String firstName = "Freda";
String lastName = "Fish";
System.out.println(
}
Constructing objects
• When we construct a new object, we often have to include information about the object
• For example:
–when constructing a String object, we may include the characters we want the string to contain
s = new String( "Hello World" );
–when constructing a Point object we may include two int values that are its coordinates. (Point is a java API class.)
p = new Point( 4, 7 );
•Exceptional case of strings:
s = "Hello World";
Assignment of objects
•Assignment with objects looks just like assignment with primitive types:
<identifier> = <object definition>;
•e.g. Point p, q;
q = new Point(3,4);
p = q;
•We can think of “=“ as meaning “names” - names of objects are used just as in everyday life.
•When we use the identifier of primitive type variable in an expression we always get a copy of the variable.
•Because objects are thought to be much larger blocks of data they are never copied automatically.
•Strings are never copied but they are special and may never be altered so that they do behave like primitives, all the same
Assignment meaning
Primitive type int i, j;
i = 10;
j = i; // makes a copy of i i = 20;
System.out.println("i: "+i+", j: "+j);
Object type Point p, q;
p = new Point(3,4);
q = p; // does not make a copy of p
p.translate (10,10); // adds 10 to both coords System.out.println("p: "+p+", q: "+q);
References to objects
•We usually describe how Java implements object variables on the computer, because assignment for primitive and objects is exactly the same.
•Memory is allocated when any variable is first declared.
Each primitive variable of the one type takes up the same space. For example, an int is 4 bytes.
•However:
Objects of the same class may use different amounts of space. For example, two String objects may store a different number of characters and hence require different amounts of space. So, it is not possible to allocate the memory for an object when the variable is first declared.
•This problem is solved by object variables storing a memory address - each address can be stored in the same amount of space.
•When an object is constructed, the space for the object is allocated from free memory and the variable simply stores the location of the object.
Initialising object variables
<identifier> = new <Classname>();
The
new <Classname>()
expression on the right hand side creates a new object of the required type and gives us the address of this object in the computer’s memory A variable of an object type actually contains the memory address of the object. This is why such variables are sometimes called reference variables - because they refer to an object
.
References to objects
We need to visualise object variables in a different way to primitive variables.
This is how we can visualise a primitive variable:
int i;
i = 10;
and this is how we can visualise an object variable:
String s;
s = new String("Hello");
NOTE: Object variables initially have a default value of null - we will return to look at null later in the course.
10
? i
i
null
"Hello"
s s
Assigning to primitive variables
With primitives, a copy of the value in the variable on the right hand side is assigned to the variable on the left:
int a = 10; // a is set to the value of 10 int b = a; // b is set to the value of a
a b
contents of a are copied into b
10 10
Assigning to object variables
With object variables, when we assign one object variable to another object variable, we copy the reference so that both variables end up referring to the same object:
Point p1 = new Point( 2,6 );
// p1 names a new Point (2,6) Point p2 = p1;
// p2 also names the object named p1
New objects must be created by using the keyword new.