STIA1123 Programming 2
Predefined Class
Chapter Objectives
❑ Learn about objects and reference variables.
❑ Explore how to create & use object from
predefined class in a program.
2
Classes and Objects
• To create an object , we MUST first provide a
definition/description for it
• A class is merely a template for one or more similar
objects. It describes an object’s behaviour and state.
• An object is created from a class. An object is called an
instance of a class
• Object instantiation – process of creating an object from
a class.
• A programmer may use predefined classes in the Java
class libraries OR may define its own class
• An example of common objects from predefined classes
you’ll use in Java application are the String & Scanner
objects
Example of Predefined Java class:
The String Class
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
• To create an object, you must declare a reference variable of the
object class type.
• The reference variable will store the address (reference) of the
object in memory.
• Note: A variable holds either a primitive type or a reference to
an object
• A class name can be used as a type to declare an object
reference variable, e.g.:
String title;
• No object is created with this declaration
• An object reference variable holds the address of an object
• The object itself must be created separately 6
Creating Objects
• Generally, we use the new operator to create an
object
title = new String ("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
• Creating an object is called instantiation
• An object is an instance of a particular class
Java variables
Primitive type Reference variables
variables
Example
Example :
String word;
: word = new String(“Java”);
int x;
x = 45; String variable word stores memory
location (1234), that is the address of
x 45 the memory space where actual data
(Java ) is stored.
Variable x and an int value in 1234 Object word
word
its memory space
reference variable 1234 Java
Creating String objects
General Syntax:
String ObjRefVar = new String(stringLiteral);
eg.
String name = new String(“Haziq”);
Since strings are used frequently, Java provides a
shorthand notation for creating a string:
String name = “Haziq”;
A String Object
String name;
name = new String(“Haziq”);
Object reference Data of the
variable Haziq
object
name
length()
concat() Methods of the object
refers to equals()
object ……
others
Creating String objects
• Two reference variables can refer to the same object:
String name4 = new String(); // Creates an object
String name5 = new String("Socrates"); // Creates another
object
String name6 = name4;
Primitive data types vs. object data types
int x; // variable of primitive data type
String str; // variable of object type
x = 45; // store the actual value
str = "Java Programming"; //store the reference to the object
12
Object and Reference Variables
String str;
str = "Hello there!";
13
Questions
String stud1 = new String(“Ani”);
int studID = 65000;
What does variable stud1 contains?
What does variable studID contains?
Is this allowed? stud1 = studID;
Ani
String stud1;
stud1 = new String(“Ani”); stud1
stud1 = new String(“Obi”); Obi
How many objects were created by the 3 statements above?
How many reference variables are there?
Invoking Methods
• Once an object has been instantiated, we can use the dot
operator to invoke its methods
name.length()
• A method may return a value, which can be used in an
assignment or expression
count = name.length();
• An object consists of both variables and methods. Both of
these are called "members" of the object. Java uses dot
operator for both.
referenceVariable.memberOfObject
Invoking Methods (another example)
The equals() method:
String strA; // first object
String strB; // second object
strA = new String( "The Dog" );
strB = new String( "The Dog" );
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
Object created with no reference variable cannot be accessed
String n1 = new
String(“Ali“);
new String(“Abu“);
n1: String : String
value =
value =
“Ali” “Abu”
This object’s method can’t be invoked
n1
(n1- object reference variable)
Commonly Used String Methods
Some Commonly Used String Methods
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
• A class library is a collection of classes that we can use
when developing programs
• Java contains an extensive library of pre-defined classes
• The Java standard class library is part of any Java
development environment
• Its classes are not part of the Java language per se, but
we rely on them heavily
• Various classes we've already used (System , Scanner,
String) are part of the Java standard class library
• Other class libraries can be obtained through third party
vendors, or you can create them yourself
Class Libraries
• These classes are divided into groups
called packages.
• Package: Contains several related
classes
• Class: Contains several methods
• Method: Set of instructions
Packages
• The classes of the Java standard class library are
organized into packages
• Some of the packages in the standard class library
are:
Package Purpose
java.lang General support
java.applet Creating applets for the web
java.awt Graphics and graphical user interfaces
javax.swing Additional graphics capabilities
java.net Network communication
java.util Utilities
javax.xml.parsers XML document processing
The import Declaration
• When you want to use a class from a package, you
could use its fully qualified name
java.util.Scanner
• Or you can import the class, and then use just the
class name
import java.util.Scanner;
• To import all classes in a particular package, you can
use the * wildcard character
import java.util.*;
The import Declaration
• All classes of the java.lang package are imported
automatically into all programs
• It's as if all programs contain the following line:
import java.lang.*;
• That's why we didn't have to import the System or
String classes explicitly in earlier programs
• The Scanner class, on the other hand, is part of the
java.util package, and therefore must be
imported
The Random Class
• The Random class is part of the
java.util package
• It provides methods that generate
pseudorandom numbers
• A Random object performs complicated
calculations based on a seed value to
produce a stream of seemingly random
values
The Random Class
Some methods of the Random Class
The Random Class
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
• Primitive type variables store data into their
memory space.
• Reference variables store the address of the
object containing the data.
• An object is an instance of a class.
• Operator new is used to instantiate an object.
Chapter Summary
• To use a predefined method, you must know its
name and the class and package it belongs to.
• The dot (.) operator is used to access a certain
method in a class.
• Methods of the class String are used to
manipulate input and output data.
• Random class provides methods that generate
pseudorandom numbers