JAXB - Unmarshalling Example

Marshalling Example
File: com.ram.core.Person.java
 package com.ram.core;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
 private String name;
 private int id;
 private int age;
 private String address;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
 
 
File: C:\Person.xml
  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <address>Richmond</address>
    <age>31</age>
    <id>1</id>
    <name>Ram</name>
</person>
  
  
File: com.ram.core.UnmarshallExample.java
package com.ram.core;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class UnmarshallExample {
 public static void main(String[] args) {
  try{
   JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
   Unmarshaller unmarshall = jaxbContext.createUnmarshaller();
   
   File f = new File("C:\\Person.xml");
            Person person = (Person) unmarshall.unmarshal(f);
 
            System.out.println("Name = "+person.getName());
            System.out.println("Id = "+person.getId());
            System.out.println("Age = "+person.getAge());
            System.out.println("Address = "+person.getAddress());
   
   
  }catch(Exception e){
   System.out.println("Exception occurred while unmarshalling ..."+e);
  }
 }

}

 
Below is the output file that gets generated when the above program is executed
Name = Ram
Id = 1
Age = 31
Address = Richmond

JAXB - Marshalling example

Marshalling Example
File: com.ram.core.Person.java
 package com.ram.core;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
 private String name;
 private int id;
 private int age;
 private String address;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
 
 
File: com.ram.core.MarshallExample.java
package com.ram.core;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class MarshallExample {
 public static void main(String[] args){
  try{
   Person person = new Person();
   person.setName("Ram");
   person.setId(1);
   person.setAge(31);
   person.setAddress("Richmond");
   
   JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
   Marshaller jaxbMarshaller =  jaxbContext.createMarshaller();
   
   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
   
   File file = new File("C:\\Person.xml");
   jaxbMarshaller.marshal(person, file);
   jaxbMarshaller.marshal(person, System.out);
   
  }catch(Exception e){
   System.out.println("Exception while marshalling ..."+e);
  }
 }
}
 
 
Below is the output file that gets generated when the above program is executed
  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <address>Richmond</address>
    <age>31</age>
    <id>1</id>
    <name>Ram</name>
</person>
  
  

Static methods and static variables storage

Question: Where do static methods and static variables get stored in memory?
Answer: Static variables and static methods are called class members. Static variables are common to all objects of that class. So instead of objects they are associated with the class and it is located in a fixed location memory. Hence any change made to the static variable is visible to all the objects. Both static variables and static methods are stored inside heap memory, but there is a special area of the heap called "Permanent Generation" (or PermGen).
Only the variables and their primitives or references are stored in Permanent Generation space. If a static variable is holding a reference to an object, then the reference would be stored in PermGen and the object would be stored in the normal heap space. The below example makes it more clear:
Since variable 'a' is a static int, its value 10 is stored in "Permanent Generation" space.
 static int a= 10;
 
Since variable 'obj' is a static object, it is stored in "Permanent Generation" space.
But, the object would be stored in heap memory.
 static MyObject obj = new MyObject();
 

User defined exception example

Exception Handling: user defined exception example
package com.ram;

import java.io.BufferedReader;
import java.io.InputStreamReader;

class MyException extends Exception{
 private static final long serialVersionUID = 1L;
 String except;

 public MyException(String str){
  except = str;
 }

 public String toString(){
  return "This is from MyException ..."+except;
 }
}

public class ExceptionHandlingExample3 {
 public static void main(String[] args){
  int a, b, c=0;

  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

   System.out.print("Enter value for a :: ");
   a = Integer.parseInt(br.readLine());

   System.out.print("Enter value for b :: ");
   b = Integer.parseInt(br.readLine());

   if(b==0){
    throw new MyException("Dividing by zero will result in exception ... enter a value other than 0 for 'b'");
   }else{
    c = a / b;
   }

   System.out.println("Value of c is :: "+c);
   
  }catch(MyException mye){
   System.out.println("Catching MyException ...");
   System.out.println(mye);
  }
  catch(Exception e){
   System.out.println("Other exceptions ... "+e);
  }
 }
}

 
 
Execute ExceptionHandlingExample3 class and user would be prompted to enter two values.
Enter value for a :: 10
Enter value for b :: 0
Catching MyException ...
This is from MyException ...Dividing by zero will result in exception ... enter a value other than 0 for 'b'

try-catch-finally example

Exception Handling: try-catch-finally example
 package com.ram;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExceptionHandlingExample2 {
 public static void main(String[] args) {
  String name = "";
  
  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Entere a name:: ");
   name = br.readLine();
   char firstName[] = name.toCharArray();
   for(int i=0;i<=20;i++){
    System.out.print(firstName[i]);
   }
   
  }catch(ArrayIndexOutOfBoundsException aiobe){
   System.out.println(" An ArrayIndexOutOfBoundsException occured = "+aiobe);
  }
  catch(Exception e){
   System.out.println("Any other exception "+e);
  }finally{
   System.out.println("Name = "+name);
  }
 }
}

 
 
Execute ExceptionHandlingExample2 class and user would be prompted to enter a value.
Entere a name:: Sachin Tendulkar
Sachin Tendulkar An ArrayIndexOutOfBoundsException occured = java.lang.ArrayIndexOutOfBoundsException: 16
Name = Sachin Tendulkar

try-catch example

Exception Handling: try-catch example
 package com.ram;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExceptionHandlingExample1 {
 public static void main(String[] args){
  int a, b, c;

  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter value for a :: ");
   a = Integer.parseInt(br.readLine());
   
   System.out.print("Enter value for b :: ");
   b = Integer.parseInt(br.readLine());
   
   c = a / b;
   System.out.println("C = "+c);
  }
  catch(ArithmeticException ae){
   System.out.println("An ArithmeticException occured = "+ae);
  }
  catch(Exception e){
   System.out.println("Any other exception "+e);
  }
 }
}

 
 
Execute ExceptionHandlingExample1 class and user would be prompted to enter two values.
To check for exception, enter "0" for variable "b"
Enter value for a :: 30
Enter value for b :: 0
An ArithmeticException occured = java.lang.ArithmeticException: / by zero

StringBuilder Example

StringBuffer example
 package com.ram;

public class StringBuilderExample {
 public static void main(String[] args) {
  //Creates an empty StringBuilder with a capacity of 16.
  StringBuilder sBuilder = new StringBuilder();
  
  sBuilder.append("There ");
  sBuilder.append("is ");
  sBuilder.append("no ");
  sBuilder.append("shortcut ");
  sBuilder.append("to success. ");
  sBuilder.append("Work ");
  sBuilder.append("Hard. ");
  sBuilder.append("- ");
  sBuilder.append("Sachin ");
  sBuilder.append("Tendulkar");
  
  //To display the StringBuilder
  System.out.println(sBuilder);
  
  //To get the length of the StringBuilder
  System.out.println(sBuilder.length());
  
  //To reverse StringBuilder
  System.out.println(sBuilder.reverse());
 }
}
 
 
Execute StringBuilderExample class and you get the below output:
There is no shortcut to success. Work Hard. - Sachin Tendulkar
62
rakludneT nihcaS - .draH kroW .sseccus ot tuctrohs on si erehT

StringBuffer example

StringBuffer example
 package com.ram;

public class StringBufferExample {
 public static void main(String[] args) {
  StringBuffer sBuffer = new StringBuffer();
  sBuffer.append("If");
  sBuffer.append(" you");
  sBuffer.append(" can");
  sBuffer.append(" dream");
  sBuffer.append(" it,");
  sBuffer.append(" you");
  sBuffer.append(" can");
  sBuffer.append(" do");
  sBuffer.append(" it");
  
  System.out.println("Complete sentence: \n"+sBuffer);
  
  //To know the length of StringBuffer
  System.out.println("Sentence length = "+sBuffer.length());
  
  //To get a character at a particular position
  System.out.println("Character at position 5 is :: "+sBuffer.charAt(5));
  
  //To get a part of string
  System.out.println(sBuffer.substring(21, 34));
  
  //To reverse StringBuffer
  System.out.println("Reverse  = "+sBuffer.reverse());
  
 }
}
 
 
Execute StringBufferExample class and you get the below output:
Complete sentence:
If you can dream it, you can do it
Sentence length = 34
Character at position 5 is :: u
you can do it
Reverse = ti od nac uoy ,ti maerd nac uoy fI

How ArrayList works internally

Question: How ArrayList works internally?
Answer:
ArrayList is like an array which can grow in memory dynamically. And we also know that ArrayList is not synchronized by default. In this post we will see how ArrayList works internally.
ArrayList<String> al = new ArrayList<String>();

This is how we declare an ArrayList. Here we did not specify any size for the list. Since we have not specified any value for the ArrayList, the default size is "10". Internally ArrayList uses Object[] array. The object array list looks like this:
 private transient java.lang.Object[] elementData;
 
When ArrayList is created the below piece of code gets executed.

this.elementData = new Object[initialCapacity];

We add items to an ArrayList using .add(); function. As we add items to ArrayList, the list checks the maximum size and if there is any space available then new element will be added. If there is no space left then then a new array would be created with 50% more space than the current ArrayList and all the data would be copied to the newly created array.

Class Loader Sub System

Class loader sub system
First of all, it loads the .class file.
Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicion, the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to execute the program. This memory is divided into 5 parts, called run time data access, which contains the data and results while running the program.
Method area: Stores the class code, code of the variables and code of the methods in the program.
Heap: Area where objects are created. Whenever jvm loads a class, a method and a heap area are immediately created in it.
Java stacks: Method code is stored on method area. But while running a method, it needs some more memory to store the data and results. This memory is allocated on java stacks. So these are the memory areas where java methods are executed. While executing methods, a separate frame will be created in the java stack, where the method is executed. Jvm uses a separate thread or process to execute each method.
PC (Program counter) registers:
These are the registers (memory areas), which contain memory address of the instructions of the methods. If there are 3 methods, 3 pc registers will be used to track the instructions of the methods.
Native method stacks: Java methods are executed on java stacks. Similarly native methods (C/C++) are executed here.

Execution engine contains interpreter and JIT compiler which are responsible for converting the byte code instructions into a machine code.

Enum example

Enum example
 package com.ram;

enum Continents{
 AUSTRALIA, ASIA, EUROPE, AFRICA, NORTH_AMERICA, SOUTH_AMERICA, ANTARCTICA 
}

public class EnumExample {
 
 Continents continents;
 
 public EnumExample(Continents continents){
  this.continents = continents;
 }
 
 public void tellAboutContinents(){
  switch(continents){
   case AUSTRALIA:
    System.out.println("Australia is the largest island. Australia's Great Barrier Reef is the world's largest coral reef.");
    break;
    
   case ASIA:
    System.out.println("It is the largest continent. It is the home of the 10 highest mountain peaks in the world.");
    break;
   
   case EUROPE:
    System.out.println("In Europe, there are no deserts.It is the only continent without any deserts.");
    break;
   
   case AFRICA:
    System.out.println("Africa is very rich in minerals.Ninety five percent of the worlds’s diamonds and more than 50% of the world’s gold comes from Africa.");
    break;
    
   case NORTH_AMERICA:
    System.out.println("North America was named after the explorer Americo Vespucci. North America is the only continent that has every kind of climate.");
    break;
    
   case SOUTH_AMERICA:
    System.out.println("The Angel Falls of South America ,is the Highest Waterfall in the World.");
    break;
    
   case ANTARCTICA:
    System.out.println("Antarctica is a frozen land area around the South Pole.It is also called Frozen Continent.");
    break;
   
   default:
    System.out.println("Rest is ocean ...");
  }
 }
 
 public static void main(String[] args) {
  EnumExample australia = new EnumExample(Continents.AUSTRALIA);
  australia.tellAboutContinents();
  EnumExample asia = new EnumExample(Continents.ASIA);
  asia.tellAboutContinents();
  EnumExample europe = new EnumExample(Continents.EUROPE);
  europe.tellAboutContinents();
  EnumExample africa = new EnumExample(Continents.AFRICA);
  africa.tellAboutContinents();
  EnumExample northAmerica = new EnumExample(Continents.NORTH_AMERICA);
  northAmerica.tellAboutContinents();
  EnumExample southAmerica = new EnumExample(Continents.SOUTH_AMERICA);
  southAmerica.tellAboutContinents();
  EnumExample antarctica = new EnumExample(Continents.ANTARCTICA);
  antarctica.tellAboutContinents();
  
 }
}
 
 
 
Execute EnumExample class and you get the below output:

Australia is the largest island. Australia's Great Barrier Reef is the world's largest coral reef.
It is the largest continent. It is the home of the 10 highest mountain peaks in the world.
In Europe, there are no deserts.It is the only continent without any deserts.
Africa is very rich in minerals.Ninety five percent of the worlds’s diamonds and more than 50% of the world’s gold comes from Africa.
North America was named after the explorer Americo Vespucci. North America is the only continent that has every kind of climate.
The Angel Falls of South America ,is the Highest Waterfall in the World.
Antarctica is a frozen land area around the South Pole.It is also called Frozen Continent.

Print "*" in a pyramid format

Pyramid example
 package com.ram;

public class Pyramid {
 public static void main(String[] args) {
  System.out.println("Program to print a character '*' in the form of a pyramid");
  System.out.println("Assuming we need a pyramid of size 10");
  //In order to print the triangle, we have to split the triangle into two parts.
  //The first will have a for loop which will print spaces (" ")
  //The second will have another for loop which will print "* "
  for(int i=0; i<10; i++){
   for(int j=i; j<10; j++){
    System.out.print(" ");
   }
   
   for(int k=0; k<=i; k++){
    System.out.print("* ");
   }
   
   System.out.println();
  }
 }
}
 
 
Execute Pyramid class and you get the below output:

Login page using Spring & Hibernate

HashMap example

HashMap example
 package com.ram;

import java.util.HashMap;
import java.util.Iterator;

public class HashMapExample {
 public static void main(String[] args) {
  HashMap map = new HashMap();
  //Men's ATP rankings as of 2014
  map.put(1, "Nadal");
  map.put(2, "Djokovic");
  map.put(3, "Ferrer");
  map.put(4, "Murray");
  map.put(5, "Del Porto");
  map.put(6, "Federer");
  
  //Get the size of HashMap
  System.out.println("Size of of HashMap: "+map.size());
  
  //Returns value if key is present
  System.out.println(map.get(2));
  
  //Retrieve values from HashMap
  Iterator it = map.keySet().iterator();
  while(it.hasNext()){
   Integer key = it.next();
   System.out.println(map.get(key)+" rank is : "+key);
  }
  
  //Returns true if the value is present
  System.out.println(map.containsValue("Murray"));
  
  //Returns true if key is present
  System.out.println(map.containsKey(6));
  
  //Removes key and its corresponding value if the key is present
  System.out.println("Removed "+map.remove(3));
 
  //Removes all mappings from map
  map.clear();
 }
}

 
Execute HashMapExample class and you get the below output:
Size of of HashMap: 6
Djokovic
Nadal rank is : 1
Djokovic rank is : 2
Ferrer rank is : 3
Murray rank is : 4
Del Porto rank is : 5
Federer rank is : 6
true
true
Removed Ferrer

ArrayList example

ArrayList example
 package com.ram;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
 public static void main(String[] args) {
  //Create an ArrayList
  ArrayList<String> al = new ArrayList<String>();
  
  al.add("Coke");
  al.add("Pepsi");
  al.add("Sprite");
  al.add("Mountain Dew");
  al.add("Fanta");
  al.add("Red Bull");
  
  //Get the size of ArrayList
  System.out.println("Size of ArrayList: "+al.size());
  
  //Display elements of ArrayList
  System.out.println("ArrayList elements: "+al);
  
  //Retrieve an element using its index
  System.out.println(al.get(5));
  
  //Replace an element at the specified position in the list with the specified element
  al.set(0, "Coca-cola coke");
  System.out.println("ArrayList elements: "+al);
  
  //Inserts an element at the specified location.
  al.add(2, "ThumsUp");
  System.out.println("ArrayList elements: "+al);
  
  //Checks if the element "Fanta" is in the list. If present will return true else false.
  System.out.println(al.contains("Fanta"));
  
  System.out.println(al.remove("Fanta"));
  
  //Display ArrayList elements using iterator
  Iterator<String> it = al.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  
  //Removes all elements from the list
  al.clear();
  System.out.println("Size of ArrayList: "+al.size());
 }
}

 
Execute ArrayListExample class and you get the below output:
Size of ArrayList: 6
ArrayList elements: [Coke, Pepsi, Sprite, Mountain Dew, Fanta, Red Bull]
Red Bull
ArrayList elements: [Coca-cola coke, Pepsi, Sprite, Mountain Dew, Fanta, Red Bull]
ArrayList elements: [Coca-cola coke, Pepsi, ThumsUp, Sprite, Mountain Dew, Fanta, Red Bull]
true
true
Coca-cola coke
Pepsi
ThumsUp
Sprite
Mountain Dew
Red Bull
Size of ArrayList: 0

Dynamic binding example

Dynamic binding example
Dynamic binding: It is a case in java where compiler is unable to decide which method to call at compilation time. Only JVM decides which method is called at runtime. Below program is an example of "dynamic binding" or "late binding".
 package com.ram;

interface Area{
 public int area(int length);
}

class Square implements Area{

 @Override
 public int area(int length) {
  int squareArea = length * length;
  return squareArea;
 }
}

class Circle implements Area{

 @Override
 public int area(int length) {
  double circleArea = (22.0/7.0) * length * length;
  return (int)circleArea;
 }
}

public class CalculateArea {
 public static void main(String[] args){
  Area areaObj1 = new Square();
  Area areaObj2 = new Circle();
  
  System.out.println("Square area = "+areaObj1.area(10));
  System.out.println("Circle area = "+areaObj2.area(10));
 }
}
 
 
Execute CalculateArea class and you get the below output:
Square area = 100
Circle area = 314

Static binding example

Static binding example
Static binding: Static binding or early binding is a case where compiler can resolve the binding at the compile time only. All static methods are called or accessed using their respective class names and a compiler can resolve the binding at the compile time. Hence all static method calls are examples of static binding. Overloaded methods are bonded using static binding. Below program is an example of "static" binding.
 package com.ram;

class Addition{
 public void add(int a, int b){
  System.out.println(a + b);
 }
 
 public void add(String a, String b){
  System.out.println(a + b);
 }
}

public class StaticBindingExample {
 public static void main(String[] args) {
  Addition obj1 = new Addition();
  obj1.add("Ram", "Akunuru");
  obj1.add(1, 2);
 }
}

 
Execute StaticBindingExample class and you get the below output:
RamAkunuru
3

Method Overriding example

Method Overriding example
 package com.ram;

class Car{
 int CC;
 String name;
 
 public void display(){
  System.out.println("Will diaplsy car details ...");
 }
}

class BMW extends Car{
 public void display(){
  name="BMW X5";
  CC = 2979;
  System.out.println(name+" has "+CC+" CC");
 }
}

class Benz extends Car{
 public void display(){
  name = "Mercedes-Benz E class";
  CC = 3498;
  System.out.println(name+" has "+CC+" CC");
 }
}

public class OverrideExample {
 public static void main(String[] args) {
  Car bmw = new BMW();
  Car benz = new Benz();
  
  bmw.display();
  benz.display();
 }
}

 
Execute OverrideExample class and you get the below output:
BMW X5 has 2979 CC
Mercedes-Benz E class has 3498 CC

Method Overloading example

Method Overload example
 package com.ram;

class Sum{
 
 public int add(int x, int y){
  return (x + y);
 }
 
 public int add(int x, int y, int z){
  return (x + y + z);
 }
 
 public double add(int x, double y){
  return (x + y);
 }
}

public class OverloadExample {
 public static void main(String[] args) {
  Sum sum = new Sum();
  System.out.println(sum.add(10, 20));
  System.out.println(sum.add(10, 20, 30));
  System.out.println(sum.add(10, 10.50));
 }
}


 
Execute OverloadExample class and you get the below output:
30
60
20.5

Interface example

Interface example
 package com.ram;

interface Mother{
 int MOTHER_PROPERTY = 1000000;
}

interface Father{
 int FATHER_PROPERTY = 5000000;
}

class Child implements Mother,Father{
 int total_property = MOTHER_PROPERTY + FATHER_PROPERTY;
 
 public void display(){
  System.out.println("Totoal property of child is = "+total_property);
 }
}

public class InterfaceExample {
 public static void main(String[] args) {
  Child child = new Child();
  child.display();
 }
}


 
Execute InterfaceExample class and you get the below output:
Totoal property of child is = 6000000

Abstract class example

Abstract class example
 package com.ram;

abstract class Mobile{
 String name;
 String os;
 String model;
 
 public abstract void display();
}

class Samsung extends Mobile{

 @Override
 public void display() {
  name = "Samsung";
  os = "Android";
  model = "Galaxy SIII";
  System.out.println(name+" "+model+" uses "+os+" operating system");
 }
}

public class AbstractClassExample {
 public static void main(String[] args) {
  Mobile obj = new Samsung();
  obj.display();
 }
}

 
Execute AbstractClassExample class and you get the below output:
Samsung Galaxy SIII uses Android operating system

Java Programming

pass-by-value or pass-by-reference?

Question: Does java support pass-by-value or pass-by-reference?
Answer: Java is pass-by-value for all variables running with in a single virtual machine. So that means it takes a copy of the variable value and then that copied value will be passed. So java passes the copy of the bits representing the value. For example, we have declared two int variables a and b and we have assigned values 10 and 20 to them respectively. We now pass these variables as parameter to an add() method, which looks like add(a, b). Now what java does is, it takes a copy of these values and those copied values would be sent to the add method and not the original values or reference to those values. Whatever happens next in the add method will not effect the actual values in the variables.
The above explanation is regarding primitive data types. What if we have to pass objects as parameters? The answer is even the object references are passed by values only. That means java passes a copy of the bits representing the reference to an object. Here two references point to the same object. So, any change made by any of the reference will effect the other as well. For example, suppose we have ref1 as a reference to the object obj. And object obj has a variable a whose value is 15. Now we pass this reference ref1 as a parameter to a method. So java copies the bits of ref1 and then the copied value is sent. Let us name the copied reference as ref2. Now suppose ref2 changes the value of variable a in the object to 25. Then the value of variable a pointed by ref1 will also be 25. Because both ref1 and ref2 are pointing to the same object obj.

JDBC interview questions and answers

  1. What is JDBC?
    Answer: JDBC is an acronym for Java Data Base Connectivity. It is an API for communicating with relational data base (where data is stored in tables with rows and columns). A developer can make use of the API which has classes (java.sql.DriverManager, java.sql.Date etc) and interfaces (Connection, Driver, Statement, ResultSet), to persist the data.
  2. Explain the general procedure for establishing a connection with the data base.
    Answer:
    • Register the driver. Below piece of code is an example of registering oracle driver.
        Driver driver = new oracle.jdbc.driver.OracleDriver();
        DriverManager.registerDriver(driver);
        
    • Use DriverManager.getConnection method to establish the connection with the data base as shown in the below code.
       Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
       
  3. Connection is an interface. How can you create an object to Connection interface?
    Answer: We cannot directly create an object to Connection interface. When we execute Connection c = DriverManager.getConnection(); it internally executes the code that is provided by JDBC driver vendor. This code creates an object based on the class provided by the vendor that implements connection interface.
  4. What are the different types of statements in JDBC?
    Answer: JDBC API provides us with 3 different statements (interfaces) using which we can persist data after establishing the connection.
    • Statement: It is used to implement simple SQL statements with no parameters.
       Statement stmt = null;
       stmt = con.createStatement();
       

    • PreparedStatement: This is used for precompiling SQL statements that may or may not contain input parameters. A sample code of how to use PreparedStatement is given below.
       PreparedStatement pstmt = conn.prepareStatement("insert into sample values(?)");
        for(int i=0; i<10; i++){
         pstmt.setInt(1, i);
         pstmt.executeUpdate();
       
      To see the complete example for PreparedStatement ... "Click here"
    • CallableStatement: This is used to execute stored procedures (a stored procedure is a group of SQL statements that form a logical unit and perform a particular task) that may contain both input and output parameters.
       callStmt = conn.prepareCall("{call procx(?,?,?)}");
        // set input parameters
        callStmt.setInt(1,10);
        callStmt.setInt(2, 20);
      
        //register output types
        callStmt.registerOutParameter(3, Types.INTEGER);
        callStmt.execute();
       
      To see the complete example for CallableStatement ... "Click here"
  5. Explain about the different JDBC drivers.
    Answer: There are four types of drivers. They are:
    • Type I driver or JDBC-ODBC Bridge Driver
    • Type II driver or JDBC-Native API Driver
    • Type IV driver or Pure java Driver
    • Type III driver or JDBC-Net pure Java
    To learn more about each driver ... "Click here"
  6. Can we execute non select statement using execute query?
    Answer: Yes we can execute non select statement using execute query but it is not recommended. But at the end data base will be updated. Some drivers give exceptions like inetGate.jar
  7. What is ResultSet?
    Answer: ResultSet object is returned as a result of executing the executeQuery. ResultSet represents a set of rows. ResultSet is an interface.
     String query = "select employee_id, first_name from employees";
      ResultSet rs = stmt.executeQuery(query);
      
      while(rs.next()){
       System.out.print("Employee_Id = "+rs.getString(1));
       System.out.println("  First_Name = "+rs.getString("first_name"));
      }
     
    Have a look at the complete program by ... Clicking here
  8. What is ResultSetMetaData?
    Answer: ResultSetMetaData is used to give more information about the ResultSet objects like data type of the columns, name of the columns etc. For example ResultSetMetaDate example
  9. How can you improve the performance of an application?
    Answer: We can improve the performance of the application by choosing appropriate value for fetch size. "statement.setFetchSize()" sets the fetch size used by the jdbc driver.
    The default fetch size of oracle driver is "10". In some drivers like JdbcOdbc by Sun Micro Systems the default fetch size id "1" and we cannot increase the fetch size.
  10. How do we know the fetch size of the driver we are using?
    Answer: To know the fetch size, we can use the below statement.
     System.out.println(statement.getFetchSize());
     
  11. How do you commit your transactions?
    Answer: By default all the jdbc drivers will be running in "autocommit" mode. To find out whether the driver is running in autocommit mode or not we can use the below statement.
      System.out.println(connection.getAutoCommit());
      
    If you want to explicitly commit a transaction then use:
    connection.commit();
  12. How do you control transactions in JDBC?
    Answer: We can control the transactions in JDBC by setting the autoCommit to "false".
  13. What is connection pooling?
    Answer: Opening a connection to a database is a time-consuming process. For short queries, it can take much longer to open the connection than to perform the actual database retrieval. Consequently, it makes sense to reuse Connection objects in applications that connect repeatedly to the same database. A connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. It reduces the overhead for the application and increases performance.
  14. What is the use of Class.forName("SomeClass")?
    Answer: Class.forName("SomeClass") does the following things.
    • It loads the "SomeClass".
    • Returns an instance of SomeClass
    For example:
     Class.forName("oracle.jdbc.driver.OracleDriver");
     

Pure object oriented programming

Question: Is java pure object oriented programming?
Answer: This has been the topic of debate for long. Java is not pure object oriented programming. Examples of pure object oriented programming language are "Ruby", "SmallTalk" etc. Below are few reasons why java is not a pure object oriented programming.
  • Java has primitive data types like int, byte, float, double, char etc. Pure object oriented programming language should contain only classes and objects. It should not contain primitive data types. Now the question comes is why java has primitive data types? It is because primitive data types are faster than objects. Primitive data type "int" takes 4 bytes where as for Integer object just the reference to the Integer takes 32 bits.
  • Java has a static keyword i.e., static fields, static methods. These are associated with the class itself, not with any particular object created from the class. You can run a program without making a single object.
  • In pure object oriented language we should access everything by message passing in other words through objects. For example, write a simple addition of two numbers inside the main() method and display the output. You can run this program without creating object.

Immutable String

Question: Why is Sting class immutable?
Answer: String class is immutable. What this means is that String class is final, its state cannot be changes and String class cannot be sub classed. The reasons are listed below:
  • In java strings are used every where. For example, user names, passwords, data base URL, network connections etc. Suppose strings are mutable and if the string goes into wrong hands (hackers) then they can change the strings and hack any system and get access to critical data. So for security reasons String classes are made immutable.
  • As discussed in the previous question, immutable objects are thread safe and solves some synchronization issues.
  • Java designers have come up with a separate memory for string known as "String Pool". String pool is a special storage space in heap. To support string pool facility, strings are immutable. To know more about string pool, please read the answer to question 23 of ... Core Java interview questions and answers

Operator overloading

Question: Why java does not support operator overloading?
Answer: Operator overloading means to use the same operator for different data types. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. Below are the reasons why java does not support operator overloading.
  • Operator overloading can be exceedingly confusing. Keeping the human tendency in mind that some operators have specific meaning and if changed then programmers tend to make errors.
  • By not supporting operator overloading, the code would be simple and clear which was one of the primary goals of java designers. And the same thing can be achieved by method overloading.
  • Operator overloading also makes the task of JVM complex. What this means that JVM takes more time to execute programs.
The only overloaded operator in Java is the arithmetic "+" operator. When "+" is used with integers it adds them. When the same "+" is used with strings it concatenates them. This can be explained with a simple example as shown below.
 package com.ram;

public class OperatorOverloading {
 public static void main(String[] args) {
  int a = 10;
  int b = 20;
  int c;
  String firstName = "Ram";
  String lastName = "Akunuru";
  String name;
  
  c = a + b; //Here "+" is used to add two integers.
  System.out.println("c = "+c);
  
  name = firstName + lastName; //Here "+" is used to concatenate the strings
  System.out.println("Name = "+name);
 }
}
 
 
Output:
c = 30
Name = RamAkunuru

Immutable class

Question: How do you create an immutable class?
Answer: Immutable class or objects are those whose state(object's data) cannot be changed once they are created. For example String class is an immutable class. Now the question is how to create immutable objects. Below are the steps for creating immutable objects.
  • Make all the fields i.e, all the member variables and methods as final.
  • To further restrict the access we can use a private access modifier.
  • Now mark the class as final. If class is declared as final then no other class can extend it.
Below is an example for immutable class.
 package com.ram;

final class Immutable{
 private final int empId;
 private final String empName;
 
 Immutable(int empId, String empName){
  this.empId = empId;
  this.empName = empName;
 }

 public int getEmpId() {
  return empId;
 }

 public String getEmpName() {
  return empName;
 }
 
}

public class ImmutableClassExample {
 public static void main(String[] args) {
  Immutable imuObj = new Immutable(123456, "Ram");
  System.out.println("Employye Id = "+imuObj.getEmpId());
  System.out.println("Employee Name = "+imuObj.getEmpName());
 }
}
 
 
Now the a question arises. What is the use of immutable class?
  • Immutable classes are thread safe (it may be used from multiple threads at the same time without causing problems).
  • They do not have any synchronization issues.
  • Immutable objects do not copy constructors (A copy constructor is a Constructor that references to another object in the same class).
  • Immutable objects can be reused by caching them.

Deadly Diamond of Death problem

Question: What is "Deadly Diamond of Death" problem in Java?
Answer: Before I explain about "Deadly Diamond of Death" problem in java, we need to know about multiple inheritance. As we all know multiple inheritance refers to a feature in which a class can inherit behaviors and features from more than one superclass. Java does not allow multiple inheritance. Now the question arises why java does not support multiple inheritance? Let me explain this with an example. Consider the following program.
 package com.ram;

class A {
 public void display(){
  System.out.println("From class A ...");
 }
}

class B extends A{
 public void display(){
  System.out.println("From class B ...");
 }
}

class C extends A{
 public void display(){
  System.out.println("From class C ...");
 }
}

public class D extends B,C{
 //Which display() method would the class inherit, B or C?
}

 
In the above code, class A has a display() method. Now class A is extended by both classes B and C. Now suppose there is a class D which extended classes B and C. So which version of display() method would the class D inherit? In other words class D will inherit two different implementations of the same method. This issue is known as "Deadly Diamond of Death" because the shape of these four classes looks like a diamond. Below diagram explains it better.

Java interesting concepts