Chapter 16: Exceptions, Assertions, and Localization Flashcards
What is an assertion?
An assertion is a boolean expression that you can place at a point in your code where you expect something to be true.
What is an assert statement?
An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError .
What is the syntax of an assert statement?
- assert keyword
- boolean expression
- optional message
example:
assert 1 == age;
assert(2 == height);
assert 100.0 == length : “Problem with length”;
Is the following assert statement valid?
assert (“Cecilia”.equals(name)): “Failed to verify user data”;
Yes.
Is the following assert statement valid?
assert (1);
No. it expects a boolean value.
Is the following assert statement valid?
assert x -> true;
No. it expects a boolean value.
Is the following assert statement valid?
assert.test(5 > age);
No. The syntax is invalid
What happens when assertions are enabled and the boolean expression of an assertion is false?
Java will throw an AssertionError.
What happens when assertions are enabled and the boolean expression of an assertion is true?
Nothing happens and Java will continue execution.
How can we enable assertions using the java command?
// single-file source-code
- java -ea SomeFile.java
- java -enableassertions SomeFile.java
// normal
- java -ea SomeFile
- java -enableassertions SomeFile
By default, assertions are enabled or disabled?
disabled.
Given the package com.demos, how do we run the application and only enable assertions for that package?
java -ea:com.demos… MyMainClass
Given the class Test in package com.demos, how do we run the application and only enable assertions for that class?
java -ea:com.demos.Test MyMainClass
What flag can we use to exclude a package/class from enabling assertions?
-da or -disableassertions
Given the class Test in package com.demos, how do we run the application and enable assertions for that package, but exclude the class Test?
java -ea:com.demos… -da:com.demos.Test MyMainClass
Why should assertions never alter outcomes?
example:
int x = 10;
assert ++x > 10;
This is not a good use of assertions because the outcome of the code will be different depending on wether assertions are turned on.
What is the difference between:
- java.time.LocalDate
- java.time.LocalTime
- java.time.LocalDateTime
- java.time.ZonedDateTime
- java.time.LocalDate: Date with day, month, year
- java.time.LocalTime: Time of day
- java.time.LocalDateTime: Date and time with no time zone
- java.time.ZonedDateTime: Date and time with a specific time zone
What static method exists to get the current value for:
- java.time.LocalDate
- java.time.LocalTime
- java.time.LocalDateTime
- java.time.ZonedDateTime
now()
What static method can we use to get a specific date?
of()
example:
LocalDate d1 = LocalDate.of(2020, 10, 20);
LocalTime t1 = LocalTime.of(6, 15, 30);
…
Create a LocalTime object of 6 hours and 15 minutes.
LocalTime time = LocalTime(6, 15);
Create a LocalTime object of 6 hours, 15 minutes, 0 seconds and 200 nanoseconds
LocalTime time = LocalTime(6, 15, 0, 200);
Given the following objects, create a LocalDateTime object.
LocalDate d1 = LocalDate.of(2020, 10, 20);
LocalTime t1 = LocalTime(6, 15);
LocalDateTime dt1 = new LocalDateTime(d1, t1);
What class can we use to format a date/time object to display standard formats?
DateTimeFormatter
example:
DateTimeFormatter.ISO_LOCAL_DATE // 2020-10-20
DateTimeFormatter.ISO_LOCAL_TIME // 11:22:34
DateTimeFormatter.ISO_LOCAL_DATE_TIME
How can we print a date/time object in a custom format?
example: October 20, 2020 at 11:12
using DateTimeFormatter.ofPattern() and use it with the format() method.
example:
var f = DateTimeFormatter.ofPattern("MMMM dd, yyyy 'at' hh:mm"); somedateobject.format(f);
What does the date/time symbol ‘M’ print?
‘M’ = month and prints the index of the month, starting with 1.
What does the date/time symbol ‘MM’ print?
‘M’ = month and prints the index of the month, starting with 01.
What does the date/time symbol ‘MMM’ print?
‘M’ = month and prints the first three letters of the month (example: JUL).
What does the date/time symbol ‘MMMM’ print?
‘M’ = month and prints the full month name.
What does the date/time symbol ‘a’ print?
‘a’ = a.m./p.m. and prints either AM or PM
What does the date/time symbol ‘z’ print?
‘z’ = Time Zone Name and prints the full time zone name.
example: Eastern Standard Time, EST
What does the date/time symbol ‘Z’ print?
‘Z’ = Time Zone Name and prints the relative timezone.
example: -0400
Given a LocalDateTime dt, why does the following code throw a runtime exception?
var f = DateTimeFormatter.ofPattern("h:mm z"); dt.format(f);
LocalDateTime does not have any information of time zones (z).
Given a LocalDate dt, why does the following code throw a runtime exception?
var f = DateTimeFormatter.ofPattern("h:mm"); dt.format(f);
LocalDate does not have any information of time (h:mm)
What other statement does the exact same as the last statement of this code?
var dt = LocalDateTime.of(2020, Month.OCTOBER, 20, 6, 15, 30); var f = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss");
dt.format(f)
f.format(dt);
Given the following LocalDate, create a formatter to print out: Party’s at October 20, 2020.
LocalDate d1 = LocalDate.of(2020, 10, 20);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“‘Party’’s at’ MMMM d, yyyy”);
Given a LocalDateTime dt, why does the following code throw a runtime exception?
DateTimeFormatter.ofPattern(“‘Time is: hh:mm: “);
There is an incomplete escape sequence (‘).
What is Internationalization?
It is the process of designing your program so it can be adapted. This involves placing strings in a properties file and ensuring the proper data formatters are used.
What is Localization?
supporting multiple locales or geographic regions and includes translating string to different languages and outputting dates and numbers in the correct format for that locale.
How do we get the current locale?
Locale locale = Locale.getDefault();
What does Locale.getDefault() return?
A Locale object containing the locale language (required) and the locale country (optional).
Which Locale formats is correct/incorrect?
- US
- en_US
- US_en
- EN
- enUS
All but en_US is incorrect.
What are three ways to get a Locale other than the default one?
// 1
Locale.GERMAN // -> de
Locale.GERMANY // -> de_DE
//2 new Locale("fr") // fr new Locale("hi", "IN") //hi_IN
//3 new Locale.Builder() .setLanguage("en") .setRegion("US") .build()
How can you change the default Locale of your Java program? (for testing etc)
Locale.setDefault(someLocaleObjectHere);
How do we format the following code to german currency?
double price = 11;
NumberFormat myLocale = NumberFormat.getCurrencyInstance(Locale.GERMANY);
myLocale.format(price);
What package does NumberFormat belong to?
java.text
Given the number n = 53508.
How can we format n to the default locale?
NumberFormat nf = NumberFormat.getInstance()
or
NumberFormat nf = NumberFormat.getNumberInstance()
nf.format(53508)
How can we format a percentage to the default locale?
NumberFormat.getPercentInstance()
How can we format decimal values to the default locale before displaying?
NumberFormat.getIntegerInstance();
How can we format data to a structured object / primitive value, taking into account the Locale?
using NumberFormat.parse();
What does the following code return?
var cf = NumberFormat.getCurrencyInstance(); cf.parse(value); //returns what?
A Number object.
What are two Locale.Category values?
- DISPLAY
- FORMAT
What is the Locale.Category value DISPLAY?
Category used for displaying data about the locale.
What is the Locale.Category value FORMAT?
Category used for formatting dates, numbers, or currencies.
What is a ResourceBundle?
A ResourceBundle contains the locale specific objects to be used by a program. It is like a map with keys and values.
Given the ResourceBundle file Zoo_fr
How do you get this Resource Bundle from java code?
ResourceBundle.getBundle(“Zoo”);
or
ResourceBundle.getBundle(“Zoo”, locale);
Given a ResourceBundle ‘Zoo’ with the default locale, what happens when requesting a ResourceBundle ‘Zoo’ of a locale that does not exist?
It will return the ResourceBundle with the default locale.
What happens when requesting a ResourceBundle of which none exists?
Java will throw a MissingResourceException
What is the maximum number of files Java would need to consider to find the appropriate resource bundle with the following code?
Locale.setDefault(new Locale("hi")); ResourceBundle rb = ResourceBundle.getBundle("Zoo", new Locale("en"));
three
- Zoo_en.properties
- Zoo_hi.properties
3 Zoo.properties
(page 783)
What happens when Java cannot find a key in the requested (and existing) resource bundle?
Use the example: Zoo_fr_FR.properties
After checking Zoo_fr_FR.properties, it will go to Zoo_fr.properties. If it doesn’t exist there, it will go to Zoo.properties.
If it also does not exist there it will throw a MissingResourceException.
Why should you use the getProperty()/setProperty() over get()/set() methods when working with the Properties class?
With getProperty() you can supply a default value. With setProperty() you can assure the data can be read
Which of the following classes contain at least one compiler error? (Choose all that apply.)
class Danger extends RuntimeException { public Danger(String message) { super(); } public Danger(int value) { super((String) null); }
class Catastrophe extends Exception { public Catastrophe (Throwable c) throws RuntimeException { super(new Exception()); c.printStackTrace(); } } class Emergency extends Danger ( public Emergency () {} public Emergency (String message) { super (message); } }
A. Danger
B. Catastrophe
C. Emergency
D. All of these classes compile correctly. E. The answer cannot be determined from the information given.
C. Exception and RuntimeException, along with many other exceptions in the Java API, define a no-argument constructor, a constructor that takes a String, and a constructor that takes a Throwable. For this reason, Danger compiles without issue. Catastrophe also compiles without issue. Just creating a new checked exception, without throwing it, does not require it to be handled or declared. Finally, Emergency does not compile. The no-argument constructor in Emergency must explicitly call a parent constructor, since Danger does not define a no-argument constructor,
What is the output of the following code?
LocalDate date = LocalDate.parse(“2020-04-30”, DateTimeFormatter. ISO_LOCAL_DATE_TIME);
System.out.println(date.getYear () + “ “
+ date.getMonth() + “ “ + date.getDayOfMonth());
A. 2020 APRIL 2 B. 2020 APRIL 30 C. 2020 MAY 2 D. The code does not compile. E. A runtime exception is thrown.
E.
A LocalDate does not have a time element. Therefore, a Date/Time formatter is not appropriate. The code compiles but throws an exception at runtime. If ISO_LOCAL_DATE was used, then the code would compile and option B would be the correct answer.
What is the output of the following code?
LocalDate date = LocalDate.parse(“2020-04-30”, DateTimeFormatter. ISO_LOCAL_DATE);
System.out.println (date.getYear () + “ “
+ date.getMonth()+””+ date.getDayOfMonth());
A. 2020 APRIL 2 B. 2020 APRIL 30 C. 2020 MAY 2 D. The code does not compile. E. A runtime exception is thrown.
B.
The code compiles and option B is the correct answer.
Assume that all of the files mentioned in the answer choices exist and define the same keys. Which one will be used to find the key in line 8?
6: Locale.setDefault(new Locale(“en”, “US”));
7: var b = ResourceBundle.getBundle (“Dolphins”);
8: System.out.println(b.getString(“name”));
A. Dolphins.properties B. Dolphins_US.properties C. Dolphins_en.properties D. Whales.properties E. Whales_en_US.properties F. The code does not compile.
C.
Java will first look for the most specific matches it can find, starting with Dolphins_en_US. properties. Since that is not an answer choice, it drops the country and looks for Dolphins_en.properties, making option C correct. Option B is incorrect because a country without a language is not a valid locale.
Which of the following exceptions must be handled or declared in the method in which they are thrown? (Choose all that apply.)
class Apple extends RuntimeException{} class Orange extends Exception{} class Banana extends Error{} class Pear extends Apple{} class Tomato extends Orange{} class Peach extends Banana {}
A. Apple B. Orange C. Banana D. Pear E. Tomato F. Peach
B, E.
An exception that must be handled or declared is a checked exception. A checked exception inherits Exception but not RuntimeException. The entire hierarchy counts, so options B and E are both correct,
What is the output of the following code?
LocalDateTime ldt = LocalDateTime.of (2020, 5, 10, 11, 22, 33); var f = DateTime Formatter.ofLocalized Time(FormatStyle. SHORT); System.out.println(ldt.format(f));
A. 3/7/19 11:22 AM B. 5/10/20 11:22 AM C. 3/7/19 D. 5/10/20 E. 11:22 AM F. The code does not compile. G. A runtime exception is thrown.
E.
Even though ldt has both a date and time, the formatter outputs only time.
Given the following code:
String n = 1240;
Convert n to a number using the current locale.
NumberFormat nf = NumberFormat.getInstance()
or
NumberFormat nf = NumberFormat.getNumberInstance()
Number myNumber = nf.parse(n);