• Post Reply Bookmark Topic Watch Topic
  • New Topic

I desperately need help  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a Java exam coming up and have been looking at past papers. These two questions have me stuck:

1. Compare and contrast Java interfaces and abstract classes. Provide an example where,
(i) Using an interface would be more appropriate than using an abstract class.
(ii) Using an abstract class would be more appropriate than using an interface.
You may describe the example Use structured English, Java code, and/or some simple UML class diagrams to describe your examples.


2. Give an account of Exception Handling in Java. Illustrate your answer by considering the following program, which may give rise to three different types of exception:
• An ArrayIndexOutOfBounds exception which happens if there are less than two command line arguments.
• A NumberFormatException which happens if one or both of the arguments are not whole numbers.
• An ArithmeticException if the first argument is a whole number and the second argument is 0.
Describe how you would rewrite this program in such a way that each of these exceptions could be handled.

class Exceptions {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a / b;
System.out.println("The answer is " + c);
}

Could anyone help me by explaining this? I am not too familiar with Abstract/Interface classes and Inheritance and am having trouble understanding how I would rewrite that exception code. Any help is greatly appreciated.
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the Java Tutorials; you should find something about those questions there. Particularly about exceptions.
 
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the exceptions thing you need try and catch blocks. For the first two exceptions you should tell the user that their input is wrong, while with the ArithmeticException you should tell the user that the answer is undefined, or that a divide by zero occurs. Its really your choice if you want to group the first two exceptions together and print out the same error message or not, but the last one should definitely be separate.
 
Campbell Ritchie
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the customary way to handle failure to provide command‑line arguments is like this:-That has the advantage that the index out of bounds exception can never occur. The other Exceptions can occur, however.
That permits you to discuss handling exceptions versus preventing them.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!