Wednesday, 15 October 2014

Use Ful Programs

FIBONACCI CODE :
public class Fibonacci {
  public static void main(String args[]) {
  int number = 4;
    for (int i = 1; i <= number; i++) {
      System.out.println(fibonacciLoop(i)+"");
    }
  }
  // Java program for Fibonacci number using recursion.
  public static int fibonacciRecusion(int number) {
    if (number == 1 || number == 2) {
      return 1;
    }
    return fibonacciRecusion(number - 1) + fibonacciRecusion(number - 2); // tail recursion 
    }
}

PALINDROME CODE :
public class Palindrome {
  static boolean isPalin(String s) {
    int len = s.length();
    for (int i = 0; i < len / 2; i++) {
      if (s.charAt(i) != s.charAt(len - i - 1)) {
        return false;
      }
    }
    return true;
  }
  public static void main(String[] args) {
    System.out.println(isPalin("123321"));
  }
}

ARMSTRONG CODE :
public class Armstrong {
  public static void main(String args[]) {
    int n=407, sum = 0, temp, r;
    temp = n;
    while (temp != 0) {
      r = temp % 10;
      sum = sum + r * r * r;
      temp = temp / 10;
    }
    if (n == sum)
      System.out.println("Entered number is an armstrong number.");
    else
      System.out.println("Entered number is not an armstrong number.");
  }
}

PRIME NUMBER:
private static boolean isPrimeNumber(int number){
   for(int i=2; i<=number/2; i++){
     if(number % i == 0){
       return false;
     }
   }
  return true;
}

CONVERT Number to Words:
public class NumberToWordsConverter {
 final private static String[] units = { "Zero", "One", "Two", "Three","Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven","Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen","Seventeen", "Eighteen", "Nineteen" };
 final private static String[] tens = { "", "", "Twenty", "Thirty", "Forty","Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
 public static String convert(int i) {
  if (i < 20)
   return units[i];
  if (i < 100)
   return tens[i / 10] + ((i % 10 > 0) ? " " + convert(i % 10) : "");
  if (i < 1000)
   return units[i / 100] + " Hundred"+ ((i % 100 > 0) ? " and " + convert(i % 100) : "");
  if (i < 1000000)
   return convert(i / 1000) + " Thousand "+ ((i % 1000 > 0) ? " " + convert(i % 1000) : "");
  return convert(i / 1000000) + " Million "+ ((i % 1000000 > 0) ? " " + convert(i % 1000000) : "");
 }
 public static void main(String[] args) {
  //Number to word
  String xx = "1234";
  System.out.println("XXXXX : " + convert(Integer.parseInt(xx)));
 }
}

PRINT LIST with Nodes:
import java.util.ArrayList;
import java.util.List;

public class RecursionList {
 public static void main(String args[]) {
  List list = new ArrayList();
  list.add("A");
  list.add("B");
  List list1 = new ArrayList();
  list1.add("C");
  list1.add("D");
  list1.add("E");
  list.add(list1);
  list.add("F");
  printList(list, "list");
 }
 private static void printList(List genericList,
   String previousPrintStatement) {
  int index = 0;
  String previousString = "";
  for (Object object : genericList) {
   previousString = previousPrintStatement + "." + index++;
   if (object instanceof List) {
    printList((List) object, previousString);
   } else {
    System.out.println("" + previousString + " " + " = " + object);
   }
  }
 }
}

Print Friendly and PDF
Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

Friday, 10 October 2014

Tech-Mahindra(Interview)

1.What are implict objects in JSP?
Ans:
Object Description
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.

2.What happens when a constructor is created?
ANS: JVM will not create the create default construtor.
          It creates an instance for a class.

3.What is is-a and has-a relationship represents in Java? And give an example?
ANS:
IS-A Relationship : 
       1.This refers to inheritance or implementation.
       2.Expressed using keyword “extends”.
       3.Main advantage is code reusability.

HAS-A Relationship 
        1.Has-A means an instance of one class “has a” reference to an instance of another class or 
           another instance of same class.
        2.It is also known as “composition” or “aggregation”.
        3.There is no specific keyword to implement HAS-A relationship but mostly we are depended
           upon “new” keyword.
Composition :  
       Without existence of container object, if there is no chance of existence of contained objects then
       container and contained objects are said to be strongly associated and this strong association is  
       known as composition.
Eg: A “university” has several “departments”. Without existence of “university” there is no chance for the “departments” to exist. Hence “university” and “departments” are strongly associated and this strong association is known as composition.
 
Aggregation : 
       Without existence of container object, if there is a chance of existence of contained objects then 
        container and contained objects are said to be loosely associated and this strong association is 
        known as aggregation.
Eg: A  “department” has several “professors”. Without existence of “departments” there is good chance for the “professors” to exist. Hence “professors” and “department” are loosely associated and this loose association is known as Aggregation.


4.When do we get ClassCastException ?
Ans:This exception is used to indicate that the application’s code has attempted to cast a specific
        object to a class of which it is not an instance. For example, an Integer object cannot be casted
        to a String object.
Example :
public interface Animal {}
 class Dog implements Animal{}

public class Main extends Dog{
  public static void main(String[] args) {
    Dog dog = new Dog();
    Animal a = dog;
    Animal as = (Main)dog;
    System.out.println("Hello");
  }
}


5.Hash-Map and Hash-table Difference? 

Parameter
Hashtable
HashMap
ThreadSafe
Yes
No
Synchronized
Yes
No
Performance
Due to theadSafe and Synchronized,it is often slower than HashMap
In single threaded environment, it is much faster than Hashtable.So if you do not work in multi thread environment ,then hashMap is recommended
Null key
Do not allow
Allows null key as well as values
Fail fast
enumeration in hashtable is not fail fast
Iterator in hashMap is fail fast
Extends
It extends Dictionary class which it quite old
It extends AbstractMap class
Alternative
No alternative
You can use ConcurrentHashMap for multi thread environment
NOTE:
         Fail-fast iterator means if one thread is iterating over hashmap and other thread trying to modify hashmap structurally it will throw ConcurrentModification Exception and fail immediately.
Structurally modification means inserting or deleting elements that can change structure of map.
6.What are the methods to be overridden while creating our own Hashmap?
   equals(Object o); return Boolean
   hashcode(); return integer

7.What are Static Factory methods and how to create ?
commonly used static factory methods:
  • valueOf
  • getInstance
  • newInstance
 8.What is difference between Comparator and Comparable?

Parameter
Comparable
Comparator
Sorting logic
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
Implementation
Class whose objects to be sorted must implement this interface.
Ex: Country class needs to implement comparable to collection of country object by id
Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. Ex:CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Package
Java.lang.Comparable
Java.util.Comparator

9.When do we get ConcurrentModificationException?
It gets when one method iterates over a collection while another method (that bis recursively called from the for loop) modifies the collection i.e., list. 
Ex:
public class IteratorExample {
    public static void main(String args[]){
       List<String> myList = new ArrayList<String>();
        myList.add("1");
        myList.add("2");
     for (Iterator iterator = myList.iterator(); iterator.hasNext();) {
      String string = (String) iterator.next();
      myList.remove(string);//If u remove this line we wont get error
      System.out.println(string);
        }
    }
}
O/P:
1
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
    at java.util.ArrayList$Itr.next(ArrayList.java:836)
    at IteratorExample.main(IteratorExample.java:15)

11.Diff between == and equals()?
==  compare the reference
.equal() compares the text

12.Difference between && and &?
&&--> This is logical operator -->This evaluates both sides of the operation
&--> This is Bitwise operator-->This evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

13.Why do we use List l = new ArrayList(); instead of ArrayList l = new ArrayList(); ?
FIRST APPROACH-->List list = new ArrayList();
you will only be able to invoke methods and fields declared inside list interface.
SECOND APPROACH-->ArrayList al = new ArrayList();
you will be able to invoke methods and fields from both the list and the arraylist.

Later on you felt that list object should be the  LinkedList() not an ArrayList();
 then first approach  is easy simply we do as below
                          list = new LinkedList();
If we had followed second approach. It is difficult to change because we cant change as we done in first approach like
                          al = new LinkedList(); {This throws the error}.


14.When to use List, Set and Map in Java ?
     If you want to create collection of unique elements an index and maintaining in an insertion order then go for --> List  
    If you want to create collection of unique elements and don't want any duplicate then go for --> Set
    If you store data in form of key and value then go for --> Map
Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

Monday, 6 October 2014

Custom/User-Defined Exception

If you are creating your own Exception that is known as custom exception or user-defined exception.

Here is an small example that tells If age is less than 18 it throws an exception as "not valid"  else it prints as "Welcome to vote"

Example:
class InvalidAgeException extends Exception{
 InvalidAgeException(String s){
  super(s);
 }
}


class TestCustomException1{ 
   static void validate(int age)throws InvalidAgeException{
     if(age<18)
      throw new InvalidAgeException("not valid");
     else
      System.out.println("welcome to vote");
   }    
   public static void main(String args[]){
      try{
      validate(13);
      }catch(Exception m){System.out.println("Exception occured: "+m);}
      System.out.println("rest of the code..."); 
  }
}


O/P:
Exception occured: InvalidAgeException: not valid
rest of the code...




NOTE :
In above example we can extends Throwable class instead of Exception.
But we need to be careful that in our main method we need to catch that Throwable.
Otherwise we get RunTime Exception.

we need to rewrite as below
catch(Throwable e){
}
Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

Simplest way to display Server Time in JSP using js

THE BELOW CODE WORKS ONLY IN JSP : <html> <body > <table width="95%" border="1" cellpadding="1...