Q:

!= is not funtioning properly in while loop

import java.util.Scanner;

class piglatin{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("enter a string");
        String s=in.nextLine(),n1="",n2="",n3="";
        int i;
        for(i=0;i<s.length();i++){
            if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='o'||s.charAt(i)=='i'||s.charAt(i)=='u')
                while (s.charAt(i)!=' '&& i!=s.length()){     // hre lies the problem
                    n1+=s.charAt(i);
                    i++;
                }
            else if(s.charAt(i)==' '){
                n2="";
                i++;
            }
            else
                n2+=s.charAt(i);

            n3=n3+n1+n2+"ay ";

        }
        System.out.println(n3);
    }
}

here when i matches the value of length the loop should break but it always show outofbounds exception. what is my mistake i have used && and the gateway should give false && true = false
please help

A:

On your last iteration while (s.charAt(i)!=' '&& i!=s.length()){
It tries to grab s.charAt(i) causing an IndexOutOfBounds, because i = length meaning that is one value to high for the size of the array.
If you check the size first it will evaluate to be not true because i = length so you will never reach the s.charAt(i) because the first evaluation will not be true, thus never throwing the exception. This is called short circuiting.

