Java Concepts

1) Java is Pass by Value and Not Pass by Reference

What is pass by value vs pass by reference ?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.

Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

In java variables are just the reference to the objects, we get confused that we are passing the reference so java is pass by reference. However we are passing a copy of the reference and hence it’s pass by value.

Detailed Explanation at this post.

 

Object Oriented Programming

1) Encapsulation : Binding (or wrapping) data and functions that operate on that data together into a single unit is known as encapsulation.

2) Abstraction: Showing functionality and hiding internal details is known as abstraction.
eg. A database system hides certain details of how data is stored and created and maintained.

3) Inheritance: When one object acquires the properties and behaviors of parent object i.e. known as inheritance.

It provides code reusability. It is used to achieve runtime polymorphism.

eg. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear).

4) Polymorphism: refers to the ability of a variable, function or object to take on multiple forms.

Polymorphism could be static and dynamic both. Overloading is static polymorphism while, overriding is dynamic polymorphism.

Overloading in simple words means two methods having same method name but takes  different input parameters. This called static because, which method to be invoked will be decided at the time of compilation

Overriding means a derived class is implementing a method of its super class.

eg. To speak something e.g. cat speaks meaw, dog barks woof

Java Exception Handling

Java Exception handling is a framework that is used to handle runtime errors only, compile time errors are not handled by exception handling in java.

The exceptions have java.lang.Throwable as their superclass and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.The three main categories of Exceptional conditions are :

  • Error(represented by java.lang.Error and its sub-classes)
  • Checked Exception(represented by direct subclasses of java.lang.Exception except java.lang.RuntimeException)
  • Unchecked or Runtime Exceptions (represented by java.lang.RuntimeException and its sub-classes)

Errors : Errors denote serious abnormal condition with the application like OutOfMemoryError or VirtualMachineError. Any reasonable application should not try to recover from such a condition.

Runtime Exception/Unchecked Exception : These types of exceptions usually indicate programming errors like NullPointerException or IllegalArgumentException. The application may or may not choose to recover from the condition.

Checked Exception : An application is supposed to catch these types of exceptions and recover reasonably from them. Examples include FileNotFoundException and ParseException.

ExceptionHierarchy

Some of the useful methods of Throwable class are:
public String getMessage()
public String toString()
public void printStackTrace()

Java Exception Handling Keywords:
     throw, throws, try-catch, finally

finally – finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

Custom exceptions can be created by extending the Exception class.

Questions:

1) What is Exception in Java?

  • Exception is an error event that can happen during the execution of a program and disrupts it’s normal flow. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.

    Whenever any error occurs while executing a java statement, an exception object is created and then JRE tries to find exception handler to handle the exception. If suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then application throws the exception to runtime environment and JRE terminates the program.

    Java Exception handling framework is used to handle runtime errors only, compile time errors are not handled by exception handling framework.

 

2) What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options.

$>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

 

3) What happens when exception is thrown by main method?

When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

 

4) What is difference between final, finally and finalize in Java?

final and finally are keywords in java whereas finalize is a method.

final keyword can be used with class variables so that they can’t be reassigned, with class to avoid extending by classes and with methods to avoid overriding by subclasses, finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources. finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed.

Out of the three, only finally is related to java exception handling.

5) What is difference between Checked and Unchecked Exception in Java?

Checked Exceptions should be handled in the code using try-catch block or else main() method should use throws keyword to let JRE know about these exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.

Exception is the super class of all checked exceptions whereas RuntimeException is the super class of all unchecked exceptions.

Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present, whereas Unchecked exceptions are mostly caused by poor programming, for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.

 

Links: https://examples.javacodegeeks.com/java-basics/exceptions/java-custom-exception-example/, http://www.journaldev.com/1696/exception-handling-in-java

Questions on Exceptions: http://www.journaldev.com/2167/java-exception-interview-questions-and-answers

Java Reflection

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

Reflection enables us to:

  • Examine an object’s class at runtime
  • Construct an object for a class at runtime
  • Examine a class’s field and method at runtime
  • Invoke any method of an object at runtime
  • Change accessibility flag of Constructor, Method and Field

For example, JUnit use reflection to look through methods tagged with the @Test annotation, and then call those methods when running the unit test.

How to use reflection?
To use reflection API we need class object, which we can obtain it in two ways:
If we know the class name at compile time:

Class aClass = MyObject.class

Or if we can obtain the class object at runtime with fully qualified class name.

Class aClass = Class.forName(className)

Common Reflection Methods to access Class Information:

String className = aClass.getName();
String simpleClassName = aClass.getSimpleName();
int modifiers = aClass.getModifiers();
Package package = aClass.getPackage();
Class superclass = aClass.getSuperclass();
Class[] interfaces = aClass.getInterfaces();
Constructor[] constructors = aClass.getConstructors();
Method[] method = aClass.getMethods();
Field[] method = aClass.getFields();
Annotation[] annotations = aClass.getAnnotations();

Reflection accessing Constructor :

Constructor[] constructors = aClass.getConstructors();
// Retrieving the constructor that takes a String parameter
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
// Retrieving the Constructor parameter types
Class[] parameterTypes = constructor.getParameterTypes();
// Instantiating an object with construtor
MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");

 

Reflection accessing class fields:

Field[] fields = aClass.getFields();
// accessing the field named "name" in the class
Field field = aClass.getField("name");
String fieldName = field.getName();  // getting field name
Object fieldType = field.getType();  // getting field type
// Getting and setting field values

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);

 

Reflection accessing private fields and methods:
To access a private field you will need to call the Class.getDeclaredField(String name) or Class.getDeclaredFields() method along with Field.setAcessible(true. The methods Class.getField(String name) and Class.getFields() methods only return public fields, so they won’t work.

To access a private method you will need to call the Class.getDeclaredMethod(String name, Class[] parameterTypes) or Class.getDeclaredMethods() method along with Method.setAcessible(true. The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods, so they won’t work.

 

Refer to this tutorial for detailed description of Reflection API’s
http://tutorials.jenkov.com/java-reflection/index.html, http://www.programcreek.com/2013/09/java-reflection-tutorial/