+ 1
what just happens when i dont initilise the sum variable ?plese explain
public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }
6 Answers
+ 4
Any variable created inside a method, including main, is called a local variable. A local variable, does not get a default assignment like a non local variable. Standard int variable, would be default 0, but since your sum is a local variable, you have to initialize it. If you don't want to, place the variable outside the method. Like so:
public class Program {
static int sum;
public static void main(String[] args) {
int [ ] myArr = {6, 42, 3, 7};
for(int x=0; x<myArr.length; x++) {
sum += myArr[x];
}
System.out.println(sum);
}
}
We use static because it's being used in a static method.
+ 1
above coding shows error. my point what just happens when no initialization is done.
+ 1
thanks for the help. well explained james
0
yust initialis ut with 0 and check if the error still appears
0
hey Friends being very pleased of you if any one tell me about how to unicode HINDI pdf file ....
is that works there ....
pls don't laugh I am series about it ,
I didn't find it for last 2 weks...😢 help me what to do
- 1
for int nothing only complex objeckts needs to be initialiesed.