This should be the exact same logic but in java.