i coded this program and had this doubt,Why the String s variable is being detected as error in the next for loop and the compiler show the error variable s might not have been initialized". Please tell me the error and how can i correct it
here is the code :
import java.util.*;
import java.io.*;
class Array
{
public static void main(String arg[])
{
int i;
String s;
for(i=0;i<5;i++)
{
System.out.println("Enter the element at position"+i+"of the array");
s=new Scanner(System.in).next();
}
for(i=0;i<5;i++)
{
System.out.println("The values of array are"+s);
}
}
}
You are trying to use the value of s in the second for loop.
Consider this general case: Your for loop runs n times (in this example, n = 5). Now, if n = 0, then there is a chance that the variable s remains uninitialized and its value is being accessed in the second for loop. (As far as Java is considered, this example is no different from any other for loop with any value for n, say n equals 0.)
So, the way to avoid this error is to properly initialize your variable. In fact, you should always properly initialize your variable.
You can do that by changing String s;
into String s = "";
PS: The above explanation only tries to clear your doubt about the variable initialization. The idea that you have tried to implement in the program does not seem logical, as you are trying to use an array of strings, and all you have actually, is just one string!
1 Like
you will have to initialize the value of “s” first, this is because java accepts a default value for the case “s” hasn’t accepted any value from user.