Why would one need try-finally block combination

If we dont wanna handle the exception and instead propogate it up the hierarchy then we go for try-finally combination

how does polymorphism works within the constructors

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.

How does DriverManager identify the type of driver loaded into JVM

Typical JDBC code to connect to the database is:

New Changes in JDK7

JDK7 is packaged with these new changes
– Small language changes
– NIO-2 Enhanced NIO
– invokedynamic
– other features

Small language Changes:

  • Now integer can accept binary format (along with octal and hexadecimal values)
<pre>int i = 0b10110
  • Switch statement can accept string variables. Since String object in Java is considered immutable, java community has come up with this concept

usage:

public int useSwitch(String strCase) {
switch(strCase) {
case "A":
return 1;
case "B":
return 2;
...
default:
return 10;
}
}
  • Inferring types with <>: while using generics RHS of stmt can be replaced with just <>

usage:

</pre>
List<String> list = new ArrayList<>();
<pre>

Note: No need to explicitly mentioned type on the RHS

  • Easy rethrow (replace multiple catch blocks with single catch block)

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

different ways of getting a new object in Java

For now I can think of getting a new object in 4 different ways

  • ‘new’ operator
  • reflection
  • deserialization
  • cloning

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

Java Security Model and its anatomy

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

Java Sandbox Model

Java Sandbox Model

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

  • Security Provider Interface– the means by which different security implementations can be plugged into security package.
  • Message Digests
  • Keys and certificates
  • Digital Signatures
  • Encryption (JCE & JSSE)
  • Authentication (through JAAS)

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

Can we propagate exceptions in threads?

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

types of traversals in a binary tree

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
 

What is BIG(O) NOTATION

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

When to use ArrayList and LinkedList in java

These two data structures(DS) operate exactly opposite in terms of read and write operations.

ArrayList: this is build from a basic array

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

Linked List: This is build from double linked list

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