Monday, August 13, 2012
String Handling
Using String, StringBuffer, and StringBuilder (Objective 3.1)
- String objects are immutable, and String reference variables are not.
- If you create a new String without assigning it, it will be lost to your program.
- If you redirect a String reference to a new String, the old String can be lost.
- String methods use zero-based indexes, except for the second argument of substring().
- The String class is final-its methods can't be overridden.
- When the JVM finds a String literal, it is added to the String literal pool.
- Strings have a method: length(); arrays have an attribute named length.
- The StringBuffer's API is the same as the new StringBuilder's API, except that StringBuilder's methods are not synchronized for thread safety.
- StringBuilder methods should run faster than StringBuffer methods.
- All of the following bullets apply to both StringBuffer and StringBuilder:
- They are mutable - they can change without creating a new object.
- StringBuffer methods act on the invoking object, and objects can change without an explicit assignment in the statement.
- StringBuffer equals() is not overridden; it doesn't compare values.
- Remember that chained methods are evaluated from left to right.
- String methods to remember: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().
- StringBuffer methods to remember: append(), delete(), insert(), reverse(), and toString().
File I/O (Objective 3.2)
- The classes you need to understand in java.io are File, FileReader, BufferedReader, FileWriter, BufferedWriter, PrintWriter, and Console.
- A new File object doesn't mean there's a new file on your hard drive.
- File objects can represent either a file or a directory.
- The File class lets you manage (add, rename, and delete) files and directories.
- The methods createNewFile() and mkdir() add entries to your file system.
- FileWriter and FileReader are low-level I/O classesYou can use them to write and read files, but they should usually be wrapped.
- Classes in java.io are designed to be "chained" or "wrapped." (This is a common use of the decorator design pattern.)
- It's very common to "wrap" a BufferedReader around a FileReader or a BufferedWriter around a FileWriter, to get access to higher-level (more convenient) methods.
- PrintWriters can be used to wrap other Writers, but as of Java 5 they can be built directly from Files or Strings.
- Java 5 PrintWriters have new append(), format(), and printf() methods.
- Console objects can read non-echoed input and are instantiated using System.console().
Serialization (Objective 3.3)
- The classes you need to understand are all in thejava.io package; they include: ObjectOutputStream and ObjectInputStream primarily, and FileOutputStream and FileInputStream because you will use them to create the low-level streams that the ObjectXxxStream classes will use.
- A class must implement Serializable before its objects can be serialized.
- The ObjectOutputStream.
writeObject() method serializes objects, and the ObjectInputStream.readObject() method deserializes objects. - If you mark an instance variable transient, it will not be serialized even thought the rest of the object's state will be.
- You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methodsIf you do this, embedding calls to defaultWriteObject() and defaultReadObject(),
respectively, will handle the part of serialization that happens normally. - If a superclass implements Serializable, then its subclasses do automatically.
- If a superclass doesn't implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its superconstructor(s).
- DataInputStream and DataOutputStream aren't actually on the exam, inspite of what the Sun objectives say.
Dates, Numbers, and Currency (Objective 3.4)
- The classes you need to understand are java.util.Date, java.util.Calendar, java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.
- Most of the Date class's methods have been deprecated.
- A Date is stored as a long, the number of milliseconds since January 1, 1970.
- Date objects are go-betweens the Calendar and Locale classes.
- The Calendar provides a powerful set of methods to manipulate dates, performing tasks such as getting days of the week, or adding some number of months or years (or other increments) to a date.
- Create Calendar instances using static factory methods (getInstance()).
- The Calendar methods you should understand are add(), which allows you to add or subtract various pieces (minutes, days, years, and so on) of dates, and roll(), which works like add() but doesn't increment a date's bigger pieces(For example: adding 10 months to an October date changes the month to August, but doesn't increment the Calendar's year value.)
- DateFormat instances are created using static factory methods (getInstance() and getDateInstance()).
- There are several format "styles" available in the DateFormat class.
- DateFormat styles can be applied against various Locales to create a wide array of outputs for any given date.
- The DateFormat.format() method is used to create Strings containing properly formatted dates.
- The Locale class is used in conjunction with DateFormat and NumberFormat.
- Both DateFormat and NumberFormat objects can be constructed with a specific, immutable Locale.
- For the exam you should understand creating Locales using language, or a combination of language and country.
Parsing, Tokenizing, and Formatting (Objective 3.5)
- regex is short for regular expressions, which are the patterns used to search for data within large data sources.
- regex is a sub-language that exists in Java and other languages (such as Perl).
- regex lets you to create search patterns using literal characters or metacharactersMetacharacters allow you to search for slightly more abstract data like "digits" or "whitespace".
- Study the \d, \s, \w, and metacharacters
- regex provides for quantifiers which allow you to specify concepts like: "look for one or more digits in a row."
- Study the ?, *, and + greedy quantifiers.
- Remember that metacharacters and Strings don't mix well unless you remember to "escape" them properlyFor instance String s = "\\d";
- The Pattern and Matcher classes have Java's most powerful regex capabilities.
- You should understand the Pattern compile() method and the Matcher matches(), pattern(), find(), start(), and group() methods.
- You WON'T need to understand Matcher's replacement-oriented methods.
- You can use java.util.Scanner to do simple regex searches, but it is primarily intended for tokenizing.
- Tokenizing is the process of splitting delimited data into small pieces.
- In tokenizing, the data you want is called tokens, and the strings that separate the tokens are called delimiters.
- Tokenizing can be done with the Scanner class, or with String.split().
- Delimiters are single characters like commas, or complex regex expressions.
- The Scanner class allows you to tokenize data from within a loop, which allows you to stop whenever you want to.
- The Scanner class allows you to tokenize Strings or streams or files.
- The String.split() method tokenizes the entire source data all at once, so large amounts of data can be quite slow to process.
- New to Java 5 are two methods used to format data for output. These methods are format() and printf()These methods are found in the PrintStream class, an instance of which is the out in System.out.
- The format() and printf() methods have identical functionality.
- Formatting data with printf() (or format()) is accomplished using formatting strings that are associated with primitive or string arguments.
- The format() method allows you to mix literals in with your format strings.
- The format string values you should know are
- Flags: -, +, 0, "," , and (
- Conversions: b, c, d, f, and s
- If your conversion character doesn't match your argument type, an exception will be thrown.
regards,
Agni..
Executive,
Talent Sprint
Hyderabad.
for Feedback and Support simply drop a mail in
agni2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Saturday, August 11, 2012
Exercise - 5 (Exception,Assertion)
1.Given
class One { public static void main(String[] args) { int assert = 0; } } class Two { public static void main(String[] args) { assert(false); } }And the four command-line invocations:
javac -source 1.3 One.javaWhat is the result? (Choose all that apply.)
javac -source 1.4 One.java
javac -source 1.3 Two.java
javac -source 1.4 Two.java
A. Only one compilation will succeed
B. Exactly two compilations will succeed
C. Exactly three compilations will succeed
D. All four compilations will succeed
E. No compiler warnings will be produced
F. At least one compiler warning will be produced
Answer:
B and F are correct. Class One will compile (and issue a warning) using the 1.3 flag, and
class Two will compile using the 1.4 flag.
A, C, D, and E are incorrect based on the above. (Objective 2.3)
A, C, D, and E are incorrect based on the above. (Objective 2.3)
2.Given
class Plane { static String s = "-"; public static void main(String[] args) { new Plane().s1(); System.out.println(s); } void s1() { try { s2(); } catch (Exception e) { s += "c"; } } void s2() throws Exception { s3(); s += "2"; s3(); s += "2b"; } void s3() throws Exception { throw new Exception(); } }What is the result?
A. -
B. -c
C. -c2
D. -2c
E. -c22b
F. -2c2b
G. -2c2bc
H. Compilation fails
Answer:
B is correct. Once s3() throws the exception to s2(), s2() throws it to s1(), and no
more of s2()'s code will be executed.
A, C, D, E, F, G, and H are incorrect based on the above. (Objective 2.5)
A, C, D, E, F, G, and H are incorrect based on the above. (Objective 2.5)
3.Given
try { int x = Integer.parseInt("two"); }Which could be used to create an appropriate catch block? (Choose all that apply.)
A. ClassCastException
B. IllegalStateException
C. NumberFormatException
D. IllegalArgumentException
E. ExceptionInInitializerError
F. ArrayIndexOutOfBoundsException
Answer:
C and D are correct. Integer.parseInt can throw a NumberFormatException, and
IllegalArgumentException is its superclass (i.e., a broader exception).
A, B, E, and F are not in NumberFormatException's class hierarchy. (Objective 2.6)
A, B, E, and F are not in NumberFormatException's class hierarchy. (Objective 2.6)
4. Which are true? (Choose all that apply.)
A. It is appropriate to use assertions to validate arguments to methods marked public
B. It is appropriate to catch and handle assertion errors
C. It is NOT appropriate to use assertions to validate command-line arguments
D. It is appropriate to use assertions to generate alerts when you reach code that should not be reachable
E. It is NOT appropriate for assertions to change a program's state
Answer:
C, D, and E are correct statements.
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so. (Objective 2.3)
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so. (Objective 2.3)
5.Given
class Loopy { public static void main(String[] args) { int[] x = {7,6,5,4,3,2,1}; // insert code here System.out.print(y + " "); } } }Which, inserted independently at line 4, compiles? (Choose all that apply.)
A. for(int y : x) { B. for(x : int y) { C. int y = 0; for(y : x) { D. for(int y=0, z=0; z < x.length; z++) { y = x[z]; E. for(int y=0, int z=0; z < x.length; z++) { y = x[z]; F. int y = 0; for(int z=0; z<x.length; z++) { y = x[z];
Answer:
A, D, and F are correct. A is an example of the enhanced for loop. D and F are examples
of the basic for loop.
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement. (Objective 2.2)
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement. (Objective 2.2)
6.Given
class Emu { static String s = "-"; public static void main(String[] args) { try { throw new Exception(); } catch (Exception e) { try { try { throw new Exception(); } catch (Exception ex) { s += "ic "; } throw new Exception(); } catch (Exception x) { s += "mc "; } finally { s += "mf "; } } finally { s += "of "; } System.out.println(s); } }What is the result?
A. -ic of
B. -mf of
C. -mc mf
D. -ic mf of
E. -ic mc mf of
F. -ic mc of mf
G. Compilation fails
Answer:
E is correct. There is no problem nesting try / catch blocks. As is normal, when an
exception is thrown, the code in the catch block runs, then the code in the finally block
runs.
A, B, C, D, and F are incorrect based on the above. (Objective 2.5)
A, B, C, D, and F are incorrect based on the above. (Objective 2.5)
7.Given
class SubException extends Exception { } class SubSubException extends SubException { } public class CC { void doStuff() throws SubException { } } class CC2 extends CC { void doStuff() throws SubSubException { } } class CC3 extends CC { void doStuff() throws Exception { } } class CC4 extends CC { void doStuff(int x) throws Exception { } } class CC5 extends CC { void doStuff() { } }What is the result? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 6
C. Compilation fails due to an error on line 8
D. Compilation fails due to an error on line 10
E. Compilation fails due to an error on line 12
Answer:
C is correct. An overriding method cannot throw a broader exception than the method it's
overriding. Class CC4's method is an overload, not an override.
A, B, D, and E are incorrect based on the above. (Objectives 1.5, 2.4)
A, B, D, and E are incorrect based on the above. (Objectives 1.5, 2.4)
8.Given
public class Ebb { static int x = 7; public static void main(String[] args) { String s = ""; for(int y = 0; y < 3; y++) { x++; switch(x) { case 8: s += "8 "; case 9: s += "9 "; case 10: { s+= "10 "; break; } default: s += "d "; case 13: s+= "13 "; } } System.out.println(s); } static { x++; } }What is the result?
A. 9 10 d
B. 8 9 10 d
C. 9 10 10 d
D. 9 10 10 d 13
E. 8 9 10 10 d 13
F. 8 9 10 9 10 10 d 13
G. Compilation fails
Answer:
D is correct. Did you catch the static initializer block? Remember that switches work on
"fall-thru" logic, and that fall-thru logic also applies to the default case, which is used when
no other case matches.
A, B, C, E, F, and G are incorrect based on the above. (Objective 2.1)
A, B, C, E, F, and G are incorrect based on the above. (Objective 2.1)
9.Given
class Infinity { } public class Beyond extends Infinity { static Integer i; public static void main(String[] args) { int sw = (int)(Math.random() * 3); switch(sw) { case 0: { for(int x = 10; x > 5; x++) if(x > 10000000) x = 10; break; } case 1: { int y = 7 * i; break; } case 2: { Infinity inf = new Beyond(); Beyond b = (Beyond)inf; } } } }And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception
Answer:
D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will
initiate an endless loop, not a stack overflow. Case 2's downcast will not cause an exception.
A, B, C, E, and G are incorrect based on the above. (Objective 2.6)
A, B, C, E, and G are incorrect based on the above. (Objective 2.6)
10.Given
public class Circles { public static void main(String[] args) { int[] ia = {1,3,5,7,9}; for(int x : ia) { for(int j = 0; j < 3; j++) { if(x > 4 && x < 8) continue; System.out.print(" " + x); if(j == 1) break; continue; } continue; } } }What is the result?
A. 1 3 9
B. 5 5 7 7
C. 1 3 3 9 9
D. 1 1 3 3 9 9
E. 1 1 1 3 3 3 9 9 9
F. Compilation fails
Answer:
D is correct. The basic rule for unlabeled continue statements is that the current iteration
stops early and execution jumps to the next iteration. The last two continue statements are
redundant!
A, B, C, E, and F are incorrect based on the above. (Objective 2.2)
A, B, C, E, and F are incorrect based on the above. (Objective 2.2)
11.Given
public class OverAndOver { static String s = ""; public static void main(String[] args) { try { s += "1"; throw new Exception(); } catch (Exception e) { s += "2"; } finally { s += "3"; doStuff(); s += "4"; } System.out.println(s); } static void doStuff() { int x = 0; int y = 7/x; } }What is the result?
A. 12
B. 13
C. 123
D. 1234
E. Compilation fails
F. 123 followed by an exception
G. 1234 followed by an exception
H. An exception is thrown with no other output
Answer:
H is correct. It's true that the value of String s is 123 at the time that the divide-byzero
exception is thrown, but finally() is not guaranteed to complete, and in this case
finally() never completes, so the System.out.println (S.O.P.) never executes.
A, B, C, D, E, F, and G are incorrect based on the above. (Objective 2.5)
A, B, C, D, E, F, and G are incorrect based on the above. (Objective 2.5)
12.Given
public class Wind { public static void main(String[] args) { foreach: for(int j=0; j<5; j++) { for(int k=0; k< 3; k++) { System.out.print(" " + j); if(j==3 && k==1) break foreach; if(j==0 || j==2) break; } } } }What is the result?
A. 0 1 2 3
B. 1 1 1 3 3
C. 0 1 1 1 2 3 3
D. 1 1 1 3 3 4 4 4
E. 0 1 1 1 2 3 3 4 4 4
F. Compilation fails
Answer:
C is correct. A break breaks out of the current innermost loop and continues. A labeled
break breaks out of and terminates the current loops.
A, B, D, E, and F are incorrect based on the above. (Objective 2.2)
A, B, D, E, and F are incorrect based on the above. (Objective 2.2)
13.Given
public class Gotcha { public static void main(String[] args) { // insert code here } void go() { go(); } }And given the following three code fragments:
I. new Gotcha().go(); II. try { new Gotcha().go(); } catch (Error e) { System.out.println("ouch"); } III. try { new Gotcha().go(); } catch (Exception e) { System.out.println("ouch"); }When fragments I - III are added, independently, at line 3, which are true? (Choose all that apply.)
A. Some will not compile
B. They will all compile
C. All will complete normally
D. None will complete normally
E. Only one will complete normally
F. Two of them will complete normally
Answer:
B and E are correct. First off, go() is a badly designed recursive method, guaranteed to
cause a StackOverflowError. Since Exception is not a superclass of Error, catching an
Exception will not help handle an Error, so fragment III will not complete normally.
Only fragment II will catch the Error.
A, C, D, and F are incorrect based on the above. (Objective 2.5)
A, C, D, and F are incorrect based on the above. (Objective 2.5)
14.Given
public class Clumsy { public static void main(String[] args) { int j = 7; assert(++j > 7); assert(++j > 8): "hi"; assert(j > 10): j=12; assert(j==12): doStuff(); assert(j==12): new Clumsy(); } static void doStuff() { } }Which are true? (Choose all that apply.)
A. Compilation succeeds
B. Compilation fails due to an error on line 4
C. Compilation fails due to an error on line 5
D. Compilation fails due to an error on line 6
E. Compilation fails due to an error on line 7
F. Compilation fails due to an error on line 8
Answer:
E is correct. When an assert statement has two expressions, the second expression must
return a value. The only two-expression assert statement that doesn't return a value is on
line 7.
A, B, C, D, and F are incorrect based on the above. (Objective 2.3)
A, B, C, D, and F are incorrect based on the above. (Objective 2.3)
15.Given
public class Frisbee { // insert code here int x = 0; System.out.println(7/x); } }And given the following four code fragments:
I. public static void main(String[] args) { II. public static void main(String[] args) throws Exception { III. public static void main(String[] args) throws IOException { IV. public static void main(String[] args) throws RuntimeException {If the four fragments are inserted independently at line 2, which are true? (Choose all that apply.)
A. All four will compile and execute without exception
B. All four will compile and execute and throw an exception
C. Some, but not all, will compile and execute without exception
D. Some, but not all, will compile and execute and throw an exception
E. When considering fragments II, III, and IV, of those that will compile, adding a try/catch block around line 4 will cause compilation to fail
Answer:
D is correct. This is kind of sneaky, but remember that we're trying to toughen you up for
the real exam. If you're going to throw an IOException, you have to import the java.io
package or declare the exception with a fully qualified name.
E is incorrect because it's okay to both handle and declare an exception. A, B, and C are incorrect based on the above. (Objective 2.4)
E is incorrect because it's okay to both handle and declare an exception. A, B, and C are incorrect based on the above. (Objective 2.4)
16.Given
class MyException extends Exception { } class Tire { void doStuff() { } } public class Retread extends Tire { public static void main(String[] args) { new Retread().doStuff(); } // insert code here System.out.println(7/0); } }And given the following four code fragments:
I. void doStuff() { II. void doStuff() throws MyException { III. void doStuff() throws RuntimeException { IV. void doStuff() throws ArithmeticException {When fragments I - IV are added, independently, at line 10, which are true? (Choose all that apply.)
A. None will compile
B. They will all compile
C. Some, but not all, will compile
D. All of those that compile will throw an exception at runtime
E. None of those that compile will throw an exception at runtime
F. Only some of those that compile will throw an exception at runtime
Answer:
C and D are correct. An overriding method cannot throw checked exceptions that are
broader than those thrown by the overridden method. However an overriding method can
throw RuntimeExceptions not thrown by the overridden method.
A, B, E, and F are incorrect based on the above. (Objective 2.4)
A, B, E, and F are incorrect based on the above. (Objective 2.4)
regards,
Agni..
Executive,
Talent Sprint
Hyderabad.
for Feedback and Support simply drop a mail in
agni2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Wednesday, August 8, 2012
Exceptions, Assertions
Writing Code Using if and switch Statements (Obj. 2.1)
- The only legal expression in an if statement is a boolean expression, in other words an expression that resolves to a boolean or a Boolean variable.
- Watch out for boolean assignments (=) that can be mistaken for boolean equality (==) tests:
boolean x = false;
if (x = true) { } // an assignment, so x will always be true!
- Curly braces are optional for if blocks that have only one conditional statement. But watch out for misleading indentations.
- switch statements can evaluate only to enums or the byte, short, int, and char data types. You can't say,
long s = 30;
switch(s) { }
- The case constant must be a literal or final variable, or a constant expression, including an enum. You cannot have a case that includes a nonfinal variable, or a range of values.
- If the condition in a switch statement matches a case constant, execution will run through all code in the switch following the matching case statement until a break statement or the end of the switch statement is encountered. In other words, the matching case is just the entry point into the case block, but unless there's a break statement, the matching case is not the only case code that runs.
- The default keyword should be used in a switch statement if you want to run some code when none of the case values match the conditional value.
- The default block can be located anywhere in the switch block, so if no case matches, the default block will be entered, and if the default does not contain a break, then code will continue to execute (fall-through) to the end of the switch or until the break statement is encountered.
Writing Code Using Loops (Objective 2.2)
- A basic for statement has three parts: declaration and/or initialization, boolean evaluation, and the iteration expression.
- If a variable is incremented or evaluated within a basic for loop, it must be declared before the loop, or within the for loop declaration.
- A variable declared (not just initialized) within the basic for loop declaration cannot be accessed outside the for loop (in other words, code below the for loop won't be able to use the variable).
- You can initialize more than one variable of the same type in the first part of the basic for loop declaration; each initialization must be separated by a comma.
- An enhanced for statement (new as of Java 6), has two parts, the declaration and the expression. It is used only to loop through arrays or collections.
- With an enhanced for, the expression is the array or collection through which you want to loop.
- With an enhanced for, the declaration is the block variable, whose type is compatible with the elements of the array or collection, and that variable contains the value of the element for the given iteration.
- You cannot use a number (old C-style language construct) or anything that does not evaluate to a boolean value as a condition for an if statement or looping construct. You can't, for example, say if(x), unless x is a boolean variable.
- The do loop will enter the body of the loop at least once, even if the test condition is not met.
Using break and continue (Objective 2.2)
- An unlabeled break statement will cause the current iteration of the innermost looping construct to stop and the line of code following the loop to run.
- An unlabeled continue statement will cause: the current iteration of the innermost loop to stop, the condition of that loop to be checked, and if the condition is met, the loop to run again.
- If the break statement or the continue statement is labeled, it will cause similar action to occur on the labeled loop, not the innermost loop.
Handling Exceptions (Objectives 2.4, 2.5, and 2.6)
- Exceptions come in two flavors: checked and unchecked.
- Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.
- Checked exceptions are subject to the handle or declare rule; any method that might throw a checked exception (including methods that invoke methods that can throw a checked exception) must either declare the exception using throws, or handle the exception with an appropriate try/catch.
- Subtypes of Error or RuntimeException are unchecked, so the compiler doesn't enforce the handle or declare rule. You're free to handle them, or to declare them, but the compiler doesn't care one way or the other.
- If you use an optional finally block, it will always be invoked, regardless of whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not.
- The only exception to the finally "will-always-be-called" rule is that a finally will not be invoked if the JVM shuts down. That could happen if code from the try or catch blocks calls System.exit().
- Just because finally is invoked does not mean it will complete. Code in the finally block could itself raise an exception or issue a System.exit().
- Uncaught exceptions propagate back through the call stack, starting from the method where the exception is thrown and ending with either the first method that has a corresponding catch for that exception type or a JVM shutdown (which happens if the exception gets to main(), and main() is "ducking" the exception by declaring it).
- You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception,and the compiler will enforce the handle or declare rule for that exception.
- All catch blocks must be ordered from most specific to most general. If you have a catch clause for both IOException and Exception, you must put the catch for IOException first in your code. Otherwise, the IOException would be caught by catch(Exception e), because a catch argument can catch the specified exception or any of its subtypes! The compiler will stop you from defining catch clauses that can never be reached.
- Some exceptions are created by programmers, some by the JVM.
Working with the Assertion Mechanism (Objective 2.3)
- Assertions give you a way to test your assumptions during development and debugging.
- Assertions are typically enabled during testing but disabled during deployment.
- You can use assert as a keyword (as of version 1.4) or an identifier, but not both together. To compile older code that uses assert as an identifier (for example, a method name), use the -source 1.3 command-line flag to javac.
- Assertions are disabled at runtime by default. To enable them, use a command- line flag -ea or -enableassertions.
- Selectively disable assertions by using the -da or -disableassertions flag.
- If you enable or disable assertions using the flag without any arguments, you're enabling or disabling assertions in general. You can combine enabling and disabling switches to have assertions enabled for some classes and/or packages, but not others.
- You can enable and disable assertions on a class-by-class basis, using the following syntax:
java -ea -da:MyClass TestClass
- You can enable and disable assertions on a package-by-package basis, and any package you specify also includes any subpackages (packages further down the directory hierarchy).
- Do not use assertions to validate arguments to public methods.
- Do not use assert expressions that cause side effects. Assertions aren't guaranteed to always run, and you don't want behavior that changes depending on whether assertions are enabled.
- Do use assertions—even in public methods—to validate that a particular code block will never be reached. You can use assert false; for code that should never be reached, so that an assertion error is thrown immediately if the assert statement is executed.
regards,
Agni..
Executive,
Talent Sprint
Hyderabad.
for Feedback and Support simply drop a mail in
agni2020{at}gmail.com
Remember to replace the {at} with @ in the email addresses
Subscribe to:
Posts (Atom)