Java Interview Questions - 7

In our earlier tutorial we have seen lot of Java interview questions and sample programs. In this tutorial we see similar set of interview questions and answers.

What state does a thread enter when it terminates its processing?


What is the Collections API?


Can a lock be acquired on a class?


What is the Vector class?


What modifiers may be used with an inner class that is a member of an outer class?


What is an Iterator interface?


What is the difference between the >> and >>> operators?


What's new with the stop(), suspend() and resume() methods in JDK 1.2?


Java Interview Questions - 7

Is null a keyword?


Which characters may be used as the second character of an identifier, but not as the first character of an identifier?


What is the List interface?


what is a transient variable?


which containers use a border Layout as their default layout?


Why do threads block on I/O?


How are Observer and Observable used?


What is synchronization and why is it important?


What is the preferred size of a component?


What method is used to specify a container's layout?


Which containers use a FlowLayout as their default layout?


How does Java handle integer overflows and underflows?


Which method of the Component class is used to set the position and size of a component?


How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?


What is the difference between yielding and sleeping?


Which java.util classes and interfaces support event handling?


Is sizeof a keyword?


What are wrapped classes?


Does garbage collection guarantee that a program will not run out of memory?


What restrictions are placed on the location of a package statement within a source code file?


Can an object's finalize() method be invoked while it is reachable?


What is the immediate superclass of the Applet class?


What is the difference between preemptive scheduling and time slicing?


Name three Component subclasses that support painting.


What value does readLine() return when it has reached the end of a file?


What is the immediate superclass of the Dialog class?


What is clipping?


What is a native method?


Can a for statement loop indefinitely?


What are order of precedence and associativity, and how are they used?


When a thread blocks on I/O, what state does it enter?


To what value is a variable of the String type automatically initialized?


What is the catch or declare rule for method declarations?


What is the difference between a MenuItem and a CheckboxMenuItem?


What is a task's priority and how is it used in scheduling?


What class is the top of the AWT event hierarchy?


When a thread is created and started, what is its initial state?


Can an anonymous class be declared as implementing an interface and extending a class?


What is the range of the short type?


What is the range of the char type?


In which package are most of the AWT events that support the event-delegation model defined?


What is the immediate superclass of Menu?


What is the purpose of finalization?


Which class is the immediate superclass of the MenuComponent class.


What invokes a thread's run() method?


What is the difference between the Boolean & operator and the && operator?


Name three subclasses of the Component class.


What is the GregorianCalendar class?


Which Container method is used to cause a container to be laid out and redisplayed?


What is the purpose of the Runtime class?


How many times may an object's finalize() method be invoked by the garbage collector?


What is the purpose of the finally clause of a try-catch-finally statement?


What is the argument type of a program's main() method?


Which Java operator is right associative?


What is the Locale class?


Can a double value be cast to a byte?


What is the difference between a break statement and a continue statement?


What must a class do to implement an interface?


What method is invoked to cause an object to begin executing as a separate thread?


Name two subclasses of the TextComponent class.


What is the advantage of the event-delegation model over the earlier event-inheritance model?


Which containers may have a MenuBar?


How are commas used in the initialization and iteration parts of a for statement?


What is the purpose of the wait(), notify(), and notifyAll() methods?


What is an abstract method?


How are Java source code files named?


What is the relationship between the Canvas class and the Graphics class?


What are the high-level thread states?


What value does read() return when it has reached the end of a file?


Can a Byte object be cast to a double value?


What is the difference between a static and a non-static inner class?


What is the difference between the String and StringBuffer classes?


If a variable is declared as private, where may the variable be accessed?


What is an object's lock and which object's have locks?


What is the Dictionary class?


How are the elements of a BorderLayout organized?


What is the % operator?


When can an object reference be cast to an interface reference?


What is the difference between a Window and a Frame?


Which class is extended by all other classes?


Can an object be garbage collected while it is still reachable?


Is the ternary operator written x : y ? z or x ? y : z ?


What is the difference between the Font and FontMetrics classes?


How is rounding performed under integer division?


What happens when a thread cannot acquire a lock on an object?


What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?


What classes of exceptions may be caught by a catch clause?


If a class is declared without any access modifiers, where may the class be accessed?


What is the SimpleTimeZone class?


What is the Map interface?


Does a class inherit the constructors of its superclass?


For which statements does it make sense to use a label?



Spring: Data access with JDBC simple example

In our earlier tutorial we have seen about Spring + Hibernate with simple example. Now lets see sample example with Spring JDBC by using DataSource. For more notes on Spring JDBC you can refer to spring doc link.
Here we used MySql database to demonstrate this example.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.app.spring.datasource</groupId>
  <artifactId>springdatasource</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
  
   <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.1.6.RELEASE</version>
 </dependency>
   <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.35</version>
 </dependency>
   <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.1.6.RELEASE</version>
 </dependency>
   
  </dependencies>
  
</project>


Employee.java

package com.app.model;

public class Employee {
 
 private int id;
 
 private String empName;
 
 private String designation;
 
 public Employee(int id, String empName, String designation){
  this.id = id;
  this.empName = empName;
  this.designation = designation;
 }
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 }  
}


EmpDao.java  

package com.app.dao;

import com.app.model.Employee;

public interface EmpDao {

 public void insert(Employee emp);
 
}


EmpDaoImpl.java

package com.app.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;

import com.app.model.Employee;

public class EmpDaoImpl implements EmpDao {

 
 private DataSource dataSource;
  
 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }
  
 public void insert(Employee emp) {
 
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  Connection con = null;
 
  try {
   con = dataSource.getConnection();
   PreparedStatement ps = con.prepareStatement(query);
   ps.setInt(1, emp.getId());
   ps.setString(2, emp.getEmpName());
   ps.setString(3, emp.getDesignation());
   ps.executeUpdate();
   ps.close();
 
  } catch (SQLException e) {
   throw new RuntimeException(e);
 
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }  
 }
}


spring-jdbc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

 
 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/roboticapp" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>
 
 <bean id="empDS" class="com.app.dao.EmpDaoImpl">
  <property name="dataSource" ref="dataSource" />
 </bean>
 
</beans>


MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(100, "Mark", "Manager");
  
  object.insert(emp);
  
  appContext.close();
 }
}


OUTPUT:
spring-Data access with JDBC simple example




Spring: Data access with JDBC simple example


Java: Regular Expressions by example

Regular Expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations using a specialized syntax held in a pattern. In Java "java.util.regex" package primarily uses classes like

  • Pattern - representation of a regular expression
  • Matcher - engine that interprets the pattern and performs match operations against an input string
  • PatternSyntaxException - unchecked exception that indicates a syntax error in a regular expression pattern

Regular Expressions
Now lets see simple example Pattern and Matcher for strings to match like username, password, email, ipaddress, 12/24 time formats. Here we are going to see only whether given string matches with the given pattern or not. Apart from that we can also use Pattern for replacing particular pattern of sub-string from the given the given string etc.,

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyRegExTest {

 public static void main(String[] args) {
  
  Pattern pattern;
  Matcher matcher;
  
  //USERNAME
  String patUsername = "^[a-z0-9_-]{4,15}$";
  
  pattern = Pattern.compile(patUsername);
  matcher = pattern.matcher("javadiscover");
  
  System.out.println("USERNMAE 1 : "+ matcher.matches());
  System.out.println("USERNAME 2 : "+ pattern.matcher("qw").matches());
 
  
  //PASSWORD
  String patPassword = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})";
  pattern = Pattern.compile(patPassword);
  
  System.out.println("PASSWORD 1 : "+ pattern.matcher("123asd").matches());
  System.out.println("PASSWORD 2 : "+ pattern.matcher("fhGe#123").matches());
  
  //IPADDRESS
  String patIp = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
  pattern = Pattern.compile(patIp);
  
  System.out.println("IP 1 : "+ pattern.matcher("123.234.19.0").matches());
  System.out.println("IP 2 : "+ pattern.matcher("257.2.99.4").matches());
  
  
  //EMAIL
  String patEmail = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
  pattern = Pattern.compile(patEmail);
  
  System.out.println("EMAIL 1 : "+ pattern.matcher("javadiscover@gmail.com").matches());
  System.out.println("EMAIL 2 : "+ pattern.matcher("spam@spam").matches());
  
  //TIME - 12-HOURS
  String patTime12 = "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)";
  pattern = Pattern.compile(patTime12);
  
  System.out.println("TIME 1 : "+ pattern.matcher("12:34 AM").matches());
  System.out.println("TIME 2 : "+ pattern.matcher("13:67 PM").matches());
  
  //TIME - 24-HOURS
  String patTime24 = "([01]?[0-9]|2[0-3]):[0-5][0-9]";
  pattern = Pattern.compile(patTime24);
  
  System.out.println("TIME 1 : "+ pattern.matcher("15:17").matches());
  System.out.println("TIME 2 : "+ pattern.matcher("13:67").matches());
 }
}


OUTPUT:

USERNMAE 1 : true
USERNAME 2 : false

PASSWORD 1 : false
PASSWORD 2 : true

IP 1 : true
IP 2 : false

EMAIL 1 : true
EMAIL 2 : false

TIME 1 : true
TIME 2 : false

TIME 1 : true
TIME 2 : false

Spring: Constructor Injection by Example

In our last tutorial we have seen about Setter Injection by simple example. In this tutorial we see same example with Constructor Injection. Only thing which we need to take care is "constructor-arg" order and type should match with bean class constructor method. Otherwise constructor injection argument type ambiguities exception will be thrown.
Dependency Injection with Spring


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.springframework.samples</groupId>
 <artifactId>SimpleSetterInj</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <!-- Spring Core -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.2.10.RELEASE</version>
  </dependency>
 </dependencies>
</project>


Employee.java

package com.app.springcore;

public class Employee {

 private String empName;
 private int age;
 private String gender;

 public Employee(String empName, int age, String gender){
  this.empName = empName;
  this.age = age;
  this.gender = gender;
 } 
 public String getEmpName() {
  return empName;
 }
 public int getAge() {
  return age;
 }
 public String getGender() {
  return gender;
 }
}


Office.java

package com.app.springcore;

public class Office {

 private String offName;
 private String offAddress;
 private Employee employee;
 
 public Office(String offName, String offAddress, Employee employee){
  this.offName = offName;
  this.offAddress = offAddress;
  this.employee = employee;
 }
 
 public String getOffName() {
  return offName;
 }
 public String getOffAddress() {
  return offAddress;
 }
 public Employee getEmployee() {
  return employee;
 }
}


Spring-Core.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
    <bean id="emp" class="com.app.springcore.Employee">
     
     <constructor-arg><value>Steve</value></constructor-arg>
   <constructor-arg><value>35</value></constructor-arg>
   <constructor-arg><value>Male</value></constructor-arg>
        
    </bean>
 
    <bean id="office" class="com.app.springcore.Office">
        <constructor-arg><value>ABCD Crop.</value></constructor-arg>
   <constructor-arg><value>Bangalore, India</value></constructor-arg>
   <constructor-arg ref="emp"></constructor-arg>
  </bean>
 
</beans>


TestClass.java

package com.app.springcore;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClass {

 public static void main(String[] args) {
  ApplicationContext appCon = new ClassPathXmlApplicationContext("Spring-Core.xml");
  Office office = (Office)appCon.getBean("office");
  
  System.out.println("Office Name    : "+office.getOffName());
  System.out.println("Office Address : "+office.getOffAddress());
  System.out.println("Employee Name  : "+office.getEmployee().getEmpName());
  System.out.println("Employee Age   : "+office.getEmployee().getAge());
  System.out.println("Employee Gender: "+office.getEmployee().getGender());
  
  ((ConfigurableApplicationContext)appCon).close();
        }
}


OUTPUT:

Office Name    : ABCD Crop.
Office Address : Bangalore, India
Employee Name  : Steve
Employee Age   : 35
Employee Gender: Male
Spring: Constructor Injection by Example




Spring: Setter Injection by Example

Core of the Spring Framework is its Inversion of Control (Ioc) container. The IoC container manages java objects – from instantiation to destruction – through its BeanFactory. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, life-cycle events, and any AOP features.
Dependency Injection with Spring
The IoC container enforces the dependency injection pattern for components by leaving them loosely coupled and allowed to code to abstractions. It exits in two major types like

  • Setter Injection
  • Constructor Injection

In this tutorial lets discuss about Setter Injection with simple example

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.springframework.samples</groupId>
 <artifactId>SimpleSetterInj</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <!-- Spring Context -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.2.10.RELEASE</version>
  </dependency>
 </dependencies>
</project>


Employee.java

package com.app.springcore;

public class Employee {

 private String empName;
 private int age;
 private String gender;
 
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
}


Office.java

package com.app.springcore;

public class Office {

 private String offName;
 private String offAddress;
 private Employee employee;
 
 public String getOffName() {
  return offName;
 }
 public void setOffName(String offName) {
  this.offName = offName;
 }
 public String getOffAddress() {
  return offAddress;
 }
 public void setOffAddress(String offAddress) {
  this.offAddress = offAddress;
 }
 public Employee getEmployee() {
  return employee;
 }
 public void setEmployee(Employee employee) {
  this.employee = employee;
 }
}


Spring-Core.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
    <bean id="emp" class="com.app.springcore.Employee">
        <property name="empName" value="Steve"></property>
        <property name="age"><value>35</value> </property>
        <property name="gender" value="Male"></property>
    </bean>
 
    <bean id="office" class="com.app.springcore.Office">
        <property name="offName" value="ABCD Crop."></property>
        <property name="offAddress" value="Bangalore, India"></property>
        <property name="employee" ref="emp"></property>
    </bean>
 
</beans>


TestClass.java

package com.app.springcore;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClass {

 public static void main(String[] args) {
  ApplicationContext appCon = new ClassPathXmlApplicationContext("Spring-Core.xml");
  Office office = (Office)appCon.getBean("office");
  
  System.out.println("Office Name    : "+office.getOffName());
  System.out.println("Office Address : "+office.getOffAddress());
  System.out.println("Employee Name  : "+office.getEmployee().getEmpName());
  System.out.println("Employee Age   : "+office.getEmployee().getAge());
  System.out.println("Employee Gender: "+office.getEmployee().getGender());
  
  ((ConfigurableApplicationContext)appCon).close();
        }
}


OUTPUT:

Office Name    : ABCD Crop.
Office Address : Bangalore, India
Employee Name  : Steve
Employee Age   : 35
Employee Gender: Male



You can download sample project in this link.