What is a flag in java?
when do we need it in our program?
what it is used for?

Recommended Answers

All 9 Replies

bit little information to go on. can you put it in a context?

class PrimeNo{
    public static void main(String args[]){
        int num = Integer.parseInt(args[0]);
        int flag=0;
        for(int i=2;i<num;i++){
            if(num%i==0)
            {
                System.out.println(num+" is not a Prime Number");
                flag = 1;
                break;
            }
        }
        if(flag==0)
            System.out.println(num+" is a Prime Number");
    }
}

what is the flag doing here? what is its function?

It's rubbish coding by someone who hasn't heard of boolean variables.
Replace it by a boolean called numberHasADivisor, initially false, set true on line 9, and all should become obvious.

James .. can u type the complete code for me bro?

Just this one time...
I just replaced the stupid int with a boolean, and gave it a meaningful name. If this code still isn't clear then add some print statements to show how the values of the main variables change, and execute it yourself.

class PrimeNo{
    public static void main(String args[]){
        int num = Integer.parseInt(args[0]);
        boolean numberHasADivisor = false;
        for(int i=2;i<num;i++){
            if(num%i==0)
            {
                System.out.println(num+" is not a Prime Number");
                numberHasADivisor =  true;
                break;
            }
        }
        if(! numberHasADivisor)
            System.out.println(num+" is a Prime Number");
    }
}
commented: really good... +2

i m having an exception of "arrayoutofbounds" ?
now what ??

int num = Integer.parseInt(args[0]);

... is the only array referred to, so there's the problem (the exception message will have told you that line number). It's trying to access the first element of the array of args, and that array is empty, so the index is "out of bounds". args is an array containing all the arguments passed to the program when it was invoked. It's in the signature of the mandatory "main" method.
It's expecting you to pass in a number as a runtime parameter/argument - that's the number it tests for being prime.
I'll leave you to find out how to pass a runtime parameter.

so ... you don't know how to use booleans, you don't know how to use command line parameters and you don't know what an arrayoutofboundsexception is.
don't go reading code, first start reading up on the basic concepts.

for that you have to pass commandline argument(input as a command line argument) when you are executing it like " java filename args[0]" this from command prompt.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.