Tags

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

May 29, 2012

How to print multi-digit numbers like a 7-segment display

During an interview , many interviewers like to ask very simple coding questions. This is usually to check how fast the interviewee can do a context switch in her mind, her ability to think about some very basic problem, etc.
So, let’s tackle a few of such coding problems in this post. I am using Java as the programming language in this example,

The idea was to help some people which started preparing for interview. I hope you find some value in it.

This is simple java program to display number in 7 segment format

Example :123 should be display in following format, and in one line.
_ _
| _| _|
| |_ _|

1 - Set up your initial data for each number. You could do this as a 2d array (dimension 1: digit, dimension 2: line)
For example:
numbers[0][0] = "|-|"
numbers[0][1] = "| |"
numbers[0][2] = "|_|"

numbers[1][0] = "  |"
numbers[1][1] = "  |"
numbers[1][2] = "  |"

2 - For each line that makes up the character, scan across each digit in your input and write the appropriate string. This will build up the characters line by line.
        public class DigitalDisplay {
            /**
             * @param args
             */
        public static void main(String[] args) {
        String [][] num=new String[4][3];
        num[0][0]="|-|";  //this will display complete "0"
        num[0][1]="| |";
        num[0][2]="|_|";

        num[1][0]=" |";
        num[1][1]=" |";
        num[1][2]=" |";

        num[2][0]=" -|";
        num[2][1]=" _|";
        num[2][2]=" |_";

        num[3][0]=" -|";
        num[3][1]=" _|";
        num[3][2]=" _|";
        int[] input = {2,1,3}; 
        for (int line = 0; line < 3; line++)
        {          
            for (int inputI=0; inputI < input.length; inputI++)
            {
                int value = input[inputI];
                System.out.print(num[value][line]);
                System.out.print("  ");
            }          
            System.out.println();
        }
    }
}

**OUTPUT**

 -|   |   -|  
 _|   |   _|  
 |_   |   _|  

Feb 22, 2012

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.

Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.

Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.
Map map = new HashMap();

//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration and is more clean.

Method #3: Iterating using Iterator.

Map map = new HashMap();
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
f you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

Check if one string is a rotation of other string

Two string s1 and s2 how will you check if s1 is a rotated version of s2

For Example:
if s1=avs then the following are some of its rotated versions:
vsa
sav
vas
where as "vas" is not a rotated version.
algorithm checkRotation(string s1, string s2) 
  if( len(s1) != len(s2))
    return false
  if( substring(s2,concat(s1,s1))
    return true
  return false
end
In Java:
boolean isRotation(String s1,String s2) {
    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

Create a custom exception in Java

Following are the steps to create custom exception.

(1) create a custom exception class in Java;
(2) throw our custom Java exception;
(3) catch our custom exception; and
(4) look at the output from our custom exception when we print a stack trace.

To create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:
/**
 * My custom exception class.
 */
class CustomException extends Exception
{
  public CustomException(String message)
  {
    super(message);
  }
}

A method to throw our custom Java exception



here's a small example class with a method named getUser that will throw our custom exception (CustomException) if the method is given the value of zero as a parameter.

/**
 * Our test class to demonstrate our custom exception.
 */
class User
{
  public String getUser(int i) throws CustomException
  {
    if (i == 0)
    {
      // throw our custom exception
      throw new CustomException("zero ...");
    }
    else
    {
      return "user";
    }
  }
}

To test our custom Java exception. In our main method, we'll create a new instance of our User class, then call the getUser method with the value of zero, which makes that method throw our custom Java exception:

/**
 * A class to test (throw) the custom exception we've created.
 *
 */
public class CustomExceptionExample
{
  public static void main(String[] args)
  {
    // create a new User
    User user= new User();
    
    try
    {
      // intentionally throw our custom exception by
      // calling getUser with a zero
      String userStr= user.getUser(0);
    }
    catch (CustomException e)
    {
      // print the stack trace
      e.printStackTrace();
    }
  }
}

Standard Naming Conventions in Java

There are a set of standard conventions which should be followed.


Class Naming
1) The class and interface names should start with Capital letters. A few examples of good class names is:
Car
Customer

Package Naming
2) The naming convention for package names says that they should start from the reverse of the domain name of your company.
com.companyname.productName.util.StringUtil
com.mycompany.productName.controller.HomeeController

Do note that all characters in the package names are in small letters.

Variables Naming
3) The variables should have a naming convention of
a) The first letter should be small letter
b) Every word in the variable names should start with a capital letter

Method Naming
4) The method names Starting with small letter and every other word staring with Capital letter.e.g.
checkUser()
addUser()

Constants Naming
5) The constants which are declared as public static final in Java should have all letters as capital and the words within the constant should be separated by _(underscore) character as:
DATE_PATTERN

Note: Same naming conventions should be used across the Java application.

Inheritance versus composition

IS-A is tied to inheritance of one class by another class and HAS-A is tied to member instance variable of another class.

1) Both IS-A and HAS-A offer code reuse
Both result in the re-use of code already written in another class.

2) Run time polymorphism can be achieved with IS-A and not with HAS-A
Since IS-A is tied to inheritance so run-time polymorphism is achievable through IS-A relationship.

3) IS-A results in increased coupling between two classes but HAS-A usually draws a line on coupling
IS-A should be used when cohesion is to be increased but HAS-A has no visible effect on cohesion

4) The container class manages the lifecycle of contained class’s object in HAS-A relationship but the super class doesn’t play any role in the lifecycle of sub class’s object in IS-A relationship.

5) HAS-A relationship is closely related to another term named as Delegation.
When the container class invokes some method on the contained class’s object then the container is said to have delegated the call to container object.

6) IS-A can be visualized as a parent-child or vertical relationship.
HAS-A can be visualized as sibling or horizontal relationship.
Use IS-A relationship for closely related classes with sub class being more specific version of super class and use HAS-A relationship for possession kind of relationships

Feb 20, 2012

Frequently Asked Question about strings



Q: Why is String class immutable?

Ans: As string objects are used the most hence to avoid placing synchronization blocks at every place where multiple threads should not access string object simultaneously, String class was made immutable
Q: What is the difference between String, StringBuffer and StringBuilder?
Ans: String is immutable. StringBuffer provides immutability but has synchronized methods and StringBuilder class has similar features as StringBuffer but has non-synchronized methods
Q:What is the difference between a String object created on String pool and on the heap? Or What will be the result of following statements?
1) “abc” == “abc”
2) new String(“abc”) == new String(“abc”) 
Ans: The second object created with same content using String literal means both are pointing to same object in pool. But if created using new operator then each one takes new memory space even if they have same characters
 Q: Which new feature has been added to JDK 7 regarding Strings?
Ans: Strings can now be used in Switch/Case statements
Q: What happens when concatenation operator is used with Strings as shown in 1 and 2 below:
1) String str1 = “abc”;
String str2 = “def”;
String str3 = str1 + str2;
2) String str4 = “abc” + “def”;
Ans:  1) doesn’t result in such optimization and hence creates more number of String objects 
2)results in compiler optimization and hence the statement becomes String str4 = “abcdef”; after compilation




Jan 24, 2012

Design patterns for Java Interview


Before you appear for an interview, be ready with 8-10 design patterns with examples from your projects and be confident to answer questions about how you implemented those design patterns. Here I am providing a list of some common design patterns which a candidate can talk about in a Java interview.

1) Flyweight: As discussed above, it’s a part of JDK and hence is used by every Java program.
2) Iterator: All collection classes provide the feature of an iterator to iterate their elements. Moreover, I have also seen custom classes in my projects where the feature of iterator is custom built for those classes.
3) DAO (Data Access Object) : This is also one of the common design pattern seen in many applications which use SQL commands to interact with the datasource/database. Usually a DAO class has methods which invoke the SQL queries for CRUD operations on the database tables thus avoiding the need to write and maintain SQL queries in multiple classes for the same database tables.

4) DTO (Data Transfer Object) : This design pattern represents the data which is actually stored in the database tables in terms of Java classes and is accepted as argument by various methods of the DAO classes. This design pattern usually translates to POJO classes corresponding to database tables and their columns.
5) Factory: If you have used DAO then it is very likely that you have also seen factory design pattern being used as a factory class is written for generating the DAO’s.
6) Abstract Factory: This design pattern represents a factory of factories. When you have many closely related factory classes, you will write an interface which all those factories implement and thus can be generically referenced. You will write a class which will have methods to return the appropriate factory depending upon the need.
7) MVC: This is also one of the famous design patterns and should not be missed in Java interview.
8) Front Controller: This design pattern is closely associated with MVC design pattern and is used to write the single point of contact for any request that comes from the users. The controller then dispatches the request to appropriate handler depending upon the arguments being passed along with the request.
9) Singleton: Though Singleton design pattern looks to be easy to understand and get away with any Java interview but one can be grilled like anything on this design pattern. There is so much to ask on Singleton that a candidate can be judged only by asking questions on Singleton. This is because the interviewer can associate Inheritance, Reflection, Serialization, Collections, Polymorphism, Cloning and other Java concepts with Singleton.
Still if you were to choose only five design patterns for an interview due to time constraints then I would advise the following list:
1) Singleton
2) DAO (Data Access Object)
3) DTO (Data Transfer Object)
4) MVC (Model View Controller)
5) Factory


How HashSet works in Java


HashSet in Java is implemented to use hash based storage of elements and also has the property of having no duplicate elements at the same time.
When we dig dipper into the implementation of HashSet then we see that a HashMap instance member variable is used which not only provides the capability of hash based storage but also ensures zero duplicates contract.
Since HashMap has the property of having unique keys, HashSet makes use of this property of HashMap and stores the members of HashSet as the keys of internal HashMap instance.

If we open the source of HashSet then we see the following two member variables:-
   public boolean remove(Object o) {
            return map.remove(o)==PRESENT;
    }
Here PRESENT is a dummy object which is used as the value object for every key,value pair inserted into the internal HashMap instance. There is no PRESENT dummy object for every key,value pair and this object is declared as static in the HashSet class.
It is interesting to see how HashSet class implements clone method which is reproduced here for reference:

public Object clone() {
            try {
                HashSet newSet = (HashSet) super.clone();
                newSet.map = (HashMap) map.clone();
                return newSet;
            } catch (CloneNotSupportedException e) {
                throw new InternalError();
            }
    }
Here we see that first the clone of super class which is AbstractSet is invoked and then the internal HashMap reference of HashSet class is cloned.
The HashSet class also implements Serializable interface and takes proper care to customize the serialization operation by
1) providing a custom serial version UID
2) provide readObject and writeObject methods