Monday, January 28, 2013

java swing GUI basic... separate thread for event ...


package gui.basics;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class GUi2 extends JFrame {

private JLabel l1, l2;
private JTextField t1, t2;
private JButton b1, b2;



public GUi2()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
l1 = new JLabel("var1");
l2 =new JLabel("var2");
t1 =new JTextField(10);
t2 =new JTextField(10);
b1 =new JButton("Ok");
b2 =new JButton("cancel");

//GridLayout gl =new GridLayout(2,3);
FlowLayout fl =new FlowLayout();
Container c = getContentPane();
c.setLayout(fl);
c.add(l1);
c.add(t1);
c.add(l2);
c.add(t2);
c.add(b1);
c.add(b2);
PQR obj =new PQR();
b1.addActionListener(obj);
b2.addActionListener(obj);
//setSize(300,400);
pack();
System.out.println("gui building " + Thread.currentThread());;


setTitle("sample window");
setVisible(true);

}

 class PQR implements ActionListener
 {
 
class StartThread extends Thread
{
public StartThread() { start(); }
public void run() { doRegistration(); }
 
 
}

public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub

System.out.println("gui building " + Thread.currentThread());;
if(arg0.getSource() == b1)
{
System.out.println("hello");
StartThread t = new StartThread();


}
else if(arg0.getSource() == b2)
{
System.out.println("hi");
}

}
 }



private void doRegistration() {
// TODO Auto-generated method stub
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}

Sunday, January 27, 2013

SPRING 3 javaconfig using annotation simple hello world example.....step by step

source:http://www.mkyong.com/spring3

Spring JavaConfig 

Now, see a full Spring JavaConfig example.

1. Directory Structure

See directory structure of this example.
directory structure of this example
2. Dependency Library
To use JavaConfig (@Configuration), you need to include CGLIB library. See dependencies :
 <!-- Spring 3 dependencies -->
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.version}</version>
 </dependency>
 
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
 </dependency>
 
 <!-- JavaConfig need this library -->
 <dependency>
  <groupId>cglib</groupId>
  <artifactId>cglib</artifactId>
  <version>2.2.2</version>
 </dependency>

3. Spring Bean

A simple bean.
package com.mkyong.hello;
 
public interface HelloWorld {
 
 void printHelloWorld(String msg);
 
}
package com.mkyong.hello.impl;
 
import com.mkyong.hello.HelloWorld;
 
public class HelloWorldImpl implements HelloWorld {
 
 @Override
 public void printHelloWorld(String msg) {
 
  System.out.println("Hello : " + msg);
 }
 
}

4. JavaConfig Annotation

Annotate with @Configuration to tell Spring that this is the core Spring configuration file, and define bean via @Bean.
package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;
 
@Configuration
public class AppConfig {
 
    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
 
}

5. Run it

Load your JavaConfig class with AnnotationConfigApplicationContext.
package com.mkyong.core;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.mkyong.config.AppConfig;
import com.mkyong.hello.HelloWorld;
 
public class App {
 public static void main(String[] args) {
 
            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
     HelloWorld obj = (HelloWorld) context.getBean("helloBean");
 
     obj.printHelloWorld("Spring3 Java Config");
 
 }
}
Output
Hello : Spring3 Java Config

SPRING dependency injection object dependency using Setter Injection and Constructor Injection.....


source:http://www.mkyong.com/spring
In Spring framework, Dependency Injection (DI) design pattern is used to define the object dependencies between each other. It exits in two major types :
  • Setter Injection
  • Constructor Injection

1. Setter Injection

This is the most popular and simple DI method, it will injects the dependency via a setter method.
Example
A helper class with a setter method.
package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
 
public class OutputHelper
{
 IOutputGenerator outputGenerator;
 
 public void setOutputGenerator(IOutputGenerator outputGenerator){
  this.outputGenerator = outputGenerator;
 }
 
}
A bean configuration file to declare the beans and set the dependency via setter injection (property tag).
<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-2.5.xsd">
 
 <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
  <property name="outputGenerator">
   <ref bean="CsvOutputGenerator" />
  </property>
 </bean>
 
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
 
</beans>
You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a setter method (setOutputGenerator).

2. Constructor Injection

This DI method will injects the dependency via a constructor.
Example
A helper class with a constructor.
package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
 
public class OutputHelper
{
 IOutputGenerator outputGenerator;
 
        OutputHelper(IOutputGenerator outputGenerator){
  this.outputGenerator = outputGenerator;
 }
}
A bean configuration file to declare the beans and set the dependency via constructor injection (constructor-arg tag).
<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-2.5.xsd">
 
 <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
  <constructor-arg>
   <bean class="com.mkyong.output.impl.CsvOutputGenerator" />
  </constructor-arg>
 </bean>
 
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
 
</beans>
You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a constructor.

Setter or Constructor injection?

There are no hard rule set by Spring framework, just use whatever type of DI that suit your project needs. However, due to the simplicity of the setter injection, it’s always selected for most of the scenarios.

How SPRING DI provides loose coupling....


source :http://www.mkyong.com/spring/

Output Generator Example

Let’s see an example, assume your project has a function to output the content to Csv or Json format. Your code may look like the following example:
File : IOutputGenerator.java – An interface for output generator
package com.mkyong.output;
 
public interface IOutputGenerator
{
 public void generateOutput();
}
File : CsvOutputGenerator.java – A Csv output generator to implement the IOutputGenerator interface.
package com.mkyong.output.impl;
 
import com.mkyong.output.IOutputGenerator;
 
public class CsvOutputGenerator implements IOutputGenerator
{
 public void generateOutput(){
  System.out.println("Csv Output Generator");
 }
}
File : JsonOutputGenerator.java – A Json output generator to implement the IOutputGenerator interface.
package com.mkyong.output.impl;
 
import com.mkyong.output.IOutputGenerator;
 
public class JsonOutputGenerator implements IOutputGenerator
{
 public void generateOutput(){
  System.out.println("Json Output Generator");
 }
}
There are couple of ways to call the IOutputGenerator, and how to use Spring to avoid objects to coupled tightly with each other.
1. Method 1 – Call it directly
Normal way, call it directly.
package com.mkyong.common;
 
import com.mkyong.output.IOutputGenerator;
import com.mkyong.output.impl.CsvOutputGenerator;
 
public class App 
{
    public static void main( String[] args )
    {
     IOutputGenerator output = new CsvOutputGenerator();
     output.generateOutput();
    }
}
Problem
In this way, the problem is the “output” is coupled tightly to CsvOutputGenerator, every change of output generator may involve code change. If this code is scattered all over of your project, every change of the output generator will make you suffer seriously.
Method 2 – Call it with helper class
You may think of creating a helper class to move all the output implementation inside.
package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
import com.mkyong.output.impl.CsvOutputGenerator;
 
public class OutputHelper
{
 IOutputGenerator outputGenerator;
 
 public OutputHelper(){
  outputGenerator = new CsvOutputGenerator();
 }
 
 public void generateOutput(){
  outputGenerator.generateOutput();
 }
 
}
Call it via helper class.
package com.mkyong.common;
 
import com.mkyong.output.OutputHelper;
 
public class App 
{
    public static void main( String[] args )
    {
     OutputHelper output = new OutputHelper();
     output.generateOutput(); 
    }
}
Problem
This looks more elegant, and you only need to manage a single helper class, however the helper class is still tightly coupled to CsvOutputGenerator, every change of output generator still involves minor code change.
Method 3 – Spring
In this scenario, Spring Dependency Injection (DI) is a good choice. Spring can make your output generator loosely coupled to the output generator.
Minor change in OutputHelper class.
package com.mkyong.output;
 
import com.mkyong.output.IOutputGenerator;
 
public class OutputHelper
{
 IOutputGenerator outputGenerator;
 
 public void generateOutput(){
  outputGenerator.generateOutput();
 }
 
 public void setOutputGenerator(IOutputGenerator outputGenerator){
  this.outputGenerator = outputGenerator;
 }
}
Create a Spring bean configuration file and declare all your Java object dependencies here.
<!-- Spring-Common.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-2.5.xsd">
 
 <bean id="OutputHelper" class="com.mkyong.output.OutputHelper">
  <property name="outputGenerator" ref="CsvOutputGenerator" />
 </bean>
 
 <bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
 <bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
 
</beans>
Call it via Spring
package com.mkyong.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.mkyong.output.OutputHelper;
 
public class App 
{
    public static void main( String[] args )
    {
     ApplicationContext context = 
        new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"});
 
     OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
     output.generateOutput();
 
    }
}
Now, you just need to change the Spring XML file for a different output generator. When output changed, you need to modify the Spring XML file only, no code changed, means less error.
Conclusion
With Spring framework – Dependency Injection (DI) is a useful feature for object dependencies management, it is just elegant, highly flexible and facilitates maintainability, especially in large Java project.

Exception Handling


How Exception Handling works?

At low level an exception is a java object with attributes and methods. When a problem occurs, an exception object is created, thrown and then handled.


exception handling can be grouped into these four phases. When a problem occurs it is the start of exception handling flow. A problem can be broadly classified into two. First one is, it can be handled and execution can continue, the second one is an unrecoverable serious situation which cannot be handled. An example for recoverable problem is, code block is expecting a value in a variable and it is not present. This can be handled by substituting a default value and the execution can continue. An easy example for unrecoverable condition is a hardware failure.

Java’s exception handling mechanism is object oriented. We have Throwable as the base class and all exceptions are sub classes of Throwable. We have Error and Exception as two immediate sub classes of Throwable.

When to use Exception Handling?

Exception handling should be used judiciously. Earlier I wrote about fail fast vs fail safe and that article loosely relates to this context and my personal preference is to fail fast. Exception handling does not mean that we should take the program flow in an alternate direction than the intended one and which may cause issues in future. We should be cautious when we say handling, as in the name of handling, an issue should not be carried over to a different context of the program as it will come back to haunt us.

So when do we use exception handling, it is when we foresee that a problem may occur at run time and we know a possible solution to it at design time itself. Then at run time if that solution path is chosen it should not alter the core objective of the program. Cases like, just logging the problem and proceeding with the flow does not fit into exception handling. A popular mistake done by java developers is to use exception handling for flow control. Though we have if-else and other options, we tend to fall on exception handling side and use it as flow control mechanism which is poor.

Exception Handling Keywords

throw

Exceptions can be thrown by either java run time environment or by the code itself. JRE throws exception when java’s rules are violated. An example is, when the code accesses an array location which is not available then ArrayIndexOutOfBoundsException is thrown. Pretty nice name right and obviously it explains the problem. All the java exception classes are not having any attributes and standard methods. It is a common design. Class name describes what exception it is and the hierarchy forms an organization chart kind of structure using which java exceptions are used.

Programmers can throw an exception to indicate a problem condition. Either java’s predefined exceptions can be used or custom exceptions can be created by extending the already available exceptions. Programmer can throw a custom exception or a predefined Java exception. Mostly custom exceptions are created based on business conditions. Programmer can use the Java keyword ‘throw‘ to generate an exception. It is done by instantiating the exception class of choice and then thrown.

try – catch

A thrown exception should be handled. If the program does not handles an exception, then it will be handled by the java run time environment. A block of code where an exception is expected should be surrounded by try – catch block. try indicates the start of the exception handling block and catch the end of the block. Following catch a block of code can be written which is the exception handling code block. This is the part the handles the exception. A catch will have an exception identified and it will catch only that type of exception. Type means the same exception and all its sub classes. There can be multiple catch blocks for a try block.

throws

When a Java method is going to throw an exception, to indicate that as part of the method signature ‘throws‘ keyword should be used followed by the exception. It means that the caller of this method should handle the exception given in the throws clause. There can be multiple exceptions declared to be thown by a method. If the caller of that method does not handles the exception, then it propagates to one level higher in the method call stack to the previous caller and similarly till it reaches base of the method call stack which will be the java’s run time system.

finally

After catch block there can be one more block of code declared as ‘finally‘. Irrespective of whether an exception is thrown or not, the finally block of code will always be executed. Important piece of code that must be executed, even if a program fails belong to this finally block. Example would be closing a database connection, a file handle, etc.

General Exception Handling Structure

try {
  // possible exception code block
} catch (ExceptionTypeA exception1) {
  // handle exception of type ExceptionTypeA and all it subclasses
} catch (ExceptionTypeB exception2) {
  // handle exception of type ExceptionTypeB and all it subclasses
} finally {
  // guarantee block: executes always irrespective of exception 
}

Friday, January 25, 2013

Top 30 Programming questions asked in Interview - Java C C++ Answers



JUST RUN THROUGH IT!!!!

Top 30 Programming interview questions

String Programming Interview Questions
String is the primary and probably most common thing you come across on any programming language and so is with any programming interview. There is almost always a question on String whether its related to length or replace but I have always find one or two String programming questions on interviews.
1) Write code to check a String is palindrome or not?
Palindrome are those String whose reverse is equal to original.This can be done by following technique demonstrated in How to reverse String in Java without using API
 
2) Write a method which will remove any given character from a String?
3) Print all permutation of String both iterative and Recursive way?
4) Write a function to find out longest palindrome in a given string?

Some more String related Questions which mostly appear in Java programming interviews:
Difference between String and StringBuffer in Java
Why String is final in Java
How to Split String in java 
Why Char array is preferred over String for storing password?

Programming questions on Array

Array is one of the topics where most of programming questions is asked. There are many and many programming questions on Array and here I have included only some of them which is not very difficult to solve but some of array programming question can be extremely challenging, so well prepare this topic.
5) In an array 1-100 numbers are stored, one number is missing how do you find it?
6) In an array 1-100 exactly one number is duplicate how do you find it?
This article contains a trick to find duplicates in Array using Java programming language
 
7) In an array 1-100 many numbers are duplicates, how do you find it?
trick in this programming questions is by using hashmap or hashtable , we can store number as key and its occurrence as value, if number is already present in hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Here is a quick tip to solve this programming question:  put the elements of the second array in the Hashtable and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table

9) How do you find second highest number in an integer array?


LinkedList Programming Interview Questions

10) How do you find middle element of a linked list in single pass?
To answer this programming question I would say you start with simple solution on which you traverse the LinkedList until you find the tail of linked list where it points to null to find the length of linked list  and then reiterating till middle. After this answer interviewer will ask you find the middle element in single pass and there you can explain that by doing space-time tradeoff you can use two pointers one incrementing one step at a time and other incrementing two step a time, so when first pointer reaches end of linked second pointer will point to the middle element.

11) How do you find 3rd element from last in single pass?
This programming question is similar to above and can be solved by using 2 pointers, start second pointer when first pointer reaches third place.
12) How do you find if there is any loop in singly linked list? How do you find the start of the loop?
This programming question can also be solved using 2 pointers and if you increase one pointer one step at a time and other as two steps at a time they will meet in some point if there is a loop.
13) How do you reverse a singly linked list?


Binary Tree Programming Interview Questions

Binary tree or simply tree is one of favorite topic for most of interviewer and pose real challenge if you struggle with recursion. Programming questions on tree can become increasingly difficult when you think iterative but sometime can be very easy if you come with recursive solution.
14) How do you find depth of binary tree?
15) Write code to print InOrder traversal of a tree?
16) Print out all leaf node of a binary tree?

 

Programming questions on searching and sorting

I have only included two programming questions related to searching and sorting but there are more can be finding on google. Purpose of these programming questions is to see whether programmer is familiar with essential search and sort mechanism or not.
17) Write a program to sort numbers using quick sort?
18) Write a program to implement binary search algorithm
19) How do you sort Java object using Comparator?
This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for answer.


Programming questions on numbers

Most of the programming questions are based on numbers and these are the ones which most of us did on college level and mind you they still has value I have seen programmers with experience of 3 years struggle with these programming questions and doesn’t solve it some time and take a lot of time which simply shows that they are not in programming in there day to day work.
19) Write code to check whether a no is power of two or not?
20) Write a program to check whether a no is palindrome or not?
check out this post which shows how to reverse number in Java and can be used to find if its palindrome or not.
 
21) Write code to check whether a no is Armstrong no or not
Here is a Java program to find Armstrong number, you can use same logic to write code in any other programming language like C and C++.
 
22) Write a program to find all prime number up to a given numbers?
Here is another Java program to find prime numbers and print them. By using logic demonstrated in this program; you can write similar program in C and C++.
 
23) Write function to compute Nth Fibonacci number? Both iterative and recursive?
Check this Java program to print Fibonacci Series using recursion and iteration.

General Programming Interview Questions

In this category of programming questions I have put questions which are not fit into any data structure but presents a real life problem and you need to provide solution. These programming questions are sometime based on problems faced by developer itself. I have not included many Software design related programming question which I have shared on Top 20 software design questions and answers; you can also check that.
24) Write a program to find out if two rectangles R1 and R2 are overlapping?
35) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.
26) Write code for Generate Random No in a range from min to max?
27) Write program for word-wrap which should work on any screen size?
28) Design an algorithm to find the frequency of occurrence of a word in an article?
29) Write a program to implement blocking queue in Java?
30) Write a program for producer-consumer problem?
This article solves producer consumer problem using BlockingQueue in Java. You can refer it to answer this question.

Tips on answering programming questions

1. If Interviewer asks you to write function then make sure you do some necessary check for bad input e.g. null check or empty check. Most of the time programmer forgets to test for not null, empty, less than 1, greater than 1 or zero input.
2. If you write iterative version of function then Interviewer may ask you to write recursive version or vice-versa so be prepare for that.
3. If you write a recursive function then Interviewer will ask to optimize it, even in case of Iterative version. So remember that you can optimize recursive function by Memorization (caching already calculated value) and by applying some space/time tradeoff principle. For example recursive version of Fibonacci series has O(n2) which can be reduced to O(n) using Memoziation.
4. Interviewer may ask you to calculate Order of complexity for best and worst case of any method so be prepared.
5. Most of the time Interviewer ask how to fix a problem as follow-up question e.g. he will ask how do you find deadlock and then how to fix deadlock in java etc.

Creating mirror of BST