This is a real exercise in efficiency. Stay away from variable declarations, trick parseInt to convert strings and test using OR not AND.

public String Problem () { int P [] = new int [5]; int sum = 0; for (int i = 2; i < primeLimit; i++) isP[i] = true; for (int p = 2; p*p < primeLimit; p++) if (isP[p] == true) for (int m = p*p; m < primeLimit; m = m+p) if (m % p == 0) isP[m] = false; mainLoop: for (P[0] = 3; P[0] < testLimit; P[0] = nextP(P[0])) { for (P[1] = nextP(P[0]); P[1] < testLimit; P[1] = nextP(P[1])) { if (!isP[Integer.parseInt(P[0] + "" + P[1])] || !isP[Integer.parseInt(P[1] + "" + P[0])]) continue; for (P[2] = nextP(P[1]); P[2] < testLimit; P[2] = nextP(P[2])) { if (!isP[Integer.parseInt(P[0] + "" + P[2])] || !isP[Integer.parseInt(P[1] + "" + P[2])] || !isP[Integer.parseInt(P[2] + "" + P[0])] || !isP[Integer.parseInt(P[2] + "" + P[1])]) continue; for (P[3] = nextP(P[2]); P[3] < testLimit; P[3] = nextP(P[3])) { if (!isP[Integer.parseInt(P[0] + "" + P[3])] || !isP[Integer.parseInt(P[1] + "" + P[3])] || !isP[Integer.parseInt(P[2] + "" + P[3])] || !isP[Integer.parseInt(P[3] + "" + P[0])] || !isP[Integer.parseInt(P[3] + "" + P[1])] || !isP[Integer.parseInt(P[3] + "" + P[2])]) continue; for (P[4] = nextP(P[3]); P[4] < testLimit; P[4]= nextP(P[4])) { if (!isP[Integer.parseInt(P[0] + "" + P[4])] || !isP[Integer.parseInt(P[1] + "" + P[4])] || !isP[Integer.parseInt(P[2] + "" + P[4])] || !isP[Integer.parseInt(P[3] + "" + P[4])] || !isP[Integer.parseInt(P[4] + "" + P[0])] || !isP[Integer.parseInt(P[4] + "" + P[1])] || !isP[Integer.parseInt(P[4] + "" + P[2])] || !isP[Integer.parseInt(P[4] + "" + P[3])]) continue; System.out.format("P[0]:%d P[1]:%d P[2]:%d P[3]:%d P[4]:%d\n", P[0],P[1],P[2],P[3],P[4]); sum = P[0]+P[1]+P[2]+P[3]+P[4]; break mainLoop; } } } } } return String.valueOf(sum); } public int nextP (int P) { P++; while (isP[P] == false) P++; return P; }