String[] strArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; int codeCount = 4; StringBuffer code = new StringBuffer(); for(int i=0; i<codeCount; i++) { code.append(strArray[(int) (Math.random()*10)]); } System.out.println(code);