Thursday, 19 May 2016

keyword strictfp


The strictfp keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE’s 754 standard, explicitly. Without using strictfp keyword, the floating point precision depends on target platform’s hardware, i.e. CPU’s floating point processing capability. In other words, using strictfp ensures result of floating point computations is always same on all platforms.

The strictfp keyword can be applied for classes, interfaces and methods.


Rules


  • strictfp cannot be applied for constructors.
  • If an interface or class is declared with strictfp, then all methods and nested types within that interface or class are implicitly strictfp.
  •  strictfp cannot be applied for interface methods.

return in catch block - can return over-skip finally block?

NO.
return is allowed inside the catch block.

What the following code will print out?

public class TestClass{

public static void main(String args[]){



try{

m1();

}

catch(IndexOutOfBoundsException e){

System.out.println("1");

throw new NullPointerException();

}

catch(NullPointerException e){

System.out.println("2");

return;

}

catch (Exception e) {

System.out.println("3");

}

finally{

System.out.println("4");

}



System.out.println("END");

}



// IndexOutOfBoundsException is a subclass of RuntimeException.

static void m1(){

System.out.println("m1 Starts");

throw new IndexOutOfBoundsException( "Big Bang " );

}

}





(1) exception can only be caught inside the try block. so NullPointerException won't be caught in this case.
(2) return is not reached.
(3) finally will definitely implemented.
(4) "END" won't be reached, for NullPointerException has been thrown to the main method.

print out:

m1 Starts 1 4

Remained question:
if 'return' can stop 'finally' implemented? I remember 'return' is an exception for 'finally'.
no, 'return' cannot stop 'finally' block.

Only if, in a try or catch block, System.exit() is called then finally will not be
executed.







Keyword Break and Continue


Continue can be only used inside for, while and do loop.
Break can be used outside loop, for instance, in the switch.

label:
{
 .... statement a;
   break label;
 ... statement b;
}
 .... statement c;

On the break, it try to handle control back to the label, and it start to operate on the statement c.

Tuesday, 17 May 2016

Java Database Connectivity (JDBC)

Four key interfaces are needed to develop any database application using Java: Driver, Connection, Statement, and ResultSet. 

These interfaces define a framework for generic SQL database access. The JDBC API defines these interfaces, and the JDBC driver vendors provide the implementation for the interfaces. 

Programmers use these interfaces.  A JDBC application loads an appropriate driver using the Driver interface, connects to the database using the Connection interface, creates and executes SQL statements using the Statement interface, and processes the result using the ResultSet interface if the statements return results.






Step 1. Loading drivers

Before JDBC version 3.0, the driver has to be loaded manually. 
A driver is a concrete class that implements the java.sql.Driver interface.

Class.forName("com.mysql.jdbc.Driver");

After the JDBC version 4.0, the driver can be loaded automatically, if the driver-jar file is located with the classpath. The SPM automates the driver loading mechanism. Using SPM, every JDBC 4.0 driver implementation must include the configuration file with the name java.sql.Driver within the META-INF/services folder in their .jar file. The file java.sql.Driver contains the full name of the class that the vendor used to implement the interface jdbc.sql.Driver. For example, com.mysql.jdbc.Driver is the name for the MySQL driver. When DriverManager requests a database connection, it loads these driver classes.

Step 2. Establishing Connections

To connect to a database, use the static method getConnection(databaseURL) in the
DriverManager class, as follows:
Connection connection = DriverManager.getConnection(databaseURL);

java.sql.Connection

The interface java.sql.Connection represents a connection session with the specified database. 
The Connection object provides a database’s metadata, information regarding the data stored in a database. It makes accessible the SQL grammar supported by the database, its stored procedures, and other database-related information.

public static Connection getConnection(String url) throws SQLException
public static Connection getConnection(String url, Properties info) throws SQLException
public static Connection getConnection(String url, String user, String pwd) throws SQLException

url = jdbc:subprotocol://<host>:<port>/<database_name>

specify additional parameters like the default connectTimeout, autoConnect, and others.
url = jdbc:subprotocol://<host>:<port>/<database_name>?<connectTimeout>

There are two ways to connect to a database: by using class java.sql.DriverManager or the interface javax.sql.DataSource. Class DriverManager is the preferred class to establish database connections with Java SE applications because DataSource works with the Java Naming and Directory Interface (JNDI). JNDI is usually supported by Java applications with a container that supports JNDI like Java Enterprise Edition Server.

Step 3. Creating Statements

Statement statement = connection.createStatement("sql-query");

The interface java.sql.Statement is used to create and execute static SQL statements and retrieve their results. The results from the database are returned as ResultSet objects or int values indicating the number of affected rows.

Step 4. Executing Statements

Method executeQuery() is used for SQL SELECT statements

ResultSet resultSet = statement.executeQuery("select firstName, mi, lastName from Student where lastName = 'Smith'");

Though the case of SQL is ignored by the underlying database, the use of uppercase for keywords is recommended and practised for better readability.

Although everything in Java is 0-based, column indexes in a ResultSet are 1-based.

Method executeUpdate() returns a count of the rows that are
or would be affected in the database for row insertions, modifications,
and deletion.


Method executeUpdate() is used to execute SQL queries to insert new rows in a table and update and delete existing rows.  It’s also used to execute DDL queries, such as the creation, modification, and deletion of database objects like tables.  If you use method executeQuery() for any of these operations, you’ll get an SQLException at runtime.

Step 5. Processing ResultSet

The ResultSet maintains a table whose current row can be retrieved. The initial row position is null. You can use the next method to move to the next row and the various getter methods to retrieve values from a current row. For example, the following code displays all the results from the preceding SQL query.

// Iterate through the result and print the student names
while (resultSet.next())

The interface java.sql.ResultSet is retrieved as a result of executing a SQL SELECT statement against
a database. It represents a table of data. The ResultSet object can be read-only, scrollable, or updatable. By default, a ResultSet object is only read-only and can be traversed in only one (forward) direction. You can create a scrollable ResultSet (that can be traversed forward and backwards) and/or an
updatable ResultSet bypassing the relevant parameters during the creation of a Statement object.


Method executeUpdate() is used to execute SQL queries to insert new rows in a table and update and delete existing rows.  It’s also used to execute DDL queries, such as the creation, modification, and deletion of database objects like tables.  If you use method executeQuery() for any of these operations, you’ll get an SQLException at runtime.



Using Transaction
It is a way to making sure the amounts consistent. A transaction is a set of one or more statements that are executed as a unit, so either all of the statements are executed, or none of the statements is executed.

Disable  auto commit first: con.setAutoCommit(false);

Committing Transactions:  con.commit();

Using Transactions to Preserve Data Integrity
Setting and Rolling Back to Savepoints






Monday, 16 May 2016

Upgrade Java SE 7 to Java SE 8 OCP Programmer 1Z0-810

Exam topics: 



Assume the following:
  • Missing package and import statements: If sample code do not include package or import statements, and the question does not explicitly refer to these missing statements, then assume that all sample code is in the same package, and import statements exist to support them.
  • No file or directory path names for classes: If a question does not state the file names or directory locations of classes, then assume one of the following, whichever will enable the code to compile and run:
    • All classes are in one file
    • Each class is contained in a separate file, and all files are in one directory
  • Unintended line breaks: Sample code might have unintended line breaks. If you see a line of code that looks like it has wrapped, and this creates a situation where the wrapping is significant (for example, a quoted String literal has wrapped), assume that the wrapping is an extension of the same line, and the line does not contain a hard carriage return that would cause a compilation failure.
  • Code fragments: A code fragment is a small section of source code that is presented without its context. Assume that all necessary supporting code exists is present and that the supporting environment fully supports the correct compilation and execution of the code shown and its omitted environment.
  • Descriptive comments: Take descriptive comments, such as "setter and getters go here," at face value. Assume that correct code exists, compiles, and runs successfully to create the described effect.
TOPICS
Lambda Expressions
  • Describe and develop code that uses Java inner classes, including nested class, static class, local class, and anonymous classes
  • Describe and write functional interfaces
  • Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing
Using Built-in Lambda Types
  • Describe the interfaces of the java.util.function package
  • Develop code that uses the Function interface
  • Develop code that uses the Consumer interface
  • Develop code that uses the Supplier interface
  • Develop code that uses the UnaryOperator interface
  • Develop code that uses the Predicate interface
  • Develop code that uses the primitive and binary variations of the base interfaces of the java.util.function package
  • Develop code that uses a method reference, including refactoring a lambda expression to a method reference
Java Collections and Streams with Lambdas
  • Develop code that iterates a collection by using the forEach() method and method chaining
  • Describe the Stream interface and pipelines
  • Filter a collection by using lambda expressions
  • Identify the operations, on stream, that are lazy
Collection Operations with Lambda
  • Develop code to extract data from an object by using the map() method
  • Search for data by using methods such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()
  • Describe the unique characteristics of the Optional class
  • Perform calculations by using Java Stream methods, such as count(), max(), min(), average(), and sum()
  • Sort a collection by using lambda expressions
  • Develop code that uses the Stream.collect() method and Collectors class methods, such as averagingDouble(), groupingBy(), joining(), and partitioningBy()
Parallel Streams
  • Develop code that uses parallel streams
  • Implement decomposition and reduction in streams
Lambda Cookbook
  • Develop code that uses Java SE 8 collection improvements, including Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods
  • Develop code that uses Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods
  • Use flatMap() methods in the Stream API
  • Develop code that creates a stream by using the Arrays.stream() and IntStream.range() methods
Method Enhancements
  • Add static methods to interfaces
  • Define and use a default method of an interface and describe the inheritance rules for the default method
Use Java SE 8 Date/Time API
  • Create and manage date- and time-based events, including a combination of date and time in a single object, by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration
  • Work with dates and times across time zones and manage changes resulting from daylight savings, including Format date and times values
  • Define, create, and manage date- and time-based events using Instant, Period, Duration, and TemporalUnit

OCPJP 7 Objectives




Java Class Design 
  • Use access modifiers: private, protected, and public
  • Override methods 
  • Overload constructors and methods 
  • Use the instanceof operator and casting
  • Use virtual method invocation
  • Override the hashCode, equals, and toString methods from the Object class to improve the functionality of your class. 
  • Use package and import statements
Advanced Class Design 
  • Identify when and how to apply abstract classes
  • Construct abstract Java classes and subclasses
  • Use the static and final keywords
  • Create top-level and nested classes
  • Use enumerated types
Object-Oriented Design Principles 
  • Write code that declares, implements and/or extends interfaces
  • Choose between interface inheritance and class inheritance
  • Apply cohesion, low-coupling, IS-A, and HAS-A principles
  • Apply object composition principles (including has-a relationships)
  • Design a class using a Singleton design pattern
  • Write code to implement the Data Access Object (DAO) pattern
  • Design and create objects using a factory pattern
Generics and Collections
  • Create a generic class
  • Use the diamond for type inference  
  • Analyze the interoperability of collections that use raw types and generic types 
  • Use wrapper classes, autoboxing and unboxing
  • Create and use List, Set and Deque implementations
  • Create and use Map implementations
  • Use java.util.Comparator and java.lang.Comparable
  • Sort and search arrays and lists
String Processing 
  • Search, parse and build strings (including Scanner, StringTokenizer, StringBuilder, String and Formatter)
  • Search, parse, and replace strings by using regular expressions, using expression patterns for matching limited to: . (dot), * (star), + (plus), ?, \d, \D, \s, \S,  \w, \W, \b. \B, [], ().
  • Format strings using the formatting parameters: %b, %c, %d, %f, and %s in format strings.
Exceptions and Assertions 
  • Use throw and throws statements 
  • Develop code that handles multiple Exception types in a single catch block
  • Develop code that uses try-with-resources statements (including using classes that implement the AutoCloseable interface)
  • Create custom exceptions
  • Test invariants by using assertions
Java I/O Fundamentals 
  • Read and write data from the console
  • Use streams to read from and write to files by using classes in the java.io package including BufferedReader, BufferedWriter, File, FileReader, FileWriter, DataInputStream, DataOutputStream, ObjectOutputStream, ObjectInputStream, and PrintWriter
Java File I/O (NIO.2) 
  • Operate on file and directory paths with the Path class 
  • Check, delete, copy, or move a file or directory with the Files class  
  • Read and change file and directory attributes, focusing on the BasicFileAttributes, DosFileAttributes, and PosixFileAttributes interfaces
  • Recursively access a directory tree using the DirectoryStream and FileVisitor interfaces
  • Find a file with the PathMatcher interface
  • Watch a directory for changes with the WatchService interface
Building Database Applications with JDBC 
  • Describe the interfaces that make up the core of the JDBC API (including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations)
  • Identify the components required to connect to a database using the DriverManager class (including the jdbc URL)
  • Submit queries and read results from the database (including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections)
  • Use JDBC transactions (including disabling auto-commit mode, committing and rolling back transactions, and setting and rolling back to savepoints)
  • Construct and use RowSet objects using the RowSetProvider class and the RowSetFactory interface
  • Create and use PreparedStatement and CallableStatement objects
Threads 
  • Create and use the Thread class and the Runnable interface
  • Manage and control thread lifecycle
  • Synchronize thread access to shared data
  • Identify code that may not execute correctly in a multi-threaded environment.
Concurrency 
  • Use collections from the java.util.concurrent package with a focus on the advantages over and differences from the traditional java.util collections.
  • Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks package to support lock-free thread-safe programming on single variables.
  • Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools.
  • Use the parallel Fork/Join Framework
Localization 
  • Read and set the locale by using the Locale object
  • Build a resource bundle for each locale
  • Call a resource bundle from an application
  • Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes (including number format patterns)
  • Describe the advantages of localizing an application
  • Define a locale using language and country codes

Wednesday, 11 May 2016

Exam. Objectives of OCAJP



TOPICS
Java Basics
  • Define the scope of variables: class scope, method scope, loop scope.
  • Define the structure of a Java class: interface, abstract class, and class
  • Create executable Java applications with a main method: public static void main(String ... args)
  • Import other Java packages to make them accessible in your code:  import static and import 
Working With Java Data Types
  • Declare and initialize variables : 
  • primitive and reference type.  init. block instance fields and static init. block. 
  • Differentiate between object reference variables and primitive variables
  • var. store reference to object; comparing the content, but not reference; 
  • Read or write to object fields
  • Explain an Object's Lifecycle (creation, "dereference" and garbage collection)
  • reference = null; system.GC() suggest jvm to collect. 
  • Call methods on objects
  • Manipulate data using the StringBuilder class and its methods
  • Creating and manipulating Strings
Using Operators and Decision Constructs  
  • Use Java operators
  • Use parenthesis to override operator precedence
  • Test equality between Strings and other objects using == and equals ()
  • Create if and if/else constructs
  • Use a switch statement
Creating and Using Arrays
  • Declare, instantiate, initialize and use a one-dimensional array
  • Declare, instantiate, initialize and use multi-dimensional array
  • *Declare and use an ArrayList
Using Loop Constructs
  • Create and use while loops
  • Create and use for loops including the enhanced for loop
  • Create and use do/while loops
  • Compare loop constructs
  • Use break and continue  
Working with Methods and Encapsulation
  • Create methods with arguments and return values
  • Apply the static keyword  to methods and fields  
  • Create an overloaded method
  • Differentiate between default and user defined constructors
  • Create and overload constructors
  • Apply access modifiers
  • Apply encapsulation principles to a class
  • Determine the effect upon object references and primitive values when they are passed  into methods that change the values
Working with Inheritance
  • Implement inheritance
  • Develop code that demonstrates the use of polymorphism
  • Differentiate between the type of a reference and the type of an object
  • Determine when casting is necessary
  • Use super and this to access objects and constructors
  • Use abstract classes and interfaces
Handling Exceptions
  • Differentiate among checked exceptions, RuntimeExceptions and Errors
  • Create a try-catch block and determine how exceptions alter normal program flow
  • Describe what Exceptions are used for in Java
  • Invoke a method that throws an exception
  • Recognize common exception classes and categories



Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...