Assertions in programming
20 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

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.

False (B)

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.

<p>toCharArray</p> Signup and view all the answers

Match the regular expression metacharacters with their meanings:

<p>\s = Matches a space character [0-9] = Matches any digit [a-zA-Z] = Matches any letter (uppercase or lowercase)</p> <ul> <li>= Specifies one or more of a preceding character</li> </ul> Signup and view all the answers

Which of the following is NOT a typical use case for assert statements?

<p>Validating input parameters in a public API. (D)</p> Signup and view all the answers

StringBuilder is used to process files

<p>False (B)</p> Signup and view all the answers

What is the term for splitting a string into an array of substrings based on a delimiter or pattern?

<p>splitting</p> Signup and view all the answers

In regular expressions, the metacharacter ______ is used to specify a range of characters.

<ul> <li></li> </ul> Signup and view all the answers

What is the main difference between using String and StringBuilder for text manipulation?

<p><code>String</code> is immutable, while <code>StringBuilder</code> is mutable. (B)</p> Signup and view all the answers

When should you prefer using an Exception over an Assertion?

<p>To handle conditions that might occur in production and from which the application might recover. (A)</p> Signup and view all the answers

If a method's parameter is declared as an integer, manual validation of the parameter's data type is still necessary.

<p>False (B)</p> Signup and view all the answers

What is a term used for a pattern of searching purposes?

<p>Regular expression</p> Signup and view all the answers

The extra space allotment in StringBuilder allows us to easily ______ characters to the end

<p>append</p> Signup and view all the answers

Besides 'append', which StringBuilder methods are not avaiable for String?

<p><code>insert</code>, <code>delete</code>, and <code>reverse</code> (C)</p> Signup and view all the answers

What outcome should never happen in the production code?

<p>An assertion should never fail (B)</p> Signup and view all the answers

String implements replace differently that StringBuilder

<p>True (A)</p> Signup and view all the answers

In Java, what is the String method called that allows strings to be broken apart?

<p>Split</p> Signup and view all the answers

The ______ statement is typically only used during development and testing, and may be disabled

<p>assert</p> Signup and view all the answers

Which one is not a functionality of StringBuilder?

<p>Read (C)</p> Signup and view all the answers

Flashcards

Assert Statement

A statement to ensure conditions in programs are met while running. Useful for debugging.

Assertion Error

Terminates the program if the condition is false, indicating an unexpected state.

When to use Assert

Used during development and testing to catch coding errors; may be disabled in production.

Validating Parameters

Used to manually validate arguments passed into parameters, throwing an exception if invalid.

Signup and view all the flashcards

IllegalArgumentException

An exception thrown when a method receives an illegal or inappropriate argument.

Signup and view all the flashcards

Exceptions

Used for run-time errors; the program may be able to recover from them.

Signup and view all the flashcards

Assertions

Used for coding errors and mistakes; program termination is expected.

Signup and view all the flashcards

toCharArray()

Converts a String to an array of characters.

Signup and view all the flashcards

split() method

Splits a string into an array of substrings based on a delimiter (regex).

Signup and view all the flashcards

Regular Expression (Regex)

Patterns used for searching and manipulating strings.

Signup and view all the flashcards

Why use Regex?

a sequence of characters that helps with matching, locating and manipulating text.

Signup and view all the flashcards

[and]

A sequence of comma separated characters, specified between square brackets. Use in Regex

Signup and view all the flashcards

Strings

Immutable: Once initialized, it cannot be changed.

Signup and view all the flashcards

StringBuilder

A mutable sequence of characters that is flexible and changeable.

Signup and view all the flashcards

StringBuilder (vs String)

Strings are immutable. Excessive text manipulation can cause performance inefficiencies

Signup and view all the flashcards

append()

Adds a string to the end of the current string in a StringBuilder.

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, an Assertion 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 an IllegalArgumentException 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 and ValidateFormat.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, and reverse are available for StringBuilder and not String.
  • Stringbuilder implements replace differently than String.

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 the append() 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.

Quiz Team

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.

More Like This

Depreciation Quiz
3 questions

Depreciation Quiz

BrotherlyScholarship avatar
BrotherlyScholarship
Depreciation Quiz
3 questions

Depreciation Quiz

HonoredRoseQuartz avatar
HonoredRoseQuartz
Python Exception Handling Quiz
48 questions

Python Exception Handling Quiz

CommendableMossAgate755 avatar
CommendableMossAgate755
Use Quizgecko on...
Browser
Browser