Error in Java program . | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

Error in Java program .

I had written a java code in Notepad , And compiled it through command prompt , it compiled successfully but when I trying to run it in cmd it shows : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 . How to solve this error ? import java.io.*; class Addition1 { public static void main(String args[]) { int no1,no2,add; no1=Integer.parseInt(args [0]); no2=Integer.parseInt(args [1]); add=no1+no2; System.out.print("The Addition of two number is : "+add); }} //output in cmd : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at Addition1.main(Addition1.java:7)

12th Dec 2021, 6:48 AM
Hrutik Bhalerao
Hrutik Bhalerao - avatar
8 Respuestas
+ 5
Try to run it giving two arguments e.g. java Addition1 21 21 Tell me does it work?
12th Dec 2021, 7:00 AM
Ipang
+ 6
How did you run the code? like what did you type on the console. Did you provide any argument following the filename?
12th Dec 2021, 6:52 AM
Ipang
+ 4
Happy to hear that 😁 And to anticipate such error, you can check <args>.length before trying to use any of its elements 👍
12th Dec 2021, 7:06 AM
Ipang
+ 4
Hrutik Bhalerao args is used to read data through command line so if you use it then you must have pass data otherwise you may get error. If you want to take input at runtime then use scanner object or buffer reader.
12th Dec 2021, 8:58 AM
A͢J
A͢J - avatar
+ 3
Hrutik Bhalerao You are reading arguments value so obviously it should have 2 arguments in command line because you have written args[0] and args[1] args[0] means first value of array args so if you don't provide any argument through command line then you get error.
12th Dec 2021, 8:54 AM
A͢J
A͢J - avatar
+ 2
I run it through cmd , their firstly I typed javac Addition1.java (Addition1 is the class and file name). Then it compiled successfully without any error , next I typed java Addition1 (for running ) , after this it directly showing that above error without taking any input or anything else.
12th Dec 2021, 6:58 AM
Hrutik Bhalerao
Hrutik Bhalerao - avatar
+ 2
Yes it works 😀 . It's showing 42 . Thank you for your help , first I thought that it would take input after running code in next line . Now it has cleared that input must be entered at the same time.
12th Dec 2021, 7:03 AM
Hrutik Bhalerao
Hrutik Bhalerao - avatar
+ 2
Thank you A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ sir . I recently started learning Java
12th Dec 2021, 9:13 AM
Hrutik Bhalerao
Hrutik Bhalerao - avatar