SlideShare a Scribd company logo
1 of 30
Download to read offline
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

Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
ย 
2java Oop
2java Oop2java Oop
2java Oop
Adil Jafri
ย 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
ย 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
ย 

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
ย 
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
ย 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
ย 

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

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
sivaprakash250
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
ย 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
SUHANI PANDEY
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
ย 

Recently uploaded (20)

Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
ย 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
ย 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
ย 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
ย 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
ย 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
ย 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
ย 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
ย 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
ย 

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)); } }