Finding Factorial of a number in Java

  • This interview question is mainly asked to freshers in Java Interviews.  
  • It also represents an example of recursion.
  • Factorial number means multiplication of all positive integer from one to that number.
  • Two factorial:   2!=  2*1=2
  • Three factorial: 3!= 3*2*1=6.
  • Eight factorial:   8!= 8* 7*6*5*4*3*2*1=40320



where ' ! ' sign represents the factorial .


package com.javainhouse;

import java.util.Scanner; public class FactiorialProgram { public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Enter a number to find factorial"); int n= in.nextInt(); int fact=1; for (int i = 1; i < n; i++) { fact=fact*i; } System.out.println("Factorial of "+n+" is "+fact); } }



Output:

Enter a number to find factorial
5
Factorial of 5 is 24

Java Program To Remove Duplicate Elements From ArrayList without using Collections



package com.javainhouse;

import java.util.ArrayList; 
public class RemoveDuplicates {
public static void main(String[] args)
{

 ArrayList<Object> al = new ArrayList<Object>(); 
 al.add("java"); 
 al.add('a');
 al.add('b');
 al.add('a');
 al.add("java");
 al.add(10.3); 
 al.add('c'); 
 al.add(14); 
 al.add("java"); 
 
 al.add(12); 
 System.out.println("Before Remove Duplicate elements:"+al);

 for(int i=0;i<al.size();i++)
 { 
 
for(int j=i+1;j<al.size();j++)
if(al.get(i).equals(al.get(j)))
al.remove(j); j--; 
System.out.println("After Removing duplicate elements:"+al);
}
}

Java Program to print numbers in pyramid shape


package com.javainhouse;

public static void main(String[] args)
 {
  
   
   int test=5;
   
   for (int i=1;i<test;i++)
   {
     int j=1;
     
      for ( j=1;j<i;j++)
    {
        
         System.out.print(j);
      }
     
      for (int k=j;k>0;k--)
    {
        
         System.out.print(k);
      }
     System.out.println();
   }
   
  
 }


OutPut: 


1
121
12321
1234321


How to reverse a String using recursion

For the solution of this program we will use recursion mechanism in which a method calls itself again and again till the condition satisfies.





package com.javainhouse;


public class reverseString

 { String reverse = "";
public String reverseString(String str)
{

if(str.length() == 1)
{
return str;
}

else

{
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}

}

public static void main(String a[])

{
StringRecursiveReversal srr = new StringRecursiveReversal();
System.out.println("Result: "+srr.reverseString("Java2novice"));

}
 } 



Output:

Reverse String Java




How to Find duplicate numbers in given list in Java

For this program we are going to use HashSet as Set does not allow duplicate elements.

We will be using two HashSets . As he list is traversed ,all the elements will be started storing in the first hash set and if any element is traversed again the first hash set will not allow that element and that element will be stored in the second hash set and at last we ll print the second Hash set .




package com.javainhouse;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class findDuplicateElements
{

public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
for (int i = 2; i < 7; i++) {
list.add(String.valueOf(i));
}
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
 
for (String element : list) {
if (!set1.add(element)) {
setToReturn.add(element);
}
}
 
System.out.println("Original List : " + list);
System.out.println("Duplicate elements from list : " + setToReturn);
}
 
}
     

OutPut :

Duplicate Elements in List Program



How to create a custom exception in Java


Why we need custom Exception ?
How to create a custom exception ?
Write code to create a Custom Exception

All these are questions usually asked in a Java interview .So my today's post on how to create a custom exception in java .

As we know There are two types of Exception :
1. Checked Exception
2. Unchecked Exception

Both these exceptions have a common parent class Exception .So ,in same order if we have to create a custom exception ,we need to extend Exception class.

Ok , let me explain the process step by step .

1. Any custom exception should extend Exception Class .

2. There should be a proper name given to the Exception ,For example if there is an exception related to Invalid age name can be given as InvalidAgeException


public class InvalidAgeException extends Exception {}


public class InvalidAgeException extends Exception {
private int age;

public InvalidAgeException ()
{
super();
}
public InvalidAgeException (String message, int age)

{
   super(message);

   this.age = age;


}

In the above way we can define two constructors of InvalidAgeException with message and without message

Usage of custom Exception:

Below is the program with usage of custom exception.

public class CustomExceptionDemo 



private static final Map<Integer, String> employee = new HashMap<>(); 

static

 {
   employee.put(100"Mahesh");
  employee.put(101"Suresh");

   employee.put(102"Bran");

   employee.put(103"Troy"); }

 public static void main(String args[])
 { 

     CustomExceptionDemo t = new CustomExceptionDemo();

    t.getAge(1000); } 

public String getAge(int age)

 { 

     if (employee.get(age) == null)


   throw new InvalidAgeException ("No such employee exists", age);

return employee.get(name);

}

}







Spring MVC / Hybris JUnit For Validators

Hi Guys ,today I am going to write a post on Test Validators in Spring MVC with Junit or How to write Junit for Validators.
I faced quite a lot problem in finding a proper solution for that while working in a project . These Validators are used
in Spring MVC and Hybris projects . So Basically while writting a Validator I had to check 2 main things 1st was that expiry date should not be null and
other was the file uploaded in form should have valid format and lesser than 5MB in size. so My Validator method looks as below:




@Override
public void validate(final Object object, final Errors errors)
{
final myForm myForm = (myForm) object;

 if (!checkFileContentType(myForm.getFileScan().getContentType())
{
errors.rejectValue("file", "File is Invalid");
}


if (myForm.getExpiryDate() == null || myForm.getExpiryDate().equals(""))
{
errors.rejectValue("date", "Invalid date");
}

}





so for JUnit of this validator i need to varify errors.rejectValue as feel upload a dummy file with java code in my validtor class.
So my Test class looks as below :






MyValidator = new MyValidator();
}

@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);// this line is optional if not using mockito

MyForm myForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.jpeg");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile FileScan = new CommonsMultipartFile(fi);
myForm.setFileScan(FileScan);
}



@Test
public void testdatenull()
{

myForm.setFileName("testFileName");
myForm.setExpiryDate(null);
final BindException errors = new BindException(myForm, myForm.class.getName());
MyValidator.validate(myForm, errors);

assertEquals("Invalid date", errors.getFieldError("date").getCode());


}

@Test
public void testEmptyFileScan()
{
MyForm myNewForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.xml");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile newFileScan = new CommonsMultipartFile(fi);
myNewForm.setFileScan(newFileScan);
myNewForm.setFileName(StringUtils.EMPTY);
myNewForm.setExpiryDate("15/08/2013");
final BindException errors = new BindException(myNewForm, MyForm.class.getName());
MyValidator.validate(myNewForm, errors);
assertEquals("File is invalid", errors.getFieldError("file").getCode());


}

private FileItem createFileItem(final String fieldName, final File file) throws Exception
{

final boolean isFormField = false;
final String fileName = file.getName();
final String contentType = new MimetypesFileTypeMap().getContentType(file);

final DiskFileItemFactory factory = new DiskFileItemFactory();
final FileItem fileItem = factory.createItem(fieldName, contentType, isFormField, fileName);

final InputStream input = new FileInputStream(file);
final OutputStream output = fileItem.getOutputStream();

IOUtils.copy(input, output);

IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);

return fileItem;
}





1. In method createFileItem I created a dummy file to send as parameter to my validate method . In test methods I am using
two differen files test.txt and test.jpg as my validtor allows only media file so test.txt is to check the failing criteria.

2. to check error.rejectValue in junit I have used assertEquals . It conatins 2 parameters first is the String and other one is the
value set in Errors object by validator .errors.getFieldError("date") in this the fieldName date is same as given in validator for errors.setrejectValue.


I hope this post helps .If someone has a better code or enhancements that can b done please comment below or also write a mail to admin@javainhouse.com

HashMap Internal Working - Java

Hashmap working in java

   Hashmap class is equivalent to hashmap besides two things that they are unsynchronized any permits null value.

So what is hashing ?

Hashing means that you use a function or method or algorithm to represent an object with an integer value which makes finding that element quite easy in a storage that can be hashtable ,hashmap or anything that is using hash technique.

Hashmap

Hash map is a collection in which the elements are stored as key-value pair and each element stored is known as an Entry object .
Entry object is an object of  a class named as Entry class which contains :
1.key
2.value.
3.next
4.hash

Now we will look how actually hashmap works and how values are stored in hashmap and retrieved from it?
There are main  methods used for storing and retereiving values from hash map

1.    put() method Ã  to put /store values in hashmap
2.    get() methodàto retrieve data/values from hasmap

Values above means objects not the actual value .
Besides these two methods two more methods plays a vital role in working of hasmap

hashcode()

equals()

Both these methods are defined in Object class only .
Now let us assume we have a map and we put some elements inside it

 HashMap<string,string> countryCapitalMap=new HashMap<string,string>();

        countryCapitalMap.put(india,"Delhi");

        countryCapitalMap.put(japan,"Tokyo");

       countryCapitalMap.put(france,"Paris");

        countryCapitalMap.put(russia,"Moscow");


So in the above example we have 4 entry objects with 4 key –value pair.

Now we are using put () method to add these objects to a hashmap name countryCapitalmap.
Let look inside code of put() method

 public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
 
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


First ,hashcode method calculates hashcode of key .
This hashcode actually indicates the index of array which stores entry objects.
The objects are stored in a single link list corresponding to each index which is also konwn as bucket
If two keys have same hashcode that means they will stored on the same index but in the same bucket or linked list .

Let us assume that we have four values in our hashmap.




        countryCapitalMap.put(india,"Delhi");

        countryCapitalMap.put(japan,"Tokyo");

       countryCapitalMap.put(france,"Paris");

        countryCapitalMap.put(russia,"Moscow");



And assume that hascode calculated on each key comes as
                                           India ->0
                                           Japan ->0
                                           France->1
                                           Russia ->2
                                           China->2



hashmap Internal working
Hashmap Internal working


By default the size of hashmap is 16 that means there will be 16 buckets and 16 indexes .Here I have shown only 5.
Each node of a link list stores an Entry object which conatins following things




Key
Value
Next
hash










Above for illustration purposes I have shown only key.


So as india’s hashcode comes as 0and japan’s also 0 ,so the entry object corresponding to india will be stored in first node of linked list at 0 index and as entry object corresponding to japan also have same hashcode so it will stored in the next node to india and next pointer of india will point to japan’s entry object.


You will be confused that when hashcode of both keys is same then the value of india entry object should be replaced no but when hashcode of two entry objects Is same at that time equals() method comes into play .when we have to store key with same hashcode then first equals method checks whether the key for which value is to be stored and the key which is already present in hashmap is same ,if both are same then the value in entry object  is replaced by new value otherwise a new node is created and the new entry object( japan in our case) is stored.

Working of Get method in hashmap

Get method in hashmap is used to retrieve value from hashmap corresponding to a key.


Code of method get () of HashMap:

public V get(Object key) {

20
  if (key == null)

21
   return getForNullKey();

22
  int hash = hash(key.hashCode());

23
  for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e =     e.next) {

24
   Object k;

25
   if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

26
    return e.value;

27
  }

28
  return null;

29
 }

First, same as put method , hashcode of key is calculated .
Then according to hashcode the index in array means index of bucket in which value/entry object is stored.
If there is only one node in the bucket/link list then the value is retrieved from that node.
If there are more than one node in the linklist then  equals() method comes into play .equals( ) methods traverse the list and compare value of each key present in bucket with the one for which we have to retrieve value  and retrieves value from entry object .


Author : Himanshu Bector

Android Studio Calculator Example

Hi , Now I am moving towards new Program that is Android Studio Calculator , a very basic calculator which will look as below :

Calculator Example Android Studio
Android Studio


Step 1 : Create a new project named as Android Studio Calculator Example 


Calculator Example Android Studio
Android Studio

Step 2 : activity_main.xml


Now , add one textview to show output .
In two textview with text as First no. and other Second no. 
Two editview to enter no.s
Four buttons as ADD,SUB,MUL and DIV

Below is the code for activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:weightSum="1"
        android:background="#fff9fdff">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text=""
            android:id="@+id/textView1"
            android:visibility="visible"
            android:autoText="true"
            android:background="#fffffad9" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="@android:dimen/app_icon_size"
            android:layout_weight="0.19">


            <TextView
                android:layout_width="10dp"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="First No."
                android:id="@+id/textView2"
                android:layout_weight="0.09" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/editText1"
                android:layout_weight="0.09" />



            <TextView
                android:layout_width="10pt"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Second No."
                android:id="@+id/textView3"
                android:layout_weight="0.09" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/editText2"
                android:layout_weight="0.09" />
        </LinearLayout>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ADD"
            android:id="@+id/button1"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SUB"
            android:id="@+id/button2" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MUL"
            android:id="@+id/button3" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="DIV"
            android:id="@+id/button4" />
    </LinearLayout>

</RelativeLayout>