+ 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); } }

16th Aug 2016, 12:50 PM
rajat kumar raicha
rajat kumar raicha - avatar
6 Respuestas
+ 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.
16th Aug 2016, 1:34 PM
James
James - avatar
+ 1
above coding shows error. my point what just happens when no initialization is done.
16th Aug 2016, 1:04 PM
rajat kumar raicha
rajat kumar raicha - avatar
+ 1
thanks for the help. well explained james
16th Aug 2016, 2:39 PM
rajat kumar raicha
rajat kumar raicha - avatar
0
yust initialis ut with 0 and check if the error still appears
16th Aug 2016, 1:14 PM
Eric Zeus
Eric Zeus - avatar
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
16th Aug 2016, 1:35 PM
मृदुल चन्द्र श्रीवास्तव
मृदुल चन्द्र श्रीवास्तव - avatar
- 1
for int nothing only complex objeckts needs to be initialiesed.
16th Aug 2016, 1:02 PM
Eric Zeus
Eric Zeus - avatar