Question

Explain how you would use assertions in java. What is the purpose of a finally block?

  1. Explain how you would use assertions in java.
  2. What is the purpose of a finally block?
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

An assertion in Java- Assertion is a statement in java. It can be used to test your assumptions about the program. When assertion executes, it is believed to be true. If it is false, java JVM throws an error named Assertion Error. Assertion is mainly used for testing purposes. An assertion allows testing the correctness of any assumptions that have been made in the program.

Syntax of using Assertion:

There are two ways to use an assertion. The first way is:

Assert expression;

The second way is:

Assert expression1: expression2;

Example of Assertion in Java-

import java.util.Scanner;

class test

{

            public static void main(String args[])

{

            Scanner in = new Scanner(System.in);

            System.out.print(“Enter your age”);

            int val = in.nextInt();

            assert value>=15:”not valid”;

            System.out.println(“Value is:”+val);

}

}

If you want to use assertion, it will not rum simply because assertion is disabled by default. To enable the assertion, -ea or –enableassertions switch of java must be used.

To compile javac test.java

To Run: java –ea test

Output: Enter your age 10

Exception in thread “main” java.lang.AssertionError: Not valid

The finally block always executes when a try block exists in a program. This ensures that the finally block is executed even if an unexpected exception occurs. A finally block has all the crucial statements that must be executed whether an exception occurs or not in the program. The statement present in this block will always execute regardless of whether an exception occurs in a try block or not such as closing a connection, stream, etc.

Add a comment
Know the answer?
Add Answer to:
Explain how you would use assertions in java. What is the purpose of a finally block?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT