Documente Academic
Documente Profesional
Documente Cultură
Scanner
Math
GregorianCalendar
2
READING MATERIAL
Chapter 3 Numerical Data
Chapter 4 Defining Your Own Classes - Part 1
3
PRIMITIVE AND REFERENCE TYPES
Primitive types
integers, real numbers, characters, boolean
Reference type
String, BufferedReader, Scanner, …
int num = 5;
creates the variable num that holds the integer value 5.
String s = "How are you?";
creates the object variable s that holds a reference to the
4
String object "How are you?".
OBJECT VARIABLES - 1
The declaration of object variables is similar to the
declaration of primitive variables. e.g.
String name;
The class used to define an object can be thought of as the
type of an object.
An object variable name holds the address of an object.
It is a pointer to the location in the memory where the
object is held.
With String name; the address stored in the object
variable name is 0 (null) as a String object has not been
created yet.
5
OBJECT VARIABLES - 2
To create or instantiate an object so that an object variable
can refer to it, we use new operator.
The new operator returns the address of the newly
created object.
Example:
name = new String(″John″);
The new operator is followed by the name of a special
method, called a constructor. The constructor helps to
set up an object.
Note:
A constructor has the same name as the class.
In the example, the parameter of the constructor is a string
literal that specifies the characters the string object will 6
hold.
OBJECT VARIABLES - 3
After an object is instantiated, the dot operator . is
used to access methods of the class from which the
object is instantiated
Example:
Scanner s = new Scanner(System.in);
int i = s.nextInt();
7
ASSIGNMENT IN PRIMITIVE TYPES
int i, j;
i = 5;
j = 6;
j = i;
// A copy of value in i is assigned to j.
// Both now contain the same value.
8
ASSIGNMENT IN REFERENCE TYPES
String n = ″narrow″;
String w = ″wide″;
// n and w refer to two different String objects.
9
ALIASES
When w = n; is executed
Given
a copy of value in n is assigned to w.
String n = ″narrow″;
n holds an address value which gets
String w = ″wide″; copied to w.
We have Both n and w refer to the same object.
w narrow
wide n
w wide
11
TEMPLATE FOR CLASS DEFINITION
Import Statements
Class Comment
Data Members
Methods
(incl. Constructor)
12
DATA MEMBER DECLARATION
<modifiers> <data type> <name> ;
13
CLASS CIRCLE
// no import statement as java.lang is imported automatically
// This class describes a circle
class Circle {
public int radius; // Data member
public Circle (int r) { // Constructor
radius = r;
}
}
14
INSTANTIATING AN OBJECT
// Test driver of class Circle
class TestCircle {
public static void main(string [] args) {
Circle c1 = new Circle(5);
Circle c2= new Circle(6);
}
}
The new keyword is used to create (instantiate) an object of
class Circle. Object creation is also called object instantiation.
Each object created is called an instance of the class.
new will call the constructor to initialize the newly created
object. References to the objects are assigned to the variables
c1 and c2. 15
INSTANCE VARIABLE
The data stored in each instance of a class is called
instance data. It is declared inside the class but not
inside any method.
The variable radius is an instance variable of class
Circle. Every instance of class Circle will have this
data stored. It is also called an attribute of the class.
Java automatically initializes instance variables with
0. However it is a good practice to initialize them
explicitly with specific values by a constructor.
Instance variables of a class can be referenced in
any method of the class.
16
METHOD DECLARATION
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}
}
17
CLASS BICYCLE
class Bicycle {
// Data Member
public String ownerName;
//Constructor: Initialzes the data member
public Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
} 18
SYNTAX OF A CONSTRUCTOR
public Bicycle ( ) {
ownerName = "Unassigned";
} Statements
19
CONSTRUCTOR
A constructor is a special method that will be
executed when an instance of the class is created.
It is called via the new keyword.
It includes statements for initializing data values.
Its name is the name of the class.
It does not have a return type (not even ″void″).
Multiple constructors with different signatures are
allowed.
For example, in class Bicycle, we can have one more
constructor as
public Bicycle(String owner) {
ownerName = owner;
20
}
CLASS BICYCLEREGISTRATION
// The test driver of class Bicycle
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;
bike1 = new Bicycle( ); // One object
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ); // Another object
bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( );
owner2 = bike2.getOwnerName( );
System.out.println(owner1 + " owns a bicycle.");
System.out.println(owner2 + " also owns one.");
} 21
}
THE PROGRAM STRUCTURE AND SOURCE FILES
BicycleRegistration Bicycle
constructors
MULTIPLE CONSTRUCTOR – 2
Given
class Dice {
public int faceValue;
public Dice() {faceValue = 1; }
} // end class Dice
What if we want to create colored dice?
// Add more attributes and more constructors:
class Dice {
public int faceValue;
public String colour; // new attribute added
public Dice() {faceValue = 1;} // 4 constructors
public Dice(int n) {faceValue = n;}
public Dice(String c) {colour = c;}
public Dice(int n, String c) {faceValue = n; colour = c;}
} 24
MULTIPLE CONSTRUCTOR DEFINITION
Java allows for multiple constructor definition.
Which of these constructors is used depends on
which signature is matched
class Dice {
class TestDice { public int faceValue;
public static void main(String[ ] args) { public String colour;
Dice d = new Dice(); public Dice() {faceValue = 1;}
Dice d1 = new Dice(6); public Dice(int n) {faceValue = n;}
Dice d2 = new Dice(″white″); public Dice(String c) {colour = c;}
} public Dice(int n, String c)
} {faceValue = n; colour = c;}
}
25
INSTANCE METHODS
Methods declared in a class are called instance methods
and they can be invoked through an object of the class.
e.g. The method to roll a Dice object:
public void roll() {
faceValue = (int) (Math.random() * 6)+1);
}
26
USING AN INSTANCE METHOD
class TestDice {
public static void main(String [] args) {
Dice d = new Dice();
System.out.println(″face of the Dice is ″ + d.faceValue);
d.roll();
System.out.println(″face of the Dice is ″ + d.faceValue);
} // end main
} // end class TestDice
class Dice {
public int faceValue;
public String colour;
public Dice() {faceValue = 1; }
public void roll() {
faceValue = (int) (Math.random() * 6)+1;
} 27
} // end class Dice
LOCAL VARIABLE, PARAMETER & DATA MEMBER
An identifier appearing inside a method can be a
local variable, a parameter, or a data member.
The rules are
If there’s a matching local variable declaration or a
parameter, then the identifier refers to the local
variable or the parameter.
Otherwise, if there’s a matching data member
declaration, then the identifier refers to the data
member.
Otherwise, it is an error because there’s no matching
declaration.
Note that a parameter is regarded as a local
variable and therefore it is invalid to have a local
variable to have the same name as a parameter 28
VARIABLE MATCHING
class MusicCD {
String ident;
artist = name1;
title = name2;
title.substring(0,9);
id = ident;
} 29
...
}
CLASS VARIABLES -1
A class variable or static variable refers to a variable
declared with modifier static
Each class variable has only one copy, belonged to the
class but shared by all objects of the same class.
class Dice {
public int faceValue;
public String colour;
public static int max = 6;
public Dice() { faceValue = 1; }
public Dice(String c) { colour = c; }
public Dice(int n) { faceValue = n; }
public void roll() {
faceValue= (int)(Math.random()*max)+1);
} // end roll method
30
} // end class
CLASS VARIABLES -2
There are two ways of accessing class variables with the
use of the access operator .:
Through the class
e.g. Dice.max
Through an object
e.g System.out.println(d1.max); // d1 is a Dice object
class TestDice {
public static void main(String [] args) {
Dice d1 = new Dice(″red″);
Dice d2 = new Dice(5);
// ….
System.out.println(″The max value for d1 is ″ + d1.max);
System.out.println(″The max value for d2 is ″ + Dice.max);
} // end main
31
} // end class TestDice
CLASS METHODS - 1
We use the reserved word static to define a class method.
public static int gcd(int m, int n) {
//the code implementing the Euclidean algorithm
}
class TestDice {
public static void main(String [ ] args) {
Dice d1 = new Dice(″red″);
// ….
Dice.changeMax(5);
System.out.println(″The max value for d1 is ″ + Dice.max);
d1.changeMax(6);
System.out.println(″The max value is now ″+Dice.max); 34
}
}
PRINTING FLOATING POINT NUMBERS
class TestFormat {
public static void main(String [ ] args) {
double num = 123.45678901234567890;
double num1 = 1.2345678901234567890;
System.out.println("num is " + num); // Print 17 digits
System.out.println("num1 is " + num1);
// Last digit printed is not accurate
} // end main
} // end class
35
THE DECIMALFORMAT CLASS
Use a DecimalFormat object to format the numerical
output.
double num = 123.45789345;
System.out.print(num);
123.45789345
System.out.print(df.format(num));
123.458
36
SCANNER METHODS
Use a Scanner object to input data:
Scanner input = new Scanner(System.in);
Method Example
nextByte( ) byte b = input.nextByte( );
nextDouble( ) double d = input.nextDouble( );
nextFloat( ) float f = input.nextFloat( );
nextInt( ) int i = input.nextInt( );
nextLong( ) long l = input.nextLong( );
nextShort( ) short s = input.nextShort( );
next() String str = input.next();
nextLine() String str = input.nextLine();
37
THE MATH CLASS
The Math class contains class methods for commonly
used mathematical functions.
double num, x, y;
x = …;
y = …;
38
SOME MATH CLASS METHODS
Method Description
exp(a) Natural number e raised to the power of a.
int randomNumber =
(int) (Math.floor(Math.random()
* (max – min + 1)) + min);
RANDOM NUMBER GENERATION - 2
We can also use the nextInt(n) method of the Random
class to generate a random number between 0 and n-1,
inclusive.
import java.util.Random;
Random random = new Random();
int number = random.nextInt(11);
//return x, 0 <= x <= 10
independenceDay
= new GregorianCalendar(1965, 7, 9);
//month 7 means August; 0 means January
44
SAMPLE CALENDAR RETRIEVAL
System.out.print(“Today is ” +
(cal.get(Calendar.MONTH)+1) + “/” +
cal.get(Calendar.DATE) + “/” +
cal.get(Calendar.YEAR));
Output
Today is 12/18/2008
45
USEFUL METHODS ON CALENDAR
computeTime()
Converts calendar field values to the time value (millisecond
offset from the Epoch (January 1, 1970 00:00:00.000 GMT )).
isLeapYear(int year)
Determines if the given year is a leap year.
add(int field, int amount)
Adds or subtracts the specified amount of time to the given
calendar field, based on the calendar's rules.
after(Object when)
Returns whether this Calendar represents a time after the time
represented by the specified Object.
before(Object when)
Returns whether this Calendar represents a time before the
time represented by the specified Object.
compareTo(Calendar anotherCalendar)
Compares the time values (millisecond offsets from the Epoch)
represented by two Calendar objects.
get(int field)
Returns the value of the given calendar field. 46