java beginner "Hello World" -
i trying learn java
i dont understand why code won't work.
it won't output "hello world" test() function.
what doing wrong?
public class main { public test(args) { system.out.println(args); } public static void main(string[] args) { test('hello world'); } }
firstly:
public test(args) { system.out.println(args); }
you need type go parameter - java typed language , need specify type. type here, system.out.println()
can take anything, set type string, object or whatever (since object has tostring()
method , has lots of overloads deal primitives.) bear in mind unusual though, of methods come across take of specific type!
since you're calling test main method here, , you're passing string it, may set type of args string.
the second problem there's no return type specified. need specify return type, in case nothing returned type void
. if don't compiler has no way of knowing whether wrote meant method or constructor.
the third problem test instance method you're calling statically. test() needs static well, otherwise belongs instances of main , not main class. why matter? well, there potentially thousands of instances of main, instance should method run on? compiler has no way of knowing.
next:
public static void main(string[] args) { test('hello world'); }
you're passing string here, needs in double quotes. java treats quotes differently php, single quotes used single character literals , double quotes used strings. can never enclose string in single quotes this, has double.
putting together:
public class main { public static void test(string args) { //add return type , parameter type, make test static system.out.println(args); } public static void main(string[] args) { test("hello world"); //change single quotes double quotes } }
Comments
Post a Comment