I would go a different way as i assume, OP is new to logic programming(from his/her question pattern).
Here we are traversing through the length of a word and backtracking them while printing i mean reversing. Have a look at it.
String str = "java";
String revStr = reverseWordByWord(str);
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}