Podcast
Questions and Answers
What is the primary purpose of using assert
statements in programming?
What is the primary purpose of using assert
statements in programming?
- To catch coding errors and unexpected conditions during development and testing. (correct)
- To optimize code execution speed.
- To handle expected runtime errors and allow program recovery.
- To validate method parameters in production code.
An AssertionError
will be thrown if an assert
statement's logical expression evaluates to true
.
An AssertionError
will be thrown if an assert
statement's logical expression evaluates to true
.
False (B)
What type of exception is recommended to be thrown when validating method parameters and an invalid value is found?
What type of exception is recommended to be thrown when validating method parameters and an invalid value is found?
IllegalArgumentException
The ______()
method can be used to convert a string to an array of characters.
The ______()
method can be used to convert a string to an array of characters.
Match the regular expression metacharacters with their meanings:
Match the regular expression metacharacters with their meanings:
Which of the following is NOT a typical use case for assert
statements?
Which of the following is NOT a typical use case for assert
statements?
StringBuilder is used to process files
StringBuilder is used to process files
What is the term for splitting a string into an array of substrings based on a delimiter or pattern?
What is the term for splitting a string into an array of substrings based on a delimiter or pattern?
In regular expressions, the metacharacter ______
is used to specify a range of characters.
In regular expressions, the metacharacter ______
is used to specify a range of characters.
What is the main difference between using String
and StringBuilder
for text manipulation?
What is the main difference between using String
and StringBuilder
for text manipulation?
When should you prefer using an Exception
over an Assertion
?
When should you prefer using an Exception
over an Assertion
?
If a method's parameter is declared as an integer, manual validation of the parameter's data type is still necessary.
If a method's parameter is declared as an integer, manual validation of the parameter's data type is still necessary.
What is a term used for a pattern of searching purposes?
What is a term used for a pattern of searching purposes?
The extra space allotment in StringBuilder allows us to easily ______ characters to the end
The extra space allotment in StringBuilder allows us to easily ______ characters to the end
Besides 'append', which StringBuilder methods are not avaiable for String?
Besides 'append', which StringBuilder methods are not avaiable for String?
What outcome should never happen in the production code?
What outcome should never happen in the production code?
String implements replace differently that StringBuilder
String implements replace differently that StringBuilder
In Java, what is the String method called that allows strings to be broken apart?
In Java, what is the String method called that allows strings to be broken apart?
The ______ statement is typically only used during development and testing, and may be disabled
The ______ statement is typically only used during development and testing, and may be disabled
Which one is not a functionality of StringBuilder?
Which one is not a functionality of StringBuilder?
Flashcards
Assert Statement
Assert Statement
A statement to ensure conditions in programs are met while running. Useful for debugging.
Assertion Error
Assertion Error
Terminates the program if the condition is false, indicating an unexpected state.
When to use Assert
When to use Assert
Used during development and testing to catch coding errors; may be disabled in production.
Validating Parameters
Validating Parameters
Signup and view all the flashcards
IllegalArgumentException
IllegalArgumentException
Signup and view all the flashcards
Exceptions
Exceptions
Signup and view all the flashcards
Assertions
Assertions
Signup and view all the flashcards
toCharArray()
toCharArray()
Signup and view all the flashcards
split() method
split() method
Signup and view all the flashcards
Regular Expression (Regex)
Regular Expression (Regex)
Signup and view all the flashcards
Why use Regex?
Why use Regex?
Signup and view all the flashcards
[and]
[and]
Signup and view all the flashcards
Strings
Strings
Signup and view all the flashcards
StringBuilder
StringBuilder
Signup and view all the flashcards
StringBuilder (vs String)
StringBuilder (vs String)
Signup and view all the flashcards
append()
append()
Signup and view all the flashcards
Study Notes
- Validation and Text Manipulation are important aspects of programming.
The assert Statement
- Ensures certain conditions in programs are met while running.
- Programs may behave unexpectedly if incorrect data is passed.
- Errors may make tracing back sources more difficult.
- Code may run with "rotten" data, causing problems.
- Can be accomplished with the
assert
statement. assert
statements include a logical expression.- If the expression is
true
, the program proceeds normally. - However, if the expression is
false
, anAssertion Error
occurs, terminating the program. - Primarily used during development and testing, it can be disabled.
BlueJ
allows assertions by default used as a learning tool.- This may not always be the case with other IDE's.
- An assertion should never fail in production code.
Assertion Examples
- Student grade should fall between
[0, 1]
. - Code example
double grade = 0.95; assert 0 <= grade && grade <= 1.0;
ensures this. - Can pass a message to be displayed alongside the
Assertion Error
using:assert condition : message;
- This is useful for debugging unexpected values.
double grade = -0.95; assert 0 <= grade && grade <= 1.0 : "Grade must be in range [0,1]: " + grade;
will display the grade if the condition is not met.
Validating Parameters
- A method expects arguments to be valid.
- Data types of parameters will be enforced automatically.
- Manual checks of parameter values can be done to enforce design rules.
- If an argument with an invalid value is found, an exception of choice can be thrown to terminate the program.
IllegalArgumentException
is a suitable choice.- This reveals where and why the program failed.
- Example code:
public void setGrade (double grade) {
boolean valid = (0 <= grade && grade <= 1.0);
if(!valid){
throw new IllegalArgumentException("grade must be in range [0,1]: " + grade);
}
this.grade = grade;
}
- If
grade = -1.0
is inputted anIllegalArgumentException
occurs.
Assertion vs Exception
- Assertions and exceptions have similar theory, but different applications.
- Assertions are used to catch coding errors and mistakes.
- Assertions throw
Assertion Error
exceptions. - Errors are typically serious, abnormal conditions that are unrecoverable.
- Exceptions are typically used for runtime errors.
- There are many types.
- Exceptions may be reasonable issues that the program may expect and recover from.
Eg:
a failed network connection or incorrect user input.
Text Manipulation toCharArray
toCharArray()
can convert a String to an array of characters.- Example:
"abc".toCharArray(); // generates char[] = {'a', 'b', 'c'};
- Arrays have access to utility functions that Strings may not have.
- Enhanced for loop usage example:
String line = "Hello World";
for(int i=0; i<line.length(); i++){
if(Character.isDigit(line.charAt(i))){ ... }
...
}
char[] lineArray = line.toCharArray();
for(char c: lineArray){
if(Character.isDigit(c)){ ... }
...
}
Text Manipulation - split
split()
method splits a string to an array of strings based on a regular expression (regex).- Inputting a character to split is the simplest form.
- Example:
"John A. Macdonald".split(" "); // yields String[] = {"John", "A.", "Macdonald"}
- Example:
"ACS-1904-003".split("-"); // yields String[] = {"ACS", "1904", "003"}
Regular Expression - Regex
- A regular expression is a pattern used for searching purposes.
[and]
specifies any character within the brackets.+
specifies one or more of a preceding character.-
specifies a range of characters.
Manipulating Text - Split
- Splitting a string allows iteration over all words in a given test.
CatenateWords.java
andValidateFormat.java
are text examples.
Manipulating Text - StringBuilder
- Strings are immutable, meaning they cannot be changed once initialized.
- However, the value of a String variable can be changed.
- This change allocates new memory area.
- Code example:
String h = "Hello ";
String s = "World";
h += s; // h = "Hello World"
- The value
h
points to a new location in memory after the change. - The original value
“Hello”
may be garbage-collected. - Excessive text manipulation is inefficient, which is where
StringBuilder
comes in. - Methods like
append
,insert
,delete
, andreverse
are available forStringBuilder
and notString
. Stringbuilder
implements replace differently thanString
.
StringBuilder - Examples
-
An instance of
StringBuilder
is initialized with a memory allotment. -
This allotment grows if needed.
-
StringBuilder
is stored as an array of characters. -
Extra space allotment allows easy character appending to the end.
-
Example declarations:
// By default, 16 bytes are allocated
StringBuilder sb1 = new StringBuilder();
// String and 16 bytes will be allocated
StringBuilder sb2 = new StringBuilder("Hello World");
// Actual number of bytes (8) provided
StringBuilder sb3 = new StringBuilder(8);
StringBuilder
can catenate several strings together using theappend()
method.- We can also use
StringBuilder
to easily check palindrome words. - A palindrome reads the same forwards and backwards.
- This can be achieved by using the
reverse()
method.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Related Documents
Description
Explanation of assertions in programming. Assertions validates program data and prevents unexpected behavior. Assertions are used to validate data during the development and testing phases.