Java Interview Questions - 5

Java Interview Questions

In our past post we have seen lot of Java interview question like programming. In this post lets see few multiple choice questions in Java. Lets get some basic knowledge on various topics in Java 


1. Enumeration doesn't have which of the following method?

a) Hasnext()
b) Next()
c) Both a & b
d) Remove()


2. The servlet handles zero or more client’s requests through which method?

a) Init()
b) Destroy()
c) Paint()
d) Service()


3. Which is an Interface that extends Serializable Interface?
 
a) Package
b) Classes
c) Externalizable
d) Abstract

  
4. Which of the following is a software component that has been designed to be reusable in a variety of different environments?
 
a) Jar file
b) Java bean
c) JVM
d) JDK


5. Which of the following is the software component that enables java application to interact with the database?
 
a) ODBC
b) API
c) JDK
d) JDBC


6. Who control the java collector?
 
a) Class
b) Java interface
c) Applets
d) JVM


7. Which allows null key and values?
 
a) Hashtables
b) Hashkeys
c) Hash set
d) Hash map

 
8. Which of the following is the JDBC driver?
 
a) AWT driver
b) Network protocol driver
c) JVM driver
d) JAR driver


9. Which method returns -1 when it has reached the end of a file?
 
a) Write()
b) Read()
c) Lock()
d) All the above


10. Which class of interface is used, where there is a collection with no duplicates and you don’t care about order when you iterate through it?
 
a) Tree set
b) Enum set
c) Hashset
d) Linked hashset


11. Which concept of object oriented programming helps you group features of an object?
 
a) Packages
b) Inheritance
c) Data abstraction
d) Expert system


12. Write down the syntax to set null layout?

a) SetLayout(null)
b) Layout(null)
c) Layout(set null)
d) Null layout


13. What is the base class of all the classes?
 
a) Java.lang
b) Java.object
c) Java.lang.object
d) Java.lang.class



Public class test {
static class innerclass { 
Public static void innermethod() {
System.out.ptintln("static inner class!";


Public static void main(string args[]) { 
Test.innerclass.innermethod(); 


14. What will be the output of the above program?
 
a) Static inner class
b) 16
c) 14
d) None of the above


15. The <an applet> tag enables to pass an applet parameter in an applet using which of the following tag?
 
a) Alt
b) Code
c) Align
d) Param

 
16. Which frees the memory occupies by the unreachable objects during the java program by deleting these unreachable objects?
 
a) Interface
b) JVM
c) Source code
d) Garbage collector


17. Which of the following modifier makes that the programmer cannot change the value anymore?
 
a) Protected
b) Private
c) Public
d) Final

 
18. Which of the following is the correct syntax to create static variable?
 
a) Type static <var>
b) Static <identifier> type
c) Static[] type <identifier>
d) Static type <identifier>

  
19. Which is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource?
 
a) String ()
b) Finalize()
c) Math()
d) Final()


20. Which of the following code shows how to call the garbage collector?
 
a) Get.gc()
b) Garbage collector()
c) Runtime.gc()
d) System.gc()


21. Which encapsulates the state changes in the event source?
 
a) Event source
b) Event object
c) Event listener
d) Event management


22. Which is the default layout of jpanel?
 
a) Text layout
b) Label layout
c) Frame layout
d) Flow layout


23. Which is the relationship between the two classes?
 
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Association


24. Which is Set implementation to use with enum types?
 
a) Util.java.enum
b) Java.util.enumset
c) Enumset.util
d) Java.enum


25. Which method can be accessed by the classes within the same package or by the sub-classes of the class in any package?
 
a) Public
b) Protected
c) Private
d) Void


26. Which of the following view lets you navigate through the various files that make up an Eclipse project?
 
a) Problem view
b) Explorer view
c) Debug view
d) Java view


27. Which of the following is the king of bugs of java program?
 
a) Incorrect result
b) Program crashes
c) Both a & b
d) None of the above


28. Which of the following option Skips the highlighted statement and executes the next statement, and then suspends the thread?
 
a) Run to return
b) Step into
c) Step over
d) Resume

 
29. Which of the following element specified the element that can occur 1 or more times?
 
a) Element *
b) Element -
c) Element +
d) Element ?


30. Which is a control that the user can click to either check or uncheck?
 
a) Radio button
b) Check box
c) Drop down List
d) All the above



31. After you compile a Java program with no errors, you can run it by choosing which key combination?
 
a) Ctrl+f2
b) Ctrl+8
c) Ctrl+4
d) Ctrl+2


32. In Java, a _______ is a unit of code that can calculate and return a value?
 
a) Identifier
b) Method
c) Variable
d) Data



33. Which of the java compiler option specifies where to find input source files?
 
a) -d <directory>
b) -extdirs <dirs>
c) -classpath <path>
d) -sourcepath <path>

  
34. Which command is called the Java dis-assembler because it takes apart class files and tells you what’s inside them?
 
a) Javac
b) Java
c) Javap
d) Javah

  
35. Which is a name and value pair that’s written inside of the start tag for an element?
 
a) DTD
b) Script
c) Code
d) Attribute


36. Which is a read-only technique for processing XML that lets you read the elements of an XML document from a file and react to them as they come?
 
a) SAX
b) DOM
c) XML
d) HTML


37. _______spells out exactly what elements can appear in an XML document and in what order the elements can appear?
 
a) DOM
b) SAX
c) Validate form
d) DTD

  
38. Which of the following java command option displays the JRE version number, then stops?
 
a) -version
b) –verbose
c) –showversion
d) –server

 
39. Which of the following operator is used to compile all the files in a folder of java programs?
 
a) $
b) *
c) @
d) &


40. Which of the following performs calculations?
 
a) Expression statement
b) Variables
c) Keywords
d) Declaration statement



41. Which is a line in your program where you want the program to be suspended?
 
a) Breakpoint
b) Trace
c) Stepping
d) Debug



42. Which of the following is based on interfaces rather than classes?
 
a) XML
b) Javascript
c) ASP
d) DOM API


43. Which is the basic Eclipse desktop environment?
 
a) editor
b) workbench
c) applets
d) javadoc



44. The text editor you wish to create the text files that contain your Java programs is called ______?
 
a) Source file
b) Destination file
c) Application file
d) System file


45. What is the size of offline version of java?
 
a) 100 gb
b) 45 mb
c) 90 mb
d) 150 mb

 
46. In text pad which is a collection of files that you work on together?
 
a) Preference
b) Javadoc
c) Applets
d) Workspace


47. Which method of the slider control sets the tool-tip text that’s displayed if the user rests the mouse over the slider for a few moments?
 
a) void setPaintLabels
b) void setToolTipText
c) setOrientation
d) void setMinimum()


48. Which document format that can be understood by most word processing programs?
 
a) JRE
b) RTF
c) Bin
d) Demo

  
49. Which is a group of one or more statements that’s enclosed in braces?
 
a) White space
b) Variable
c) Keyword
d) Blocks


50. When debugging is executing program statements one at a time is called _____?
 
a) Threads
b) Program crashes
c) Bugs
d) Stepping


Useful MySQL commands and queries

Viewing from dev.mysql.com site

We all know that MySQL database is widely used open source database. So lets see few simple examples like how to start and stop MySQL service, creating database and few simple query for create, select, update, delete and alter tables. First lets see how to start and stop MySQL server along with few other commands in Unix machines. 


START MYSQL:
# /etc/init.d/mysqld start


STOP MYSQL:
# /etc/init.d/mysqld stop


CHECK MYSQL STATUS:
# /etc/init.d/mysqld status


RESTART MYSQL:
# /etc/init.d/mysqld restart


Login to MySQL database:
# mysql -u root -p <ENTER>
Enter password: <ENTER ROOT PASSWORD>
mysql>


LIST AVAILABLE DATABASES:
mysql>show databases;


CHANGE ROOT USER PASSWORD:
mysql> use mysql;
Database changed
mysql> update user set password=PASSWORD("mypassword") where User='root';
mysql> flush privileges;

NOTE: Once we change password need to flush privileges or need to restart MySQL database.


CREATE DATABASE:
mysql> create database <DATABASE_NAME>;


DROP DATABASE:
drop database <DATABASE_NAME>;


SELECT DATABASE:
mysql> use <DATABASE_NAME>;
Database changed
mysql> 


LIST AVAILABLE TABLES:
mysql>show tables;


SHOW TABLE STRUCTURE:
mysql> desc <TABLE_NAME>;


CREATE TABLE (showing sample tables):
CREATE TABLE tbl_master (
        user_id int not null primary key AUTO_INCREMENT,
user_name varchar(100) not null                
);

CREATE TABLE tbl_details (
id int not null primary key AUTO_INCREMENT,
user_id int not null,
project_name varchar(100) not null,
project_start datetime,
project_end datetime,
FOREIGN KEY (user_id) REFERENCES tbl_user_master(user_id)
);  


INSERT QUERY:
INSERT INTO tbl_master (user_name) VALUES("Rex");
INSERT INTO tbl_details (user_id, designation, date_of_birth) VALUES(1, "APAC-Mono", "2012-10-25", "2013-01-30");


SELECT QUERY:
SELECT * FROM tbl_master;
SELECT user_name, project_name, project_start, project_end FROM tbl_details as D, tbl_master as M WHERE D.user_id = M.user_id;   


UPDATE QUERY:
UPDATE tbl_details SET project_name = "APAC-Teli" WHERE project_name = "APAC-Mono";


ALTER QUERY:
ALTER TABLE tbl_master DROP PRIMARY KEY, ADD PRIMARY KEY(user_id, user_name);
ALTER TABLE tbl_master MODIFY user_name VARCHAR(150);
ALTER TABLE tbl_master DROP COLUMN user_name;
ALTER TABLE tbl_master ADD COLUMN user_name VARCHAR(150);


DELETE TABLE:
DELETE TABLE tbl_details WHERE user_id = 1;
DELETE TABLE tbl_details;


TRUNCATE TABLE:
TRUNCATE tbl_details;


DROP TABLE:
DROP TABLE tbl_details;


IdentityHashMap in Java

IdentityHashMap in java

IdentityHashMap implements Map interface as same as HashMap class. This class has been added from Java 1.4 and used very minimal across the programmers. Basically IdentityHashMap holds special implementation of Map interface which won't override equals() and hashcode() methods for object comparison. Instead it uses "==" operator to compare each objects of key and value. 
So lets see the difference between HashMap and IdentityHashMap in Java,

  • HashMap overrides equals() and hashcode() methods to compare objects, where as IdentityHashMap used only "==" operator to compare key and value. IdentityHashMap wont use object.hashCode() but uses System.identityHashCode(object) because we can use IdentityHashMap for mutable objects for whose hash code changes during the "in map" time frame.
  • For example when we use HashMap the object values can be directly changed which leads to strange behavior while IdentityHashMap works fine.
  • Next for using large maps which uses equals() and hashcode() will lead to expensive and in those cases we can switch to IdentityHashMap because both methods are not overridden in this class. Important using IdentityHashMap also specific to application. 

These are major difference between HashMap and IdentityHashMap in Java. Now lets see simple example with both HashMap and IdentityHashMap implementation classes.


import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class IdentityHashMapTest {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  Map<String, String> ihm = new IdentityHashMap<String, String>();
  
  hm.put("java", "111");
  hm.put(new String("java"), "222");
  hm.put("java", "333");
  
  ihm.put("java", "111");
  ihm.put(new String("java"), "222");
  ihm.put("java", "333");
  
  System.out.println("HashMap Size         : "+hm.size());
  System.out.println("IdentityHashMap Size : "+ihm.size());
  
  System.out.println("HashMap Values         : "+hm);
  System.out.println("IdentityHashMap Values : "+ihm);
 }
}


OUTPUT:


HashMap Size         : 1
IdentityHashMap Size : 2
HashMap Values         : {java=333}
IdentityHashMap Values : {java=333, java=222}


In above example if we see the size of both HashMap and IdentityHashMap is 1 and 2. Since HashMap overrides equals() and hashcode() methods it will compare object level of key and replaces for 1st 2 key and value which are trying to put in HashMap and remains only 1 key in Map.
Next when we see IdentityHashMap the size is 2, because "java" and new String("java") are considered as 2 different Objects. So it holds 2nd and 3rd value in Map.  




String replace in java

string replace in java

We all know that String class is a immutable and values once stored will not be changed. So what is String replace and how its working in java? basically whenever we change are replace the value in String new String Object will be created.
And also have to know that every-time it won't create String Object, only when string change happen in string value then it will create new String Object otherwise it will return same String Object. Totally there are 4 types of replace methods are there in Java,

public String replace(char oldChar, char newChar)
- Used to replace matching character in a String and returns the new String Object. 

public String replace(CharSequence target, CharSequence replacement)
- Used to replace set of character sequence in a String and returns the new String Object.  

public String replaceAll(String regex, String replacement)
- Used to replace all matching pattern in String using regular expression or either simple string and returns the new String Object.  

public String replaceFirst(String regex, String replacement)
- This method is simplar to above method but only used to replace first matching pattern in String using regular expression or either simple string and returns the new String Object.

Important:

  • As we seen above if there is not actual replace then these all methods will return same String Object instead of new String Object.
  • All these methods are Case Sensitive and will replace only with matching case characters.

First lets see simple example for calling replace method and there's no actual replace, so we need to get same String Object.



public class StringReplaceTest {

 public static void main(String[] args) {
  
  String source = "Hello Java";
  
  String str2 = source.replace("hi", "hello");
  
  //By using == operator we can test is it same Object
  if(source == str2){
   System.out.println("First Compare - Both are same String Object");
  }else{
   System.out.println("First Compare - Both are NOT same String Object");
  }
  
  /************************************************/
  
  String str3 = source.replace("Hello", "Hello");
  
  //By using == operator we can test is it same Object
  if(source == str3){
   System.out.println("Second Compare - Both are same String Object");
  }else{
   System.out.println("Second Compare - Both are NOT same String Object");
  }
 }
}


OUTPUT:


First Compare - Both are same String Object
Second Compare - Both are NOT same String Object



In above example we are trying to replace string "hi" with string"hello" where "hi" is not present in source string. So replace method will return same String Object instead of new String in first compare. 
In second replace we trying to replace "Hello" with same same string "Hello" where "Hello" present in source string. So replace method will return new String Object. 


Now lets see simple examples for all 4 replace methods in java 


public class StringReplaceTest {

 public static void main(String[] args) {
  
  String source = "Hello Java Hello";
  
  // Replace character with new character
  String str1 = source.replace('H', 'S');
  System.out.println("\nMethod 1 : "+str1);
  
  // Replace character sequence with new character sequence
  CharSequence old = "Java";
  CharSequence _new = "String";
  
  String str2 = source.replace(old, _new);
  System.out.println("\nMethod 2 : "+str2);
  
  // Replace all matching pattern
  String str3 = source.replaceAll("el", "al");
  System.out.println("\nMethod 3 : "+str3);
  
  // Replace any matching pattern at beginning of the line
  String str4 = source.replaceAll("^H", "S");
  System.out.println("Method 3 : "+str4);
  
  // Replace only first matching pattern
  String str5 = source.replaceFirst("Hello", "Hi");
  System.out.println("\nMethod 4 : "+str5);
 }
}

OUTPUT:


Method 1 : Sello Java Sello

Method 2 : Hello String Hello

Method 3 : Hallo Java Hallo
Method 3 : Sello Java Hello

Method 4 : Hi Java Hello



MySQL JDBC Connection Example

 

Java MySQL

In one of our earlier tutorial we have seen about PostgreSQL database connection with simple JSP login page example. In this tutorial we will see about MySQL JDBC connection with example. To test this code we assume already MySQL database has been installed properly and its in running state. Also we have create a test database to verify the code. 
Any Java IDE like Eclipse, IntelliJ  etc., can be used or even we can test from command prompt. 
Next we need MySQL JDBC jar file or MySQL connector jar file. If you are using any IDE then downloaded jar file can be added to your libraries.

In below example we will see how to create MySQL DB connection, how to use simple select query and finally closing the connection. 


public class TestConnection {
 
 public static void main(String[] args) {
  
  // Creating DB connection
  Connection conn = createConnection();
  
  // Simple fetch query
  fetchEmailId(conn);
  
  // Closing connection
  closeConnection(conn);
 }

 public static Connection createConnection(){
  
  Connection conn = null;
   
  try {
   Class.forName("com.mysql.jdbc.Driver");
   System.out.println("MySQL JDBC Driver Registered successfully :)");
   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username", "password");
  
  } catch (SQLException e) {
   System.err.println("Connection failed !!!");
   e.printStackTrace();
   return null;
  
  } catch (ClassNotFoundException e) {
   System.err.println("Please configure MySQL driver file !!!");
   e.printStackTrace();
  }
  return conn;
 }
 
 public static void fetchEmailId(Connection conn){
  Statement st = null;
  if(conn == null){
   System.err.println("Connection failed !!!");
   return;
  }
  
  System.out.println("Database connection is successfull :)");
  
  //Querying simple select query
  try {
   String qry = "SELECT email_id FROM tbl_email_master";
   st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
   ResultSet rs = st.executeQuery(qry);
   while(rs != null && rs.next()){
    System.out.println(rs.getString("email_id"));
   }
   
  } catch (SQLException e) {
   e.printStackTrace();
  
  } finally{
   try{
    if(st != null) st.close();
   }catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
 
 public static void closeConnection(Connection conn){
  if(conn != null){
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
}