Why would one need try-finally block combination
October 9, 2012 Leave a comment
If we dont wanna handle the exception and instead propogate it up the hierarchy then we go for try-finally combination
"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." — John Tukey
October 9, 2012 Leave a comment
If we dont wanna handle the exception and instead propogate it up the hierarchy then we go for try-finally combination
October 9, 2012 Leave a comment
First of all it is not good practice to call any instance methods inside the constructor, if we cannot avoid then do as little as possible.
What happens:
Assume we call a over-ridden method within the constructor and if that method manipulates data that has not been initialized (because constructor is not yet completed) yet then it will lead to disaster.
The only safe methods inside the constructor to call are final methods in base class.
October 9, 2012 Leave a comment
Typical JDBC code to connect to the database is:
October 9, 2012 Leave a comment
JDK7 is packaged with these new changes
– Small language changes
– NIO-2 Enhanced NIO
– invokedynamic
– other features
Small language Changes:
<pre>int i = 0b10110
usage:
public int useSwitch(String strCase) {
switch(strCase) {
case "A":
return 1;
case "B":
return 2;
...
default:
return 10;
}
}
usage:
</pre> List<String> list = new ArrayList<>(); <pre>
Note: No need to explicitly mentioned type on the RHS
usage:
try {
// Reflective operations calling Class.forName,
// Class.newInstance, Class.getMethod,
// Method.invoke, etc.
...
} catch(final FileNotFoundException |
SQLException |
ClassNotFoundException) {
log(e);
throw e;
}
// try with resources
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(ds)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
NIO-2 Enhanced NIO
NIO-2 (Enhanced Asynchronous NIO)
invokedynamic
Dynamic linking of method by the JVM is introduced
Other Features:
Fork joins (for recursive functionalities) – Multi process environment
October 9, 2012 Leave a comment
For now I can think of getting a new object in 4 different ways
Using new operator
MyClass mc = new MyClass();
– Here MyClass.java availability will be checked at compile time.
– This is the most common way of creating objects in day-2-day activities of java programmer
using Class.forName(“<fully-qualified-class-name>”)
Class c = Class.forName("com.techforum.MyClass");
c.newInstance();
– Here code will compile without any issues, ie, with/without presence of MyClass.java in the classpath. But at runtime if the class is not found then it will throw run time exception. For this reason we are forced to handle ClassNotFoundException, it is an compile time exception, while loading a class at runtime
Using clone method
MyClass mc = new MyClass(); MyClass mcClone = mc.clone();
– Here we should make sure MyClass.java is implementing Cloneable interface in order to clone its object.
Deserialization
ObjectInputStream ois = new ObjectInputStream(is); // Here is 'is' is stream representing the flat file // that is generated while serializing the object MyClass object = (MyClass) ois.readObject();
– Here we should make sure we are implementing Serializable interface if we wanna serialize/deserialize object
October 9, 2012 Leave a comment
Java Sandbox Model
Java has circumvented the virus or Trojan horse problems that plagued other models of software distributions. Java sandbox model is responsible for protecting a number of resources and it does it at number of levels.
Java programs are considered safe because they cannot run, install or propagate viruses and program itself cannot perform any action that is harmful to the user’s computing environment.
Anatomy of java application in SECURITY
The components drawn in the above figure play important role in java security model.
Byte Code verifier:
It ensures that all java class files that are loaded into JVM follow the rules of the Java language. In terms of resources, it helps enforce memory protections for all java programs. As the figure implies not all the class files are subjected to byte code verification.
Class Loader
One or more class loaders load all the java classes. Programmatically, the class loader can set permissions for each class it loads.
Access Controller
It allows OR prevents access from the core API to the operating system, based upon the policies set by the end user or administrator.
Security Manager
This is the primary interface between Core API and Operating System, however it exists for historic reasons
Security Package
It allows you to add security features to your applications as well as providing the basis by which java classes may be signed. This is a complex API and is further broken into following
Key database
Key database is a set of keys used by the security infrastructure to create or verify digital signatures.
With respect to the sandbox, digital signatures play an important role because they provide authentication of who actually provided java class
October 9, 2012 Leave a comment
Prior to Java1.5 we cannot because the run() method in Runnable interface is written such that there is no return value as well as return exceptions in the method signature and hence the overridden method cannot propagate exceptions.
In Java1.5 SUN has released java.util.concurrent package in which alternative to Runnable i.e, Callable is introduced which can return any type and throw any subtype of Exception.
So,
– Using Runnable interface, one cannot propagate the exception and cannot return any value (return type is ‘void’), hence we should go for try-catch block to handle the exception
– Using Callable interface, we can propagate exception( or return a value) to the parent thread where we invoked the callable thread.
Sample code demonstrating the usage is uploaded in GITHub
https://github.com/ntallapa/TechForumWorkspace
October 8, 2012 Leave a comment
There are three types of traversals in binary tree: pre-order, in-order and post-order
Lets take an example of BST
20
15 25
12 18 22 28
pre-order: visit each node before its children
public void preorder(BinaryNode root) {
if(root != null) {
System.out.println(root.element);
preorder(root.left);
preorder(root.right);
}
}
Output: 20, 15, 12, 18, 25, 22, 28
in-order (applied only for binary trees): visit left sub-tree, node and then right sub-tree
public void inorder(BinaryNode root) {
if(root != null) {
inorder(root.left);
System.out.println(root.element);
inorder(root.right);
}
}
Output: 12, 15, 18, 20, 22, 25, 28
Note: If we notice the above elements they are all sorted which means the inorder traversal of any BST gives us the sorted elements.
post-order: visit each node after its children (left and right sub trees)
public void postorder(BinaryNode root) {
if(root != null) {
postorder(root.left);
postorder(root.right);
System.out.println(root.element);
}
}
Output: 12, 18, 15, 22, 28, 25, 20
October 8, 2012 Leave a comment
BIG O Notation is used to represent complexity of an algorithm in worst case scenario.
Complexity in computer programming can be defined in terms of time and space. Space complexity tells us how much space is going to be taken for a particular algorithm. Time complexity tells us number of iterations (indirectly time) that are required for the completion of an algorithm.
O(1) means It takes constant space/time irrespective of the size of the data structure
O(n) means the space/time complexity is proportional to the length of the data structure
October 8, 2012 1 Comment
These two data structures(DS) operate exactly opposite in terms of read and write operations.
read operation complexity: O(1)
This is always constant because we query for an element based on index and hence there is no search involved to reach to the required element.
write operation: O(n)
Any modifications will lead to the shift of elements in an array completely, it first creates new array with new size inserts elements prior to the position of element to be inserted, then inserts the current element and inserts remaining elements after it.
Ex: If we wanna add element at 1st position then we need to shift all elements 1 position to the right and then insert element at first position
read operation: O(n):
Since the traversal of this data structure is based on links we need to traverse from starting position till the point we encounter the element that we are searching for, since in BIG-O notation time complexity is worst case scenario, if the element we are looking for is at last position then read operation complexity will be proportional to the length of the DS, hence O(n)
write operation: O(1):
Just by changing the links we would be able to insert the element at any position at any place in the DS which consumes same time
Mostly technology with occasional sprinkling of other random thoughts
Amir Amintabar's personal page
Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)
My words, my world...
Do not wait for leaders; do it alone, person to person - Mother Teresa
An unexamined life is not worth living – Socrates
A topnotch WordPress.com site
Just another WordPress.com site
"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey
Recent Comments