Lecture 3:
Using Java standard classes
Plan
▪ Discuss some Java standard classes
▪ Write some programs using these classes
▪ Learn about these classes BUT ALSO about OOP
generally
Recall…
▪ We looked at classes and objects.
▪ We saw how we can define our own classes and create
objects from those classes.
▪ Instead of writing our own classes, we can get used to
OOP using Java standard classes.
– Date, SimpleDateFormat
– Scanner
– DecimalFormat
– Math
Date class
▪ Date objects have methods and attributes that can be
used to represent dates
– millisecond precision
▪ When Date objects are created, it set to the current
time.
▪ The date is internally stored as a count of the number
of milliseconds since midnight 1 January, 1970.
– Does it matter how it is stored internally?
Date class
▪ Start by importing java.util:
import java.util.*
▪ Then, in main, declare and create an object:
Date now = new Date();
▪ Date objects have a method called toString() which converts
the stored time into a string that can be printed
System.out.print(now.toString());
Date class
▪ Date also has some methods
– boolean after(Date d)
– boolean before(Date d)
▪ Example: Write a method (in main()) that
– Creates a Date object
– Does some stuff – This is so that when you run it, the two Date
objects will be different.
– Creates another Date object
– Confirms that the first Date object is older the second Date
object.
public class L3 {
public static void main(String[] args) {
Date d1 = new Date();
for (int i = 0; i < 1e6;i++) {
int j = i * i;
}
Date d2 = new Date();
if (d1.before(d2))
System.out.println("d1 is older than d2");
else
System.out.println("d1 is newer than d2");
}
}
}
Creates a Date object
Does some stuff
Creates another
Date object
Confirms that the
first Date object is
older the second
Date object.
SimpleDateFormat class
▪ Date class has a method toString() which converts the
internal stored data format into a string.
▪ But what if we want more options?
▪ SimpleDataFormat objects have methods that can convert
Date objects.
SimpleDateFormat class
▪ Start by importing java.text:
import java.text.*;
▪ Create a SimpleDateFormat object and pass the format:
SimpleDateFormat SDF = new SimpleDateFormat(“dd/MMM/yyyy”);
▪ SimpleDateFormat objects have a method called format() – it
takes a Date object and returns a string of that date in the
correct format.
System.out.println(SDF.format(d1));
SimpleDateFormat class
▪ These are some of the formatting options1.
1Taken from "An Introduction to Object Orientated Programming with Java (5th ed.)" by C.ThomasWu
SimpleDateFormat class
▪ Exercise: Write a program
that:
– creates a Date object
– Displays it with one format
– Displays it with another
format
– Displays what day of the year
it is
Scanner class
▪ Scanner class is used to create objects that read data from a
source.
▪ This source might be from a…
– Keyboard – reading what a user is typing
– File – reading text or data from a file.
Scanner class
▪ Start by importing java.util:
import java.util.*;
▪ Then, in main(), declare and create a Scanner object. On creation,
we pass it where reads from:
Scanner scan = new Scanner(System.in);
OR
Scanner scan = new Scanner(s); //s is a String
OR
Scanner scan = new Scanner(f); // f is a file
Scanner class
▪ Scanner objects have a method next() which returns the next
input value as a String.
▪ Instead of the next() method, which returns a String:
– int nextInt() – returns the next input value as an int.
– byte nextByte() – returns the next input value as a byte
– float nextFloat() – returns the next input value as a float
– …
▪ Also several functions which check if there is anything in the
scanner:
– bool hasNextInt() – returns true if the scanner object has an integer input
– bool hasNextFloat() – returns true if the scanner object has a float input
– …
Scanner class
▪ Exercise: Reading in a user’s name from the console:
– Create a String and a scanner.
– Prompt for a name
– Use scanner to read in what comes next from its source
– Print the name to the screen.
public class L3 {
public static void main(String[] args) {
String firstName;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter your name: ");
firstName = scan.next();
System.out.println("Welcome, " + firstName);
}
}
Create a String and
a scanner
Prompt for a name
Use scanner to read
in what comes next
from its source
Print the name to
the screen
Scanner class
▪ Exercise: Write a program that reads in a person’s first name,
surname and age, greets them by name and tells them what year
they were born in.
String firstName, secondName;
int age;
Scanner scan = new Scanner(System.in);
System.out.print("Enter first name: ");
firstName = scan.next();
System.out.print("Enter surname name: ");
secondName = scan.next();
System.out.print("Enter age: ");
age = scan.nextInt();
System.out.println("Hello, " + firstName + " " + secondName +
". You were born in " + (2019‐age) + ".");
Constants
▪ Similar to a variable, precede with the keyword final
▪ Does not take up memory space
▪ Wherever it appears in your code is replaced the constant
value when you program compiles.
▪ e.g.
▪ Similar to #define in C
final double PI = 3.14159
…
area = 2* 3.14159 * radius;
final double PI = 3.14159;
…
area = 2* PI * radius;
Class methods vs Object methods
▪ Also called static methods vs instance methods
▪ Object methods (instance methods):
– Belong to object, not the class
– Need to create the object first
– Each object created from the class has its own copy of the method
▪ Class method:
– Belong to the class
– They can be called without creating an object first
– To be shared among all objects from the same class
▪ Revisit in more detail when we write our own classes.
Math class
▪ Math class: contains class constants and methods to
perform mathematical operations.
Math class
▪ Part of the java.lang package, automatically included so
don’t need to import specifically.
▪ NB: These are class methods and class constants
▪ Because they are class methods, call them without
declaring an object:
y = Math.abs(x);
y = 2 * Math.PI * r;
y = Math.random();
▪ Math.random() - Returns a random number between 0.0
and 1.0
Math class
▪ Taken from Table 3.7 from “An
Introduction to Object Orientated
Programming with Java (5th ed.)”
by C. Thomas Wu
Math class
▪ Write a program that sets the height and radius of a cylinder
randomly. Height is between 1.0 and 3.0, radius is between 5.0
and 8.0. Calculate the surface area and volume of this cylinder.
public class L3 {
public static void main(String[] args) {
double h, r, a, v;
h = Math.random() * 2.0 + 1.0;
r = Math.random() * 3.0 + 5.0;
a = 2*Math.PI * r * (h+r);
v = Math.PI * Math.pow(r, 2) * h;
}
}
h = Math.random();
h = Math.random() * 2.0;
h = Math.random() * 2.0 + 1.0;
h ranges from 0 to 1
h ranges from 0 to 2
h ranges from 1 to 3
DecimalFormat class
▪ DecimalFormat class is used to provide a standard format for
displaying float point numbers.
▪ We can use format specifiers like %0.1f
▪ But what if we wanted to let someone else specify how many
decimal points we should use?
▪ DecimalFormat objects are created with a specified format and
then any value passed to them is converted into this format.
DecimalFormat class
▪ Start by importing java.text:
import java.text.*;
▪ In main, declare and create an object. On creation, we pass a
pattern (string) that illustrates the number of decimal places:
DecimalFormat df = new DecimalFormat("0.00"); //2 dec places
DecimalFormat df = new DecimalFormat("0.000"); //3 dec places
DecimalFormat class
▪ DecimalFormat objects have a methods format() which returns a
String version of the number to the correct number of decimal
places
float f = 1.2345f;
DecimalFormat df = new DecimalFormat("0.0");
System.out.println(f); //1.2345
System.out.println(df.format(f)); //1.2
DecimalFormat class
▪ Amend the math class program from earlier to display the surface
area and volume correct to 1 decimal place.
public class L3 {
public static void main(String[] args) {
double h, r, a, v;
h = Math.random() * 2.0 + 1.0;
r = Math.random() * 3.0 + 5.0;
a = 2*Math.PI * r * (h+r);
v = Math.PI * Math.pow(r, 2) * h;
DecimalFormat df = new DecimalFormat("0.0");
System.out.println(df.format(a));
System.out.println(df.format(v));
}
}

Lecture3.pdf

  • 1.
    Lecture 3: Using Javastandard classes
  • 2.
    Plan ▪ Discuss someJava standard classes ▪ Write some programs using these classes ▪ Learn about these classes BUT ALSO about OOP generally
  • 3.
    Recall… ▪ We lookedat classes and objects. ▪ We saw how we can define our own classes and create objects from those classes. ▪ Instead of writing our own classes, we can get used to OOP using Java standard classes. – Date, SimpleDateFormat – Scanner – DecimalFormat – Math
  • 4.
    Date class ▪ Dateobjects have methods and attributes that can be used to represent dates – millisecond precision ▪ When Date objects are created, it set to the current time. ▪ The date is internally stored as a count of the number of milliseconds since midnight 1 January, 1970. – Does it matter how it is stored internally?
  • 5.
    Date class ▪ Startby importing java.util: import java.util.* ▪ Then, in main, declare and create an object: Date now = new Date(); ▪ Date objects have a method called toString() which converts the stored time into a string that can be printed System.out.print(now.toString());
  • 6.
    Date class ▪ Datealso has some methods – boolean after(Date d) – boolean before(Date d) ▪ Example: Write a method (in main()) that – Creates a Date object – Does some stuff – This is so that when you run it, the two Date objects will be different. – Creates another Date object – Confirms that the first Date object is older the second Date object.
  • 7.
    public class L3{ public static void main(String[] args) { Date d1 = new Date(); for (int i = 0; i < 1e6;i++) { int j = i * i; } Date d2 = new Date(); if (d1.before(d2)) System.out.println("d1 is older than d2"); else System.out.println("d1 is newer than d2"); } } } Creates a Date object Does some stuff Creates another Date object Confirms that the first Date object is older the second Date object.
  • 8.
    SimpleDateFormat class ▪ Dateclass has a method toString() which converts the internal stored data format into a string. ▪ But what if we want more options? ▪ SimpleDataFormat objects have methods that can convert Date objects.
  • 9.
    SimpleDateFormat class ▪ Startby importing java.text: import java.text.*; ▪ Create a SimpleDateFormat object and pass the format: SimpleDateFormat SDF = new SimpleDateFormat(“dd/MMM/yyyy”); ▪ SimpleDateFormat objects have a method called format() – it takes a Date object and returns a string of that date in the correct format. System.out.println(SDF.format(d1));
  • 10.
    SimpleDateFormat class ▪ Theseare some of the formatting options1. 1Taken from "An Introduction to Object Orientated Programming with Java (5th ed.)" by C.ThomasWu
  • 11.
    SimpleDateFormat class ▪ Exercise:Write a program that: – creates a Date object – Displays it with one format – Displays it with another format – Displays what day of the year it is
  • 12.
    Scanner class ▪ Scannerclass is used to create objects that read data from a source. ▪ This source might be from a… – Keyboard – reading what a user is typing – File – reading text or data from a file.
  • 13.
    Scanner class ▪ Startby importing java.util: import java.util.*; ▪ Then, in main(), declare and create a Scanner object. On creation, we pass it where reads from: Scanner scan = new Scanner(System.in); OR Scanner scan = new Scanner(s); //s is a String OR Scanner scan = new Scanner(f); // f is a file
  • 14.
    Scanner class ▪ Scannerobjects have a method next() which returns the next input value as a String. ▪ Instead of the next() method, which returns a String: – int nextInt() – returns the next input value as an int. – byte nextByte() – returns the next input value as a byte – float nextFloat() – returns the next input value as a float – … ▪ Also several functions which check if there is anything in the scanner: – bool hasNextInt() – returns true if the scanner object has an integer input – bool hasNextFloat() – returns true if the scanner object has a float input – …
  • 15.
    Scanner class ▪ Exercise:Reading in a user’s name from the console: – Create a String and a scanner. – Prompt for a name – Use scanner to read in what comes next from its source – Print the name to the screen.
  • 16.
    public class L3{ public static void main(String[] args) { String firstName; Scanner scan = new Scanner(System.in); System.out.print("Please enter your name: "); firstName = scan.next(); System.out.println("Welcome, " + firstName); } } Create a String and a scanner Prompt for a name Use scanner to read in what comes next from its source Print the name to the screen
  • 17.
    Scanner class ▪ Exercise:Write a program that reads in a person’s first name, surname and age, greets them by name and tells them what year they were born in.
  • 18.
    String firstName, secondName; intage; Scanner scan = new Scanner(System.in); System.out.print("Enter first name: "); firstName = scan.next(); System.out.print("Enter surname name: "); secondName = scan.next(); System.out.print("Enter age: "); age = scan.nextInt(); System.out.println("Hello, " + firstName + " " + secondName + ". You were born in " + (2019‐age) + ".");
  • 19.
    Constants ▪ Similar toa variable, precede with the keyword final ▪ Does not take up memory space ▪ Wherever it appears in your code is replaced the constant value when you program compiles. ▪ e.g. ▪ Similar to #define in C final double PI = 3.14159 … area = 2* 3.14159 * radius; final double PI = 3.14159; … area = 2* PI * radius;
  • 20.
    Class methods vsObject methods ▪ Also called static methods vs instance methods ▪ Object methods (instance methods): – Belong to object, not the class – Need to create the object first – Each object created from the class has its own copy of the method ▪ Class method: – Belong to the class – They can be called without creating an object first – To be shared among all objects from the same class ▪ Revisit in more detail when we write our own classes.
  • 21.
    Math class ▪ Mathclass: contains class constants and methods to perform mathematical operations.
  • 22.
    Math class ▪ Partof the java.lang package, automatically included so don’t need to import specifically. ▪ NB: These are class methods and class constants ▪ Because they are class methods, call them without declaring an object: y = Math.abs(x); y = 2 * Math.PI * r; y = Math.random(); ▪ Math.random() - Returns a random number between 0.0 and 1.0
  • 23.
    Math class ▪ Takenfrom Table 3.7 from “An Introduction to Object Orientated Programming with Java (5th ed.)” by C. Thomas Wu
  • 24.
    Math class ▪ Writea program that sets the height and radius of a cylinder randomly. Height is between 1.0 and 3.0, radius is between 5.0 and 8.0. Calculate the surface area and volume of this cylinder.
  • 25.
    public class L3{ public static void main(String[] args) { double h, r, a, v; h = Math.random() * 2.0 + 1.0; r = Math.random() * 3.0 + 5.0; a = 2*Math.PI * r * (h+r); v = Math.PI * Math.pow(r, 2) * h; } } h = Math.random(); h = Math.random() * 2.0; h = Math.random() * 2.0 + 1.0; h ranges from 0 to 1 h ranges from 0 to 2 h ranges from 1 to 3
  • 26.
    DecimalFormat class ▪ DecimalFormatclass is used to provide a standard format for displaying float point numbers. ▪ We can use format specifiers like %0.1f ▪ But what if we wanted to let someone else specify how many decimal points we should use? ▪ DecimalFormat objects are created with a specified format and then any value passed to them is converted into this format.
  • 27.
    DecimalFormat class ▪ Startby importing java.text: import java.text.*; ▪ In main, declare and create an object. On creation, we pass a pattern (string) that illustrates the number of decimal places: DecimalFormat df = new DecimalFormat("0.00"); //2 dec places DecimalFormat df = new DecimalFormat("0.000"); //3 dec places
  • 28.
    DecimalFormat class ▪ DecimalFormatobjects have a methods format() which returns a String version of the number to the correct number of decimal places float f = 1.2345f; DecimalFormat df = new DecimalFormat("0.0"); System.out.println(f); //1.2345 System.out.println(df.format(f)); //1.2
  • 29.
    DecimalFormat class ▪ Amendthe math class program from earlier to display the surface area and volume correct to 1 decimal place.
  • 30.
    public class L3{ public static void main(String[] args) { double h, r, a, v; h = Math.random() * 2.0 + 1.0; r = Math.random() * 3.0 + 5.0; a = 2*Math.PI * r * (h+r); v = Math.PI * Math.pow(r, 2) * h; DecimalFormat df = new DecimalFormat("0.0"); System.out.println(df.format(a)); System.out.println(df.format(v)); } }