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