code to calculate factorial of a number using string handling in java. Here String is used to hold the number instead of other data type like int having size constraint, to make it possibel to calculate factorial of large numbers also.
import java.util.*; class CC { public static void main(String args[]) { String str=new String(args[0]); //str1 is the number 1 less than input number. String str1=new Integer(Integer.parseInt(str)-1).toString(); while(Integer.parseInt(str1)>=1) { int l=str.length(); int l1=str1.length(); String comp[]=new String[l+1]; // to multiply every digit of str1 with str for(int i=l1-1; i>=0; i--) { StringBuffer intrb=new StringBuffer(""); int y=0; for(int j=l-1; j>=0; j--) { int x=(Integer.parseInt(str.substring(j,j+1))*(Integer.parseInt(str1.substring(i,i+1))) )+y; if(x/10!=0) { y=x/10; } else y=0; String intr=new Integer(x).toString(); char ch[]=intr.toCharArray(); intrb=intrb.insert(0,ch); } for(int w=0; w<l1-i-1; w++) intrb.append("0"); comp[i]=intrb.toString(); } String revrs[]=new String[l+1]; for(int t=0; t<l1; t++) { revrs[t]=(new StringBuffer(comp[t]).reverse()).toString(); } int ln=comp[0].length(); for(int e=0; e<l1; e++) { int f=ln-revrs[e].length(); for(int g=0; g<f; g++) { revrs[e]=(new StringBuffer(revrs[e]).append("0")).toString(); } } String carry[]=new String[ln+1]; String sum[]=new String[ln+1]; int sm=0; int cr=0; carry[0]="0"; int r; for(r=0; r<ln; r++) { for(int s=0; s<l1; s++) { sm+=Integer.parseInt(revrs[s].substring(r,r+1))+Integer.parseInt(carry[r]); if((sm/10)!=0) { sm=sm%10; cr=sm/10; } } sum[r]=new Integer(sm).toString(); carry[r+1]=new Integer(cr).toString(); } str1=new Integer(Integer.parseInt(str1)-1).toString(); StringBuffer sbr=new StringBuffer(""); for(int v=0; v<ln; v++) { sbr.append(sum[v]); } str=(sbr.reverse()).toString(); } System.out.println("n"+"your factorial is="+"n"+str); } }