Searching for duplicates without any collection or sorting I have written code which is easy to understand, but may not be efficient but will solve the purpose.

public static void main(String a[]){
        int ar[] ={1,2,3,4};
        boolean flag=false;
        int count=0;
        while(count&lt;ar.length){
            for(int i=0;i&lt;ar.length-1;i++){
                if(ar[count]==ar[i+1] &amp;&amp; count !=i+1){
                    flag=true;
                }
        }
            count++;
        }
        if(flag){

        System.out.println("Duplicate Exists in Array!");
        }else{
            System.out.println("Duplicates Doesn't Exists in Array!");
        }

    }
As you may be aware, your solution takes O(n2) time.  Sorting can bring that down to O(n log n).  Hashing can produce an O(n) solution.  Of course, for a four-element array, performance isn't an issue at all.



Please take care to indent your code consistently.



This kind of loop structure…

int count = 0;
while (count &lt; ar.length) {
    …
    count++;
}


… is more easily recognizable when written as a for-loop:

for (int count = 0; count &lt; ar.length; count++) {
    …
}


Once you do that, you'll see nested for-loop, which is easier to understand:

for (int count = 0; count &lt; ar.length; count++) {
    for (int i = 0; i &lt; ar.length - 1; i++) {
        if (ar[count] == ar[i + 1] &amp;&amp; cont != i + 1) {
            flag = true;
        }
    }
}


But you are inspecting almost every pair of elements twice.  Typically, the inner loop limits are written to avoid half the work:

for (int i = 1; i &lt; ar.length; i++) {
    for (int j = 0; j &lt; i; j++) {
        if (ar[i] == ar[j]) {
            // Duplicate found!
            …
        }
    }
}




Variables named flag (or that act as a flag) are usually a bad idea, because they express your intentions indirectly.  In the case of duplicate element detection, once you've found a single duplicate, you're all done.  There should be a break, or better yet, a return:

public static boolean duplicateExists(int[] ar) {
    for (int i = 1; i &lt; ar.length; i++) {
        for (int j = 0; j &lt; i; j++) {
            if (ar[i] == ar[j]) {
                return true;
            }
        }
    }
    return false;
}

public static void main(String[] args) {
    int[] ar = …;
    System.out.println(duplicateExists(ar) ? "Duplicate exists in array!"
                                           : "No duplicates in array!");
}