Why it gives an error?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why it gives an error??

import java.util.Arrays; import java.util.Scanner; class Main{ int[]arr=new nextint[3]; public static void main(String args[]){ for(int i=0;i<3;i++){ arr[i]=i; } System.out.println(arr[1]); } System.out.println(arr[1]); }

29th Aug 2021, 1:54 PM
Shruti Shukla
Shruti Shukla - avatar
7 Answers
+ 4
Shruti Shukla 1 - Because you cannot directly print inside Class, you need method. 2 - initialisation of array is wrong, there should be int instead of nextint. nextInt is a method of scanner class. 3 - You can't call any non-static things inside static method so make arr static So here is your solution with explanation: https://code.sololearn.com/cpxKfSJOuzD1/?ref=app
29th Aug 2021, 2:22 PM
A͢J
A͢J - avatar
+ 2
Martin Taylor ,i am not learning java from this app
29th Aug 2021, 3:26 PM
Shruti Shukla
Shruti Shukla - avatar
+ 2
The problem is that the "println" method is static, so it can only be called in a static context like the "main" method.
30th Aug 2021, 10:32 PM
Augusto Hernandez
Augusto Hernandez - avatar
+ 1
import java.util.Arrays; import java.util.Scanner; class Main{ int[]arr=new nextint[3]; public static void main(String args[]){ for(int i=0;i<3;i++){ arr[i]=i; } System.out.println(arr[1]); } System.out.println(arr[1]); }
29th Aug 2021, 2:07 PM
Shruti Shukla
Shruti Shukla - avatar
+ 1
Aj-soloHelper ,in your code what do you means by this line -Main m=new Main()?
29th Aug 2021, 3:15 PM
Shruti Shukla
Shruti Shukla - avatar
+ 1
Shruti Shukla Creating object of Main class. Whenever you create an object of the class, constructor will automatically invoke and printed value inside constructor will be print on terminal.
29th Aug 2021, 3:40 PM
A͢J
A͢J - avatar
+ 1
Shruti Shukla this ( Main m = new Main(); ) this is called object creation may be you are new in java . But when you creating any class and you compiling it by default constructor calling at a time of object . Constructor name is always same as class name here class name is Main so constructor is also with same same Main() this is non parameterized constructor . And the purpose is to initialize the object. Once try to make simple class program and create one object and run your file via command line. Then type javap your java file name and press enter you can see default constructor.
29th Aug 2021, 6:39 PM
A S Raghuvanshi
A S Raghuvanshi - avatar