Week 02 - Predefined Classes
Week 02 - Predefined Classes
Predefined Class
Chapter Objectives
2
Classes and Objects
• To create an object , we MUST first provide a
definition/description for it
State/Data Field
Behaviour/Methods
(for complete list, refer to
API documentation)
Creating & Using Object
⬧ A class provides a special type of methods,
known as constructors, which are used to
construct and initialize objects from the class
⬧ Constructors are a special kind of methods
that are invoked to construct objects
⬧ Steps to create and use objects
i. Declaring object reference variables
ii. Creating object
iii. Accessing object by invoking its method
5
Declare Object Reference Variables
General Syntax:
String ObjRefVar = new String(stringLiteral);
eg.
String name = new String(“Haziq”);
String name;
name = new String(“Haziq”);
12
Object and Reference Variables
String str;
str = "Hello there!";
13
Questions
referenceVariable.memberOfObject
Invoking Methods (another example)
if ( strA.equals( strB ) )
System.out.println( "This WILL print.");
The equals( String ) method compares the contents of String objects. It returns
either true or false.
Object without object reference
variable
value =
value =
“Ali” “Abu”
n1
19
public class StringExamples{
public static void main(String [] args){
String word1 = "How"; //String word1=new String ("How");
String word2 = "are"; //String word2=new String ("are");
String word3 = "you"; //String word3=new String ("you");
String word4= word1 + word2 + word3;
System.out.println("UPPERCASE: "+word1.toUpperCase());
System.out.println("word4: "+word4+"?");
System.out.println("length: "+word4.length());
System.out.println("substring: "+word4.substring(3,9));
}//end main
}//end class
UPPERCASE: HOW
word4: Howareyou?
OUTPU
T:
length: 9
substring: areyou
Howareyou
word4
Class Libraries
import java.util.Random;
/* Create a random number that is greater than or equal to 0,
and less than 100. (It is set to run 20 tests.)*/
public class JavaRandomClassExample {
public static void main(String[] args){
int numTests = 20; // run 20 random examples
Random random = new Random();// create a new Java Random object
for ( int i=0; i<numTests; i++ ){
int randomInt = random.nextInt(100); // get the next random int
System.out.print(randomInt +" ");
}
}
}
Sample output:
27 43 22 0 86 60 27 90 11 30 54 68 70 73 58 0 12 79 37 10
Chapter Summary