SimpleDateFormat

            String dateFormat = "dd/MM/yyyy";
	    Scanner scanner = new Scanner(System.in);
	    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
	    Date date =sdf.parse(scanner.nextLine());
	    System.out.println(sdf.format(date));

Sample Database Application

Structure

ConnectionUtil.java


package com.student.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionUtil {


	public static Connection getConnection()
	{
		Connection conn = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentDb", "root", "");


		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;

	}

	public static void closeConnection(Connection conn, PreparedStatement ps) {
		try {
			conn.close();
			ps.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

	public static void closeConnection(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			conn.close();
			ps.close();
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

Student.java


package com.student.dto;

public class Student {

	private long id;
	private String name;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Student(long id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public Student() {
		
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + "]";
	}

}

StudentDao.java


package com.student.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import com.student.dto.Student;
import com.student.util.ConnectionUtil;

public class StudentDao {

	//Insert new student.
	public void save(Student student)
	{
		Connection conn = null;
		PreparedStatement ps = null;
		conn = ConnectionUtil.getConnection();
		String query = "insert into studenttable (STUDENT_ID, STUDENT_NAME) values (?,?)";
		try {
			ps = conn.prepareStatement(query);
			ps.setLong(1,student.getId());
			ps.setString(2, student.getName());

			int rows = ps.executeUpdate();
			System.out.println("No.of records inserted:"+rows);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			ConnectionUtil.closeConnection(conn, ps);
		}
	}


	//Update student
	public void update(Student student)
	{
		Connection conn = null;
		PreparedStatement ps = null;
		conn = ConnectionUtil.getConnection();
		String query = "update studenttable set STUDENT_NAME =? where STUDENT_ID=?";
		try {
			ps = conn.prepareStatement(query);
			ps.setString(1, student.getName());
			ps.setLong(2,student.getId());
			int rows = ps.executeUpdate();
			if (rows>0)
				System.out.println("No.of records updated:"+rows);
			else
				System.out.println("Given id is not found in the database");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			ConnectionUtil.closeConnection(conn, ps);
		}


	}


	//View all Students
	public List<Student> findAll()
	{

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<Student> studentList = new ArrayList<Student>();
		conn = ConnectionUtil.getConnection();
		String query = "select * from studenttable";

		try {
			ps = conn.prepareStatement(query);
			rs = ps.executeQuery();
			while(rs.next())
			{
				Student student = new Student();
				student.setId(rs.getLong(1));
				student.setName(rs.getString(2));
				studentList.add(student);
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			ConnectionUtil.closeConnection(conn, ps,rs);
		}
		return studentList;
	}


	//Searching student by id
	public Student findOne(long id)
	{
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Student student = new Student();

		String query = "select student_name from studenttable where STUDENT_ID=?";

		try {
			conn = ConnectionUtil.getConnection();
			ps = conn.prepareStatement(query);
			ps.setLong(1, id);
			rs = ps.executeQuery();

			if(rs.next())
			{
				student.setId(id);
				student.setName(rs.getString(1));
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			ConnectionUtil.closeConnection(conn, ps,rs);
		}

		return student;
	}


	//Delete Student
	public void delete(long id)
	{
		Connection conn = null;
		PreparedStatement ps = null;

		String query = "delete from studenttable where STUDENT_ID=?";

		try {
			conn = ConnectionUtil.getConnection();
			ps = conn.prepareStatement(query);
			ps.setLong(1, id);
			int rows = ps.executeUpdate();
			if(rows>0)
				System.out.println("Record deleted");
			else
				System.out.println("Given id is not found in the database");

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			ConnectionUtil.closeConnection(conn, ps);
		}
	}
}

TestStudent.java


package com.student.test;

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

import com.student.dao.StudentDao;
import com.student.dto.Student;

public class TestStudent {

	public static void main(String[] args) {


		//Uncomment the below method to test		
		//insertStudent();

		//findAllStudent();

		//findOneStudent();

		//updateStudent();

		deleteStudent();

	}

	private static void deleteStudent() {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the id number");
		long id = input.nextLong();
		StudentDao studentDao = new StudentDao();
		studentDao.delete(id);

	}

	private static void updateStudent() {
		//Student Object Creation
		Student student = new Student();

		//Initializing values by setter method
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the id number");
		long id = Long.parseLong(input.nextLine());
		student.setId(id);
		System.out.println("Enter new name to update");
		String name = input.nextLine();
		student.setName(name);

		//Create Dao object
		StudentDao studentDao = new StudentDao();
		studentDao.update(student);

	}

	private static void findOneStudent() {

		System.out.println("Enter the Student id for retrive:");
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		long id = input.nextLong();
		StudentDao studentDao = new StudentDao();
		Student student = studentDao.findOne(id);
		System.out.println(student);


	}

	private static void findAllStudent() {

		StudentDao studentDao = new StudentDao();
		ArrayList<Student> studentList = new ArrayList<Student>();
		studentList = (ArrayList<Student>)studentDao.findAll();

		Iterator<Student> studentIterator = studentList.listIterator();
		while(studentIterator.hasNext())
		{
			Student student = studentIterator.next();
			System.out.println(student);
		}

	}

	public static void insertStudent() {
		//Student Object Creation
		Student student = new Student();

		//Initializing values by setter method
		student.setId(102);
		student.setName("KARTHI");

		//Create Dao object
		StudentDao studentDao = new StudentDao();
		studentDao.save(student);

	}

} 

Difference between Comparable and Comparator

Comparable Comparator
1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
2) Comparable affects the original class i.e. actual class is modified. Comparator doesn’t affect the original class i.e. actual class is not modified.
3) Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.
4) Comparable is found in java.lang package. Comparator is found in java.util package.
5) We can sort the list elements of Comparable type byCollections.sort(List) method. We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.

Difference between overloading & overriding

Property

Overloading

Overriding

Method names Must be same Must be same
Arguments Must be different (at least order) Must be same (including order)
Method Signatures Must be different Must be same
Return types No restriction Co variant return types are allowed
Private, static & final methods Can be overloaded Cannot be overridden
Access modifiers No restriction We can’t reduce the scope of the access modifier, but we can increase
Throws clause No restriction If the child class throws any checked exception, then it is compulsory, the  parent class method  should throw the same checked exception.
Method Resolution Always takes care compiler based on the reference type Always takes care by JVM based on runtime object.
Also known as Compile time polymorphism or static polymorphism or early binding Runtime polymorphism, dynamic polymorphism or late binding

Adding values in ArrayList

import java.util.ArrayList;
import java.util.List;

public class TestArrayList{

	public static void main(String[] args) {
		String name1 = "Rajan";
		String name2 = "karthik";
		String name3 = "Vimal";
                //Declaration and Construction of Array List 
		List<String> nameList = new ArrayList<String>();
                //Adding String Object in Array List
		nameList.add(name1);
		nameList.add(name2);
		nameList.add(name3);

		System.out.println("Names in the list are");
                
		for(String name:nameList)
		{
			System.out.println(name);
		}

	}
}

User Defined Exception

public class StringEmptyException extends Exception{
	private static final long serialVersionUID = 1L;

	public StringEmptyException(String errorMessage) {
		super(errorMessage);
		/* Uncomment the following code and test this program with e.getMessage()
		System.out.println("Given String is Empty");*/
		
	}
}


import java.util.Scanner;

public class TestException {

	public static void main(String[] args) {
		String name;
		@SuppressWarnings("resource")
		Scanner input = new Scanner(System.in);
		name= input.nextLine();
		try {
			if(name.equals(""))
			{
				throw new StringEmptyException("Empty String");
			}else
			{
				System.out.println("Given String is: "+name);
			}
		}catch (StringEmptyException e) {
			
			e.printStackTrace();
			
			//e.getMessage();
		}	
	}

}

Check Validate User

class UserDAO {
     
    public static String[]  getUsers() {
        String [] usernames = new String[] { "sridhar", "senthil", "siva" , "kamal" };
        return usernames;
    }
     
    public static boolean isValidUser(String username) {
         
        String[] users = getUsers();
        boolean isValid = false;
        for (String name : users) {
             
            if ( name.equals(username )) {
                isValid = true;
                break;
            }
        }
         
        return isValid;
         
    }
}
 
 
public class TestLogin {
 
    public static void main(String[] args) {
         
        //success case
        String username1 = "sridhar";
        System.out.println(  username1 + " is a Valid User ? " +  UserDAO.isValidUser(username1));
         
        //failure case
        String username2 = "abc";
        System.out.println(  username2 + " is a Valid User ? " +  UserDAO.isValidUser(username2));
         
    }
}

Sort an ArrayList Element

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class SortCollection {
 
	public static void main(String... args)
	{
 
		List<String> li = new ArrayList<String>();

		li.add("India");
		li.add("United States");
		li.add("Malaysia");
		li.add("Australia");
		li.add("Lundon");

		Collections.sort(li);
		System.out.println("Countries are: ");
		for(String temp: li)
		{
			System.out.println(temp);
		}
		
	}
}

Sorting an array element

import java.util.Arrays;
public class SortArray {
 
    public static void main(String... args)
    {
            String[] states = {"Tamilnadu","Andra pradesh","Karnataka","Kerala","Delhi"};
 
            Arrays.sort(states); // States array values will be sorted here
 
            for(int i=0;i<states.length;i++)
            {
                System.out.println("States : "+states[i]);
            }
    }
}