Java Interview Questions - 3



Java Interview Questions



1. Which is the base class for all classes in java?

Object class.


2. What are methods in object class in java?

clone() - Creates and returns a copy of this object.

equals(Object obj) - Indicates whether some other object is "equal to" this one.

finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

getClass() - Returns the run-time class of an object.

hashCode() - Returns a hash code value for the object.

notify() - Wakes up a single thread that is waiting on this object's monitor.

notifyAll() - Wakes up all threads that are waiting on this object's monitor.

toString() - Returns a string representation of the object.

wait() - Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

wait(long timeout) - Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

wait(long timeout, int nanosec) - Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.


3. Program to remove any given character from a String?


public class RemoveChar {
 
 public static void main(String[] args) {
  String line = "A simple implementation of Bindings backed";
  char chr = 'i';
  String finalStr = new RemoveChar().removecharater(line, chr);
  
  System.out.println("INPUT:  "+line);
  System.out.println("CHAR TO REMOVE: "+chr);
  System.out.println("\nOUTPUT: "+finalStr);
 }
 
 public String removecharater(String line, char chr){
  char[] charArr = line.toCharArray();
  StringBuilder strBuilder = new StringBuilder();
  
  for (char c : charArr) {
   if(c != chr){
    strBuilder.append(c);
   }   
  }  
  return strBuilder.toString();
 }
}


OUTPUT:


INPUT:  A simple implementation of Bindings backed
CHAR TO REMOVE: i

OUTPUT: A smple mplementaton of Bndngs backed




4. Find no. of occurances of each character in a given string?


public class CharOccurance {

 public static void main(String[] args) {
  String line = "implementation";
  
  HashMap<Character, Integer> charCounts = getCharCounts(line);
  
  System.out.println("INPUT:  "+line);
  System.out.println("RESULT: "+charCounts);  
 } 
 
 public static HashMap<Character, Integer> getCharCounts(String line){
  HashMap<Character, Integer> charCounts = new HashMap<Character, Integer>();
  char[] chr = line.toCharArray();
  for (char c : chr) {
   if(charCounts.containsKey(c)){
    int cnt = charCounts.get(c);
    charCounts.put(c, cnt+1);
   }else{
    charCounts.put(c, 1);
   }
  }  
  return charCounts;
 } 
}

OUTPUT:


INPUT:  implementation
RESULT: {t=2, e=2, a=1, p=1, n=2, o=1, l=1, m=2, i=2}


5. Find second highest number in an integer array?


public class SecondHighest {

 public static void main(String[] args) {
  int[] values = {8,4,1,3,7,6,5,2,9};
  
  // Sorting array into TreeSet
  Set<Integer> tree = new TreeSet<Integer>();
  for (int i : values) {
   tree.add(i);
  }
  
  // Copy TreeSet values into ArrayList
  List<Integer> list = new ArrayList<Integer>();
  list.addAll(tree);
  
  // Print last 2nd value for 2nd Hignest value
  System.out.println("SECOND HIGHEST : "+list.get( list.size()-2 ));  
 }  
}

OUTPUT:


SECOND HIGHEST : 8


6. How to read/write/append/delete a file?

Please refer to the earlier post for complete all file operations. - http://javadiscover.blogspot.com/2013/03/how-to-create-writeappend-read-delete.html 


7. What are the ways we can create threads in java?

By 2 ways we can create thread 
a. Extending Thread class
b. Implementing Runnable interface 


8. How to create a Thread using extending a Thread class?



public class MyThread extends Thread{
 
 @Override
 public void run() {
  int i=0;
  while(i<5){
   System.out.println(Thread.currentThread().getName());
   i++;
  }
 }
 
 public static void main(String[] args) {
  MyThread t1 = new MyThread();
  MyThread t2 = new MyThread();
  t1.start();
  t2.start();
 }
}


OUTPUT:


Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0




9. How to create a Thread using implemeting Runnable interface ?


public class MyThread implements Runnable{
 
 public void run() {
  int i=0;
  while(i<5){
   System.out.println(Thread.currentThread().getName());
   i++;
  }
 }
 
 public static void main(String[] args) {
  MyThread obj = new MyThread();
  Thread t1 = new Thread(obj);
  Thread t2 = new Thread(obj);
  t1.start();
  t2.start();
 }
}

OUTPUT:


Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1


10. What are different types of cloning in Java?

There are 2 types of cloning in Java, Deep and shallow cloning (Copy). By default shallow copy is used in Java. As we seen in 2nd question by Object class clone() will do this operation by default. 







Simple login page using JSP

Today we will see about creating simple login page using JSP. For this tutorial we have used 
  • Eclipse
  • Apache Tomcat (Web Server)
  • Postgres Database

In this example lets start with simple JSP page which will have username and password field with login button. Also wwe have used javascript to validate text fields. In back-end we have created database connection and validating the username and password are valid or not. If its valid then we are returning true else false to the JSP page.

In JSP page if the returned value is true then we are redirecting to success.jsp else displaying error message in same page.

We have done very basic login page which will be understandable for beginners. There are lot and lot of tools and frameworks which we can use and make our web pages more powerful and rich in UI. But we have this taken simple way to start with login page.

To Be Ready with:

i. JDK 1.5 and above should be installed in the machine

ii. Download Eclipse J2EE version according to your machine and OS and install - http://www.eclipse.org/downloads/ 

iii. Download Apache Tomcat web server and install - http://tomcat.apache.org/download-60.cgi

iv. Download and install Postgres database or any other database according to your choice - http://www.postgresql.org/download/

v. Download necessary database driver jar files. In case of Postgres we need to download postgres SQL JDBC driver - http://jdbc.postgresql.org/download.html


Step - 1: Create Dynamic web project in Eclipse

File -> New -> Dynamic Web Project



Step - 2: Add database driver in project Libraries 
Right click Project -> Properties -> Java Build Path -> Libraries -> Add External JARs




Step - 3: Create simple login.jsp 


<%@page import="com.javadiscover.login.LoginValidate"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Please Login....</title>

<script type="text/javascript">
    function validate_required(field, alerttxt) {
        with (field) {
            if (value == null || value == "") {
                alert(alerttxt);
                return false;
            }
            else {
                return true;
            }
        }
    }

    function validate_Loginform(thisform) {
        with (thisform) {
            if (validate_required(username, "Please enter the username") == false)
            {
                username.focus();
                return false;
            }

            if (validate_required(password, "Please enter the password") == false)
            {
                password.focus();
                return false;
            }
            return true;
        }
    }
</script>
</head>
<body>


<%
 String msg = "";
 String uname = request.getParameter("username");
 String password = request.getParameter("password");
 if(uname != null && password != null && uname.length() > 0 && password.length() > 0){
  LoginValidate obj = new LoginValidate();
  boolean flag = obj.validateUserLogin(uname, password);
  if(flag){
   request.getRequestDispatcher("success.jsp").forward(request, response);
  }else{
   msg = "Invalid username or password";
  }
 }
%>

 <form action="login.jsp" method="post" onsubmit="return validate_Loginform(this)">
  <table width="40%" border="1" align="center">
   <tr>
    <th colspan="2" align="center" valign="top">Please enter login details</th>
   </tr>
   <tr height="50">
    <td valign="middle" align="right">User Name</td>
    <td align="left"><input name="username" size="20" value=""  type="text">
    </td>
   </tr>
   <tr>
    <td valign="middle" align="right">Password</td>
    <td align="left"><input name="password" size="20" value=""  type="password">
    </td>
   </tr>
   <tr height="40">
    <td colspan="2" align="center"><input value="Login" name="B1" type="submit"></td>
   </tr>
  </table>
  
  <br>
  <br>
  <br>
  <br>
  
  <p align="center"> <b><font color="darkred"><%=msg %></font></b></p>

 </form>
</body>
</html>



Step - 4: Create LoginValidate.java page
package com.javadiscover.login;

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

/**
 * @author Java Discover
 */
public class LoginValidate {
 
 public boolean validateUserLogin(String uname, String pwd){
  boolean flag = false;
  Connection con = null;
  try{
   con = createConnection();
   if(con != null){
    Statement stat = con.createStatement();
    String qry = "SELECT * FROM tbl_login_master WHERE uname = '"+uname+"' AND password = '"+pwd+"' ";
    ResultSet rs = stat.executeQuery(qry);
    if(rs.next()){
     flag = true;
    }
   }
  }catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(con != null){
    try {
     con.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
  return flag;
 }
 
 public Connection createConnection() {
  System.out.println("Createung postgres DataBase Connection");
  Connection connection = null;

  try {
   
   // Provide database Driver according to your database
   Class.forName("org.postgresql.Driver");
   
   // Provide URL, database and credentials according to your database 
   connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydatabase", "javadiscover","postgres");

  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
  if(connection != null){
   System.out.println("Connection created successfully....");
  }
  return connection;
 }
}




Step - 5: Create success.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
 String uname = request.getParameter("username");
%>
 <h1>Hi <%=uname%>, Successfully Logged in.....</h1>
</body>
</html>



Step - 6: Make sure database and table present in your database

As per above code Database : mydatabase
Table : tbl_login_master
Credentials:
Username: javadiscover
Password: postgres



Step - 7: Start server and test your application by login.jsp page



Project Explorer:



Login Page:



Success Login Page:




Failure Login Page:





Java Interview Questions - 2


Java Interview Questions

In our earlier tutorial we have discussed about few Java interview programming questions. In this tutorial we will discuss on more interview questions.


1. How to run program without main() method?

    By using static block as given below.


    public class MyTestClass {
   
        static{
            System.out.println("Hi, I'm in static block");
        }   
    }



2. Can we call constructor from another constructor?
   
    Yes, we can call by using "this" keyword as given below.

    public class MyTestClass {
   
    public MyTestClass() {       
        this(10);       
    }   
   
    MyTestClass(int i){
        System.out.println("Value : "+i);
    }
   
    public static void main(String[] args) {
        new MyTestClass();
    }   
}



3. What will be the size of HashMap if we place twice same Object in key?

    public static void main(String[] args) {
        MyTestClass obj = new MyTestClass();
        Map<MyTestClass, String> map = new HashMap<MyTestClass, String>();
        map.put(obj, "first");
        map.put(obj, "second");
        System.out.println("Size : "+map.size());       
    }   


   SIZE: 1


4. What will be the size of HashMap if we place 2 Objects of same class in key?
  
    public static void main(String[] args) {
        

        MyTestClass obj = new MyTestClass();
        MyTestClass obj1 = new MyTestClass();
        Map<MyTestClass, String> map = new HashMap<MyTestClass, String>();
        map.put(obj, "first");
        map.put(obj1, "second");
       

        System.out.println("Size : "+map.size());      
    }

  
    SIZE: 2


 5. How to call parametrized method using java reflection?

    Please refer to Java Reflection post for set of reflection related questions and answers.

6. Can we have try block without catch block?
  
    Yes, we can but finally block should be there. Below are the combination of valid and invalid blocks in exception handling.
  
    VALID:
  
    try{
        ....
    }catch(Exception ex){
        ....
    }
    
    try{
        ....
    }finally{
        ....
    }
    
    try{
        ....
    }catch(Exception ex){
        ....
    }finally{
        ....
    }
    
    try{
        ....

    }catch(Exception ex){
        ....
    }catch(Exception ex){
        ....
    }finally{
        ....
    }


    INVALID:
  
    try{
        ....
    }




7. What will be the output of this code?
   
    public class MyTestClass {

        public static void main(String[] args) {
            System.out.println(new MyTestClass().myMethod());
        }
        
        public int myMethod(){
            try{
                int tmp = 5/0;
                return 5;
            }catch (Exception e) {
                return 6;            
            }finally{
                return 10;
            }
        }
    }


    OUTPUT: 10

    method myMethod() will return 10 irrelevant to try or catch blocks. Finally block will be executed always and will return 10.



8. Can we able to override static or private method?

    No, we can not override static or private methods.

9. Will this piece of code work or throws exception?
   
    It will give "null" output, it won't throw any exception.

    public static void main(String[] args) {
      

        HashMap hm = new HashMap();
        hm.put(null,null);
       

        System.out.println(hm.get(null));
    }


    OUTPUT: null
 

10. What is a transient variable?

    If we say in one line, Transient variables will not be serialized.
    For example when we serialize any Object if we need to serialize only few variables and rest should not be serialized then we can use transient keyword to avoid serialization on those variables.

11. Default value assigned to Boolean variable?

    false.

12. Abstract class can be final ?

    No, Class cannot be both final and abstract.

13. Abstract class should have abstract methods?

    No, its not compulsory to have abstract methods. But if there are any abstract method then class must be abstract.

14. Abstract class can have variables?

    Yes can have.

15. Interface can have method definition?

    No, interface can have only method declaration.

16. Interface can have variables?

    Yes, by default it will be static.

17. Interface can be abstract?

    Yes, but we can't have any method definitions.
      

18. How this and super keywords are used?

    this is used to refer to the current object instance and variables.
    super is used to refer to the variables and methods of the superclass of the current object instance.


19. How to Synchronize List, Map and Set?

    By using Collections util class we can Synchronize as given below,

    List<String> list = new ArrayList<String>();
     Set<String> set = new HashSet<String>();
     Map<String, String> map = new HashMap<String, String>();
   
     list = Collections.synchronizedList(list);
     set = Collections.synchronizedSet(set);
     map = Collections.synchronizedMap(map);


20. Why java is not a 100% OOP's?

    Since we have primitive data-types (int, float, double) than complete Objects. Hence we can say it as not 100% OOP's.