Search code examples
javapackagevoid

Package in java says void is not allowed here


this is A.java

package pack;
import java.util.*;
class A
{
    public void msg()
    {
        System.out.println("Hello");
    }
    public void add(int num1,int num2)
    {
        System.out.println(num1+num2);
    }
}

This is B.java

package pack;
class B
{
    public static void main(String[] args)
    {
        A obj = new A();
        System.out.println("30+20=" +obj.add(30, 20));
        ob.msg();
    }
}

pack\B.java:7: error: 'void' type not allowed here System.out.println("30+20=" +obj.add(30, 20)); ^ pack\B.java:8: error: cannot find symbol ob.msg(); ^ symbol: variable ob location: class B 2 errors

i keep getting this error

I have made a file named pack and added A.java and B.java inside of the file I am compiling it by ....Desktop\java class\tut4\mypackage>javac pack*.java


Solution

  • obj.add(30, 20) refers to your add method in your A.java file. The return type of this add method is void. Think it through - what does a + b mean when b is of type void? Hopefully you see why this code doesn't compile and why you get this exact error. If you don't get it - then you may need to review what void means, as evidently it's confusing you. (void means that nothing is returned - it has no value. Hence any attempt to treat it as a value, which is obviously neccessary if you want to add it to something, cannot work).