|
Java Certifications
www.javacertifications.com
|
| home | scjp 5 | OCPJP 6 | Upgrade OCPJP 7 | scwcd 1.5 | scjp 5 questions | OCPJP6 questions | OCPJWCD 5 success kit | scjp 5 success kit | OCPJP 6 success kit |
| JavaCertifications.net provides java certfication tutorials and mock questions. |
| 805 OCPJP 6 Questions | 788 SCJP 5 questions | 650 OCPJWCD 5 questions | 600 OCAJP 7 questions | 610 OCPJP 7 questions | 510 Upgrade to OCPJP 7 questions |
|
Tutorials
|
Upgrade to OCPJP 7 Java SE 7 Programmer (1Z0-805) Guide : Language Enhancements
1) Language EnhancementsIn Java SE 7 and later, you can use aString object in the switch statement's
expression. The following code example, StringSwitch, displays the color RGB based
on the value of the String named color:
public class StringSwitch {
public static void main(String[] args) {
String color = "black";
switch (color) {
case "white":
System.out.print(color + " RGB: ffffff");
break;
case "black":
System.out.print(color + " RGB: 000000");
break;
default:
System.out.print(color + " RGB: UNKNOWN");
break;
}
}
}
The output from this code is: black RGB: 000000
The
1.2. Use binary literals, numeric literals with underscoresInteger Literals
An integer literal is of type
Values of the integral types
For general-purpose programming, the decimal system is likely to be the only number system you will ever use. However, if you need to use another number system, the following example shows the correct syntax. The prefix '0x' indicates hexadecimal and '0b' indicates binary: int decVal = 26; // The number 26, in decimal int hexVal = 0x1a; // The number 26, in hexadecimal int binVal = 0b11010; // The number 26, in binary
Binary Literals
In Java SE 7, the integral types ( // An 8-bit 'byte' value: byte aByte = 0b00100001; // A 16-bit 'short' value: short aShort = 0b0010001010001010; // Some 32-bit 'int' values: int anInt1 = 0b10100001010001011010000101000101; int anInt2 = 0b101; int anInt3 = 0B101; // The B can be upper or lower case. // A 64-bit 'long' value. Note the "L" suffix: long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L; // OK, implicit casting int to float or double variable float f1 = 0b0001; double d1 = 0b0001; // COMPILATION FAILS! Binary literal can only be of integer type (byte, char, int, long), // while 'd' or 'f' suffixes explicitly say these are decimal point type literals double d2 = 0b0001d; float f2 = 0b0001f;
Underscores in Numeric Literals In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code. For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator. The following example shows other ways you can use the underscore in numeric literals: long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you CANNOT place underscores in the following places:
The following examples demonstrate valid and invalid underscore placements in numeric literals. Valid: int x1 = 5_2; // OK (decimal literal) int x2 = 5_______2; // OK (decimal literal) int x3 = 0x5_2; // OK (hexadecimal literal) int x4 = 0B0_0_0; // OK (binary literal)
Invalid: float pi1 = 3_.1415F; // Cannot put underscores adjacent to a decimal point float pi2 = 3._1415F; // Cannot put underscores adjacent to a decimal point long ssn = 999_99_9999_L; // Cannot put underscores prior to an L suffix int x1 = 52_; // Cannot put underscores at the end of a literal int x2 = 0_x52; // Cannot put underscores in the 0x radix prefix int x3 = 0x_52; // Cannot put underscores at the beginning of a number int x4 = 0x52_; // Cannot put underscores at the end of a number
Invalid (compilable, but logical error): int x1 = _52; // This is an identifier, not a numeric literal
Use try-with-resourcesThe try-with-resources statement is atry statement that
declares one or more resources.
A resource is as an object that must be closed after the program is finished with it. The try-with-resources
statement ensures that each resource is closed at the end of the statement. Any object that implements
package java.lang;
public interface AutoCloseable {
void close() throws Exception;
}
The
package java.io;
import java.io.IOException;
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
The following example reads the first line from a file. It uses an instance of
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a
Prior to Java SE 7, you can use a
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
However, in this example, if the methods
You may declare one or more resources in a try-with-resources statement. The following example makes a
copy of a file, using the try-with-resources statement. There are two resources defined in the
public static void copyFile(String src, String dest) throws IOException {
try (BufferedReader in = new BufferedReader(new FileReader(src));
BufferedWriter out = new BufferedWriter(new FileWriter(dest))) {
String line;
while((line = in.readLine()) != null) {
out.write(line);
out.write('\n');
}
} // No need to close resources in a "finally"
}
NOTE: the
NOTE: in try-with-resource statement the
In JDBC 4.1 the
The following example uses a try-with-resources statement to automatically close a
public static void viewTable(Connection con) throws SQLException {
String query = "SELECT ... FROM ...";
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
// ...
}
} catch (SQLException e) {
// ...
}
}
The resource
NOTE: A try-with-resources statement CAN have Making an Auto-Closeable Class
As you know, a try-with-resources statement cannot manage every class. A new interface called
Such Consider the following example: public class AutoCloseableResource implements AutoCloseable { @Override public void close() { System.out.println("in close()"); throw new RuntimeException("Exception in close()"); } public void work() throws Exception { System.out.println("in work()"); throw new Exception("Exception in work()"); } }
public class AutoCloseableTest {
public static void main(String[] args) {
try (AutoCloseableResource resource = new AutoCloseableResource()) {
resource.work();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The in work() in close() java.lang.Exception: Exception in work() at AutoCloseableResource.work(AutoCloseableResource.java:21) at AutoCloseableTest.main(AutoCloseableTest.java:15) Suppressed: java.lang.RuntimeException: Exception in close() at AutoCloseableResource.close(AutoCloseableResource.java:16) at AutoCloseableTest.main(AutoCloseableTest.java:16)
The output clearly proves that Suppressed Exceptions
If both the (explicit)
The Java SE 7 extensions to
These extensions were introduced especially for supporting the try-with-resources statement and fixing exception-masking problems.
An exception can be thrown from the block of code associated with the try-with-resources statement. In the example Use multi-catch in exception statementsIn Java SE 7, a singlecatch block can handle more than one type of exception. This feature can reduce code duplication and
lessen the temptation to catch an overly broad exception.
Consider the following example, which contains duplicate code in each of the
try {
// ...
} catch (IOException ex) {
logger.log(ex);
throw ex;
} catch (SQLException ex) {
logger.log(ex);
throw ex;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable
The following example, which is valid in Java SE 7, eliminates the duplicated code:
try {
// ...
} catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
The
NOTE: An exception can not be a subtype or supertype of one of the
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("data"))) {
out.writeUTF("Hello");
} catch (FileNotFoundException | IOException e) { // COMPILATION FAILS !!!
// ...
}
public class FileNotFoundException extends IOException {
// ...
}
NOTE: If a
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("data"))) {
out.writeUTF("Hello");
} catch (RuntimeException | IOException e) {
e = new Exception(); // COMPILATION FAILS !!! (The e is final)
}
Bytecode generated by compiling a Use the diamond operator with generic declarationsYou can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>)
as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the
diamond.
For example, consider the following variable declaration: Map<String, List<String>> myMap = new HashMap<String, List<String>>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters ( Map<String, List<String>> myMap = new HashMap<>();
Note that to take advantage of automatic type inference during generic class instantiation, you MUST specify the diamond. In the following example,
the compiler generates an unchecked conversion warning because the Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example DOES NOT compile:
List<String> list = new ArrayList<>();
list.add("A");
// The following statement should fail since addAll expects Collection<? extends String>
list.addAll(new ArrayList<>()); // Compilations fails !!!
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations. In comparison, the following example successfully compiles:
List<String> list = new ArrayList<>();
list.add("A");
List<? extends String> list2 = new ArrayList<>(); // NOT very practical ;-)
list.addAll(list2); // OK, it expects Collection<? extends String>
The compiler infers the type on the right side. So if you have a List<?> list = new ArrayList<>();
Use more precise rethrow in exceptionsThe Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in thethrows clause of a method declaration.
Consider the following example:
public class FirstException extends Exception {
// ...
}
public class SecondException extends Exception {
// ...
}
public void rethrowException(String exceptionName) throws Exception {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e;
}
}
This examples's
However, in Java SE 7, you CAN specify the exception types
public void rethrowException(String exceptionName) throws FirstException, SecondException {
try {
// ...
} catch (Exception e) {
throw e;
}
}
This analysis is disabled if the
In detail, in Java SE 7, when you declare one or more exception types in a
The Java SE 7 compiler allows you to specify the exception types
In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the |
|