Tuesday, 9 June 2015

Java Interview Questions - 8

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 is the purpose of the System class?


Which TextComponent method is used to set a TextComponent to the read-only state?


How are the elements of a CardLayout organized?


Is &&= a valid Java operator?


Name the eight primitive Java types.


Java Interview Questions - 7

Which class should you use to obtain design information about an object?


What is the relationship between clipping and repainting?


Is "abc" a primitive value?


What is the relationship between an event-listener interface and an event-adapter class?


What restrictions are placed on the values of each case of a switch statement?


What modifiers may be used with an interface declaration?


Is a class a subclass of itself?


What is the highest-level event class of the event-delegation model?


What event results from the clicking of a button?


How can a GUI component handle its own events?


What is the difference between a while statement and a do statement?


How are the elements of a GridBagLayout organized?


What advantage do Java's layout managers provide over traditional windowing systems?


What is the Collection interface?


What modifiers can be used with a local inner class?


What is the difference between static and non-static variables?


What is the difference between the paint() and repaint() methods?


What is the purpose of the File class?


Can an exception be rethrown?


Which Math method is used to calculate the absolute value of a number?


How does multithreading take place on a computer with a single CPU?


When does the compiler supply a default constructor for a class?


When is the finally clause of a try-catch-finally statement executed?


Which class is the immediate superclass of the Container class?


If a method is declared as protected, where may the method be accessed?


How can the Checkbox class be used to create a radio button?


Which non-Unicode letter characters may be used as the first character of an identifier?


What restrictions are placed on method overloading?


What happens when you invoke a thread's interrupt method while it is sleeping or waiting?


What is casting?


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


Name four Container classes.


What is the difference between a Choice and a List?


What class of exceptions are generated by the Java run-time system?


What class allows you to read objects directly from a stream?


What is the difference between a field variable and a local variable?


Under what conditions is an object's finalize() method invoked by the garbage collector?


How are this() and super() used with constructors?


What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?


What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?


How is it possible for two String objects with identical values not to be equal under the == operator?


Why are the methods of the Math class static?


What Checkbox method allows you to tell if a Checkbox is checked?


What state is a thread in when it is executing?


What are the legal operands of the instanceof operator?


How are the elements of a GridLayout organized?


What an I/O filter?


If an object is garbage collected, can it become reachable again?


What is the Set interface?


What classes of exceptions may be thrown by a throw statement?


What are E and PI?


Are true and false keywords?


What is a void return type?


What is the purpose of the enableEvents() method?


What is the difference between the File and RandomAccessFile classes?


What happens when you add a double value to a String?


What is your platform's default character encoding?


Which package is always imported by default?


What interface must an object implement before it can be written to a stream as an object?


How are this and super used?


What is the purpose of garbage collection?


What is a compilation unit?


What interface is extended by AWT event listeners?


What restrictions are placed on method overriding?


How can a dead thread be restarted?


What happens if an exception is not caught?


What is a layout manager?


Which arithmetic operations can result in the throwing of an ArithmeticException?


What are three ways in which a thread can enter the waiting state?


Can an abstract class be final?


What is the ResourceBundle class?


What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?


What is numeric promotion?


What is the difference between a Scrollbar and a ScrollPane?


What is the difference between a public and a non-public class?


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


Can try statements be nested?


What is the difference between the prefix and postfix forms of the ++ operator?


What is the purpose of a statement block?


What is a Java package and how is it used?


What modifiers may be used with a top-level class?


What are the Object and Class classes used for?


How does a try statement determine which catch clause should be used to handle an exception?


Can an unreachable object become reachable again?


When is an object subject to garbage collection?


What method must be implemented by all threads?


What methods are used to get and set the text label displayed by a Button object?


Which Component subclass is used for drawing and painting?


What are synchronized methods and synchronized statements?


What are the two basic ways in which classes that can be run as threads may be defined?


What are the problems faced by Java programmers who don't use layout managers?


What is the difference between an if statement and a switch statement?


What is the List interface?




read more.. "Java Interview Questions - 8"

Monday, 8 June 2015

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?



read more.. "Java Interview Questions - 7"

Friday, 5 June 2015

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


read more.. "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

read more.. "Java: Regular Expressions by example"