SlideShare a Scribd company logo
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));
}
}

More Related Content

Similar to Lecture3.pdf

Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
Adewumi Ezekiel Adebayo
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
MiltonMolla1
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Lecture 5
Lecture 5Lecture 5
Lecture 5
Muhammad Fayyaz
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
2java Oop
2java Oop2java Oop
2java Oop
Adil Jafri
 
Objective c
Objective cObjective c
Objective c
ricky_chatur2005
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
SakhilejasonMsibi
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
Mahmoud Samir Fayed
 

Similar to Lecture3.pdf (20)

Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
2java Oop
2java Oop2java Oop
2java Oop
 
Objective c
Objective cObjective c
Objective c
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Oop java
Oop javaOop java
Oop java
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 

More from SakhilejasonMsibi

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
SakhilejasonMsibi
 
Lecture 4 part 2.pdf
Lecture 4 part 2.pdfLecture 4 part 2.pdf
Lecture 4 part 2.pdf
SakhilejasonMsibi
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
SakhilejasonMsibi
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
SakhilejasonMsibi
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
SakhilejasonMsibi
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
SakhilejasonMsibi
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
SakhilejasonMsibi
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
SakhilejasonMsibi
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
SakhilejasonMsibi
 

More from SakhilejasonMsibi (9)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 4 part 2.pdf
Lecture 4 part 2.pdfLecture 4 part 2.pdf
Lecture 4 part 2.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
ramrag33
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 

Recently uploaded (20)

Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 

Lecture3.pdf

  • 1. Lecture 3: Using Java standard classes
  • 2. Plan ▪ Discuss some Java standard classes ▪ Write some programs using these classes ▪ Learn about these classes BUT ALSO about OOP generally
  • 3. 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
  • 4. 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?
  • 5. 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());
  • 6. 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.
  • 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 ▪ 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.
  • 9. 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));
  • 10. SimpleDateFormat class ▪ These are 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 ▪ 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.
  • 13. 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
  • 14. 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 – …
  • 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; 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) + ".");
  • 19. 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;
  • 20. 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.
  • 21. Math class ▪ Math class: contains class constants and methods to perform mathematical operations.
  • 22. 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
  • 23. Math class ▪ Taken from Table 3.7 from “An Introduction to Object Orientated Programming with Java (5th ed.)” by C. Thomas Wu
  • 24. 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.
  • 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 ▪ 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.
  • 27. 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
  • 28. 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
  • 29. DecimalFormat class ▪ Amend the 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)); } }