user622378 user622378 - 4 months ago 8
Java Question

java beginner "Hello World"

I am trying to learn Java

I dont understand why this code won't work.

It won't output "Hello World" from test() function.

What am I doing wrong?

public class Main {

public test(args) {
System.out.println(args);
}

public static void main(String[] args) {
test('Hello World');
}
}

Answer

Firstly:

public test(args) {
    System.out.println(args);
}

You need a type to go with a parameter - Java is a strongly typed language and thus you always need to specify a type. As to what the type is here, System.out.println() can actually take anything, so you could set the type to String, Object or whatever you like (since Object has a toString() method and it has lots of overloads to deal with all the primitives.) Bear in mind this is unusual though, most of the methods you come across will just take something of a specific type!

Since you're only calling test from the main method here, and you're passing a string to it, you may as well set the type of args to String.

The second problem with this is that there's no return type specified. You always need to specify a return type, in this case nothing is returned so the type is void. If you don't do this then the compiler has no way of knowing whether what you wrote was meant to be a method or a constructor.

The third problem is that test is an instance method but you're calling it statically. test() needs to be static as well, otherwise it belongs to instances of Main and not the Main class. Why does this matter? Well, there could potentially be thousands of instances of Main, so what instance should the method run on? The compiler has no way of knowing.

Next:

public static void main(String[] args) {
    test('Hello World');
}

You're passing a string here, which needs to be in double quotes. Java treats quotes differently to PHP, single quotes are used for single character literals and double quotes are used for strings. So you can never enclose a string in single quotes like this, it has to be double.

Putting it all together:

public class Main {

    public static void test(String args) { //Add return type and parameter type, make test static
        System.out.println(args);
    }

    public static void main(String[] args) {
        test("Hello World"); //Change single quotes to double quotes
    }
}
Comments