```
public int nextGreaterElement(int n) {
String nu = "" + n;
char[] num = nu.toCharArray();
int len = nu.length();
int i = len - 1;
while(i > 0 && num[i] <= num[i - 1]) i--;
if(i == 0) return -1;
int j = len - 1;
while(num[j] <= num[i - 1]) j--;
char save = num[i - 1];
num[i - 1] = num[j];
num[j] = save;
Arrays.sort(num, i, len);
String res = new String(num);
if(Long.parseLong(res) > Integer.MAX_VALUE) return -1;
return Integer.parseInt(res);
}
}
```

the algorithm used for this question is same as next permutation, but overflow must be considered for this question.