Monday, 30 May 2016
loops
Types of loops
for(initialization;termination;update):
1)initialization allows only assignment.
2)termination condition must return a boolean.
3)update: allows assignment, pre- and post operations, and method call, even new class instances; but logic comparing is allowed.
for(element:collection):
for(Iterator it;it has next)
do{}while(termination);
while(termination){do};
Keyword:
break: quite from the whole of loop.
continue:quite from current iteration.
Note: 1) 'break' used only in switch and loop; 2) 'continue' only used in the loop.
Switch(x) Rules
Java really have many rules, that is why it is the most hard lang. to dominate.
In java, x can only be
1) primitive type: byte, short, char, int
2) and their wrapper classes.
3) reference type: String and Enum.
please note: x cannot be boolean, long, float, and double.
5) x can be an expression, like a+b etc; but it must return types above.
6) Case values: a) the value of a case label must be compiling-time constant. the following case is not valid. however, you may make variable final, for the final variable won't be changed once it is declared and initialized. I guess the reason it is easy to understand. On compiling time, the case number are variables, then how to determine the case brunches?
the following is valid, for b and c are constants on compiling time.
how about the following case? it is not considered as compiling time constants, for the constant a and b, not initialized as declaring.
b) null cannot be case number. c) case number should have the same type as switch input type.
(7) switch body can only contain case and default brunch
(8) case type must fit the type of x
(9) case cannot be duplicated.
(10) x cannot be Object type, even though x could be String and Enum
(11) when x matches a case; it will be handled there; when a case has no break then it will falling down to implement the rest cases until a break is met.
(12) default can have break or not have; however, if default is located before or among cases, it should have a break.
Actually, I don't know why switch has been created so complicated; more than necessary?
In java, x can only be
1) primitive type: byte, short, char, int
2) and their wrapper classes.
3) reference type: String and Enum.
please note: x cannot be boolean, long, float, and double.
5) x can be an expression, like a+b etc; but it must return types above.
6) Case values: a) the value of a case label must be compiling-time constant. the following case is not valid. however, you may make variable final, for the final variable won't be changed once it is declared and initialized. I guess the reason it is easy to understand. On compiling time, the case number are variables, then how to determine the case brunches?
int a=10, b=20, c=30; switch (a) { case b+c: System.out.println(b+c); break; case 10*7: System.out.println(10*7512+10); break; }
the following is valid, for b and c are constants on compiling time.
final int a = 10; final int b = 20; final int c = 30; switch (a) { case b+c: System.out.println(b+c); break; }
how about the following case? it is not considered as compiling time constants, for the constant a and b, not initialized as declaring.
public class VarCase { /** * @param args the command line arguments */ public static void main(String[] args) { final int a, b; a = 20; b = 10; int x = a + b; switch (x) { case a + b: System.out.println("" + (a + b)); break; } } }
b) null cannot be case number. c) case number should have the same type as switch input type.
(7) switch body can only contain case and default brunch
(8) case type must fit the type of x
(9) case cannot be duplicated.
(10) x cannot be Object type, even though x could be String and Enum
(11) when x matches a case; it will be handled there; when a case has no break then it will falling down to implement the rest cases until a break is met.
(12) default can have break or not have; however, if default is located before or among cases, it should have a break.
Actually, I don't know why switch has been created so complicated; more than necessary?
Sunday, 29 May 2016
anagram
I am thinking of this ........... How to find out Permutations of a string
"TEAM"
"T" "E" "A" "M" //1
taking "T" and removing it from //1
"E" "A" "M" //2
"T" //3
combination of //2 and //3
"TE" "TA" and "TM"
Saturday, 28 May 2016
Object eligible for GC
1) When an object become no long accessed, for instance outside of its scope.
2) When an object reference variable is assigned a null, or re-assigned another object reference; so the object may become eligible for GC, for it might be not ref. any more.
Concept:
reference var. holding the reference value.
instance: it is instantiated in the heap memory by using new keyword, or specific case for the string using "hello world".
reference: more like the pointer in the C programming language; it points to a memory location of the instance.
Java passing by value:
When assigning an instance to a reference variable, its reference is copied to the reference variable.
When an instance has not been referred by any reference variable, then it is eligible to be released for saving resource. This is automatically by the garbage collector.
It is possible to explicitly declare a reference variable to be null, thus dissolving the binding with the instance. It is a way to release the instance, and become eligible to cleaned.
It is possible to explicitly force GC to do garbage collection, by using System.gc() command. However, the impact is not guaranteed immediately.
Scope of Java Variables
Variable life span depends on its scope. Only 4 scopes:
1) Class variable //1 once class loaded, accessible by all instances of class
2) Instance variable //2 once instance constructed as calling its constructor.
3) Method argument variable //3 once method is invoked
4) Local variable //4 being alive within the method alone, or a block.
//1 outside all instances of the class; accessible by all instances method and class methods.
//2 outside all instance methods, can be accessible by them alone.
//3 method argument variable has a method scope.
//4 within in a scope of method, or a block, for example a if(){ }
The scope of a local variable depends its declaration place within the method
Please note: instance variable cannot be accessible in a static context, i.e. by a class method.
Some rules:
(1) Class and instance var. should not be declared as the same name;(compiling error).
(2) Local var. and method parameter should not have the same name.(compiling error)
(3) Local var. can hide instance var and class var.
(4) Local var. must init. before using it, otherwise a compiling error.
1) Class variable //1 once class loaded, accessible by all instances of class
2) Instance variable //2 once instance constructed as calling its constructor.
3) Method argument variable //3 once method is invoked
4) Local variable //4 being alive within the method alone, or a block.
//1 outside all instances of the class; accessible by all instances method and class methods.
//2 outside all instance methods, can be accessible by them alone.
//3 method argument variable has a method scope.
//4 within in a scope of method, or a block, for example a if(){ }
The scope of a local variable depends its declaration place within the method
Please note: instance variable cannot be accessible in a static context, i.e. by a class method.
/** * * @author YNZ */ public class BlockScope { /** * @param args the command line arguments */ public static void main(String[] args) { boolean b = false; //method scope if (b) { int i = 0; //block scope } else { int i = 1; //block scope } } }
Some rules:
(1) Class and instance var. should not be declared as the same name;(compiling error).
(2) Local var. and method parameter should not have the same name.(compiling error)
(3) Local var. can hide instance var and class var.
(4) Local var. must init. before using it, otherwise a compiling error.
/** * * @author YNZ */ public class LocalVar { static int i; //class var. public static void main(String[] args) { //int i=0; local var. must be init. before using it. //local var. hiding the class field i. //Well, this is a java feature. this is not an error. for (int i = 0; i < 10; i++) { //local var. i within scope of for loop. System.out.print(" " + Math.random()); } System.out.println(""); for (int i = 0; i < 10; i++) {//local var. i with scope of for loop. System.out.print(" " + Math.random()); } System.out.print("\n"); } public void m() { int d; //method variable(local var.) //d++, it must be init. before using it; otherwise it gives comipling error. { { } }; } public void m(int x) { int y = 0; //int x =0 will cause an error
if (true) { int z = 0; //life span within if block } else { int z = 100; //life span within else block } int z =300; //so here it is valid. System.out.println(z); } }
3 ways to create String instance
It may be tricky if not knowing the concept clearly.
There are three ways to create String instances in java. They may be instantiated in different part of memory allocation, i.e. heap memory or string constant pool; in the constant pool, an string instance may be reused for memory efficiency.
1) String str = new String("hello world"); //1
2) String str = "hello world"; //2
3) System.out.println("hello world"); //3
//1: "new" will instantiate a new string object in heap memory, no matter what.
//2: JVM will check if the string constant already created in the constant pool first; if not, then create a new one; otherwise, the existing will be reused, so the reference of the same string maybe copied to different String variables.
//3: "xxxxx" may also instantiate a new string object in the string constant pool, if the same text constant is not existed yet.
Tuesday, 24 May 2016
Java Access Modifier
public: anywhere.
protected: accessible by classes within in the same package, and sub-class outside the package.
default: only access within the class and classes in the same package.
private: only access within the class, not accessible even by the sub-classes.
The following example will show a compiling error, for A constructor using default modifier cannot be accessible outside the package. So it causes sub-class to init. error as calling super().
//File A.java package a; public class A { A() { } public void print() { System.out.println("A"); } } //File B.java package b; import a.*; public class B extends A { B() { } public void print() { System.out.println("B"); } public static void main(String[] args) { new B(); } }
class normally being declared as public or default accessible.private class is invalid modifier for the class, actually it doesn't make any sense; a private class should be declared as an inner class.
Monday, 23 May 2016
instanceof determine if a subtypes is its super-type.
'instanceof' is used to determine if an object is a sub-type of a super-class.
If d is Double, then compiler definitely knows it is not a Date. so it will give a compiling error;
If d is Double, then compiler definitely knows it is not a Date. so it will give a compiling error;
String s = "ddd"; System.out.println(""+ s instanceof String); Double d = 1d; System.out.println(d instanceof java.util.Date);
'final' keyword
A 'final' keyword can be applied on a variable
Maybe a class variable or an instance variable. It means that once the variable is initialized, its value cannot be modified, or changed. Meaning that its value is considered as a constant. Therefore, a final variable must be initialized, as it is declared, Otherwise, compiler will pop up an error. It won't be automatically initialized as a null or a zero by Java.
final class variable should be initialized in a static block; final instance variable can be initialized in a constructor.
A 'final' keyword can be applied on a method
Maybe a class method or an instance method. Final methods can be inherited by sub-classes. However, for a class method it means that the method cannot be hidden; for an instance method it means that the method cannot be overridden.
A 'final' keyword applied on a class
It means that the class cannot be extended; there is no kids allowed.
Maybe a class variable or an instance variable. It means that once the variable is initialized, its value cannot be modified, or changed. Meaning that its value is considered as a constant. Therefore, a final variable must be initialized, as it is declared, Otherwise, compiler will pop up an error. It won't be automatically initialized as a null or a zero by Java.
final class variable should be initialized in a static block; final instance variable can be initialized in a constructor.
A 'final' keyword can be applied on a method
Maybe a class method or an instance method. Final methods can be inherited by sub-classes. However, for a class method it means that the method cannot be hidden; for an instance method it means that the method cannot be overridden.
A 'final' keyword applied on a class
It means that the class cannot be extended; there is no kids allowed.
/** * * @author YNZ */ public final class KeyFinal { public static final int A = 10; public static final int B; public final int x; static { B = 30; } public KeyFinal() { this.x = 20; } public final void doSome() { System.out.println("" + this.x); } public static void main(String[] args) { KeyFinal kf = new KeyFinal(); System.out.println("" + A); kf.doSome(); } }
Method Overriding and Virtual Method Invoking
The purpose of overriding is to allow sub-class to carry out the method in its own preferred way. So the same behaviour may differ from parents to its derivatives. It is an OOP feature that enables a derived class to define a specific implementation of exiting base class to extend its own behaviour.
Overriding is related to the concept of inheritance;
A constructor cannot be inherited. A static method is not inherited, but accessible for all instances. A final method cannot be inherited. So we don't need to talk about how to override them. Only non-final instance method that can be inherited, that is overriding about.
Method overriding reuses the method signature and using the same argument list. Overridden methods are also synonymous with polymorphic methods.
The static method cannot be overridden, but hidden; so the concept of overriding is only related to the inheritance concept.
A final method cannot be overridden.
A method that can be overridden by a derived class is called a virtual method. Please note that the virtual method is not a Java term, but a term used in OOP domain. A virtual method invocation refers to invoking correct overridden methods.
parts of a method declaration
non-access modifier ¶ access modifier ¶ return type¶ method name ¶ parameter list ¶ exception list¶
static/final ¶ public, protected
synchronised ¶ default, private
Correct syntax of overriding methods
method signature exactly the same
method argument: exactly the same
access modifier: can be the same level; or less restrictive access level
Non-access modifier: overriding method can use any non-access modifier.
Return type: covariant return types. the overridden method cannot return more generic type; otherwise, the client cannot determine what can be returned from the overridden method.
what is the co-variant principle?
supertype and sub-type
Exceptions that are thrown: for the checked exception, the overridden method can throw the same or none exception; or a subtype of exception that is thrown by the overridden method. An overriding method can throw any runtime exception, even the overridden method doesn't.
this is because the un-checked exception is not part of method composition, so it is not checked by the compiler.
The overriding method can throw no exception, the same exception or subtype of the exception that is thrown by the overridden method.
It is the reference variable type that dictates which overloaded method will be chosen at the compilation time.
Can you override all methods from the superclass?
No. you cannot override static method; you cannot override private method; you cannot override the final method. So you cannot override all methods from the superclass.
A Method can be overloaded, overridden, or hidden.
A Static method cannot be overridden but hidden. Hidden is about the scope.
Overloaded is about reuse the method signature, but different parameter list;
Overriding is about invoking virtual method;
Why overriding Class Object is important
Overriding happens only with the concept, Inheritance. Our parents prefer to celebrate a new year in their way; however, for the young generation, they may celebrate in a different way. In such a case, a method inherited can be overridden in the child class. It is called the overridden method, and its counterpart on the child class is called overriding method.
(1) using the same signature.
(2) using the same argument.
(3) allowing co-variant return types. (since Java 1.5)
(4) An overriding method cannot throw a superclass exception, while a constructor of a subclass cannot throw subclass exception(must be the same).
(4) An overriding method cannot throw a superclass exception, while a constructor of a subclass cannot throw subclass exception(must be the same).
private/final/static methods cannot be overridden.
private cannot be inherited so won't be overridden;
a final method is not allowed to be inherited.
a static method can be hidden, but not overridden.
(5)about access modifier: you cannot define more restrictive access modifier than the method that is going to be overridden.
(6) if the overridden method does not have any throws clause, the overriding method cannot declare any checked exceptions; can throw unchecked.
private cannot be inherited so won't be overridden;
a final method is not allowed to be inherited.
a static method can be hidden, but not overridden.
(5)about access modifier: you cannot define more restrictive access modifier than the method that is going to be overridden.
(6) if the overridden method does not have any throws clause, the overriding method cannot declare any checked exceptions; can throw unchecked.
Friday, 20 May 2016
random access
ref. to how to access data. Random access is also called direct access, you can read and write anywhere in the random access; in the sequential access you have to read or write in a sequence. it seems random access is more efficient access than sequential access.
In java, there is a pubic interface modifier, java.util.RandomAccess.
ArrayList is the one typically implement this interface;
It needs to consider the performance view implementing RandomAcess, or not.
ArrayList implements RandomAcess, but LinkedList implements not. How to compare them on accessing?
I think the random access in the linked-list is not efficient.
from string to numeric, and vice versa
Java primitive types: boolean, byte, char, short, int, long, float, and double.
Java primitive wrappers: Boolean, Byte, Character, Short, Integer, Long, Float, and Double.
The pairs follow auto-boxing principle.
Wrapper classes offer certain amount of static methods, for instance, converting number in string into numeric values.
/* * Class wrappers of primitive types offer static service methods. * converting digit numbers from String to numeric primitive type. * String class offers another way around, converting number to string. */ package NumberWraper; /** * * @author YNZ */ public class UserNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { double d = Double.parseDouble("20.456"); double a = Double.parseDouble("10.46"); double sum = a + d; System.out.printf("%f + %f = %f \n ", d, a, sum); //converting from numeric to string. String aStr = String.valueOf(d); String dStr = String.valueOf(a); //valueOf srevice returns wrapper type Double e = Double.valueOf(dStr); } }You need watch out the number type even in the String format.
double ee = Double.parseDouble("20"); //1 int ff = Integer.parseInt("121.3"); //2
//1 is fine, for double may hold a int type without losing.
//2 is not valid for "121.3" is not integer.
exception happens in the catch block
it cannot be caught, but need adding a nested try block, or throws it to the caller.
/* * exception happends in catch block won't be caught. * using nested try block to catch it. * or throws to caller. */ package Ex; import java.io.IOException; /** * * @author YNZ */ class PortConnector { public PortConnector(int port) throws Exception { if (Math.random() > 0.5) { throw new IOException(); } throw new MyException(); } } class ThrowExcep { @SuppressWarnings("CallToPrintStackTrace") public static void main(String[] args) throws Exception { try { try { PortConnector pc = new PortConnector(10); } catch (Exception re) { re.printStackTrace(); throw new ArithmeticException(); } finally { System.out.println("finally"); } } catch (Exception e) { e.printStackTrace(); } } } class MyException extends Exception{ public MyException() { super("my exception"); } }
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?
(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.
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.
Class.forName("com.mysql.jdbc.Driver");
DriverManager class, as follows:
Connection connection = DriverManager.getConnection(databaseURL);
ResultSet resultSet = statement.executeQuery("select firstName, mi, lastName from Student where lastName = 'Smith'");
// Iterate through the result and print the student names
while (resultSet.next())
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
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 theDriverManager 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.
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
- 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
Subscribe to:
Posts (Atom)
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...
-
Could not extract response: no suitable HttpMessageConverter found for response type [class dk.enettet.evu.core.model.Address] and content ...
-
First time met this hibernate exception. I think this issue should due to one to one relationship. One driver has one car; one car has on...
-
A large object refers to the entity property that is modified by @Lob. It may be persisted in several records. However, in database manage...