I was trying to call the main function inside the main function i have tried the following code and got successfully compiled code.
class test
{
static int i = 0;
public static void main(String args[])
{
String asda[] = {"!2312"};
if (++i == 1)
main(asda);
}
}
But the error occurs in case of the following code:
class test
{
static int i = 0;
public static void main(String args[])
{
if (++i == 1)
main({"!2312"});
}
}
this made me so confused. the confusion is that String array initialization is done like String A[]={"asdf","Asdf"); then why is it giving an error in the second case?
I'm using java 8u40.
The syntax for what you're looking for is:
main(new String[]{"!2312"});
In your first example, Java is smart enough to know that you're creating a String array, since it's in the String[] declaration part. But since you don't have that in your second example, Java isn't smart enough to know that's a String array, or an array of Objects. So you need to specifically tell Java that it's a String array by including the String[] part.
Edit: I will also note that you could use varargs instead of an array as the argument to your main() method:
public static void main(String... args){
And then you can call your main() method with a String literal instead of an array, just like this:
main("!2312");
Your whole program might look something like this:
public class Main{
static int i = 0;
public static void main(String... args){
if (++i == 1){
main("!2312");
}
}
}
That's slightly outside your question, but it might be useful for you to know.
The problem with literals like {"!2312"} is that they do not have type information. E.g., Java has no way of knowing if you mean a String[] with one value or an Object[] with one value. You need to explicitly specify it, either by initializing a variable:
String asda[]={"!2312"};
if(++i==1)
main(asda);
or by calling the new operator:
if(++i==1)
main(new String[]{"!2312"});
In the previous code when you passed asda to main through
main(asda);
asda was an array but {"!2312"} is not an array and the main method accepts string arrays as specified in the declaration
public static void main(String args[])
where args is an array. So you should pass an array to main.
Create an array then place that string literal in it and then pass it to main.
Related
Can some one tell , why args in main method are of String type . in
public static void main(String args[]){
}
I mean, why it is not int or float or something else. I was asked the same but could not find appropriate answer.
You might run your java program with parameters through console like this:
java YourClass first second third
In the java program you may use it through String args[].
public static void main(String[] args) {
Arrays.asList(args).forEach(System.out::println);
}
Output:
first
second
third
But it is not necessary to use such name. There are few ways to declare signature of the main method:
public static void main(String... args)
public static void main(String[] strings)
public static void main(String [] args)
Why it is not int or float or something else? At the command prompt the command is considered to be a string.
I will give you my inputs.
Command line arguments are Strings which is why that is the data type.
You can get other datatypes easily from Strings.
Most of Java's syntax is based on C, and since C used String args, maybe the creators did the same for java. (Just a possibility)
when we write java filename.java that means you giving your filename to java compiler whose main method is to be called it is obvious that the file name you are giving will be a string.
on the other end if you want to give any parameter to compiler at the same time it will also be in string not an integer or any other data type.
Because String can be converted to any type easily. If it were int and you want to take double as input, how would this happen? But with String, you can convert to whatever you expect.
Is it possible that public static void main(String[] args) in java returns String instead of void? If yes, how?
public static String main(String[] args)
instead of:
public static void main(String[] args)
when I change my code as below:
public static String main(String[] args) throws IOException {
String str = null;
TurkishMorphParser parser = TurkishMorphParser.createWithDefaults();
str = new Stm(parser).parse("bizler");
System.out.println("str = " + str);
String replace = str.replace("[","");
String replace1 = replace.replace("]","");
List<String> result1 = new ArrayList<String>(Arrays.asList(replace1.split(",")));
String result = result1.get(0);
System.out.println("Result = " + result);
return result;
}
I receive this error:
Error: Main method must return a value of type void in class Stm, please define the main method as:
public static void main(String[] args)
In short - no, it can't.
You can always print to stdout from the main method (using System.out.print or System.out.println), but you can't change the return type of main.
The main method's return type must be void, because the java language specification enforces it. See 12.1.4.
For interprocess communication you can either use:
System.in and System.out
Sockets
No you can't... once the main is finished the program is dead.. So you don't have any benefit from that.. What is you purpose? What you are trying to achieve?
You can wrap all in other method that will return String to your main.
public static void main(String[] args) throws IOException {
String result = doSomething();
return result;
}
public static String doSomething() {
String str = null;
TurkishMorphParser parser = TurkishMorphParser.createWithDefaults();
str = new Stm(parser).parse("bizler");
System.out.println("str = " + str);
String replace = str.replace("[","");
String replace1 = replace.replace("]","");
List<String> result1 = new ArrayList<String>(Arrays.asList(replace1.split(",")));
String result = result1.get(0);
System.out.println("Result = " + result);
}
Yes you can but you can't run that class. You will get error
class Test {
public static String main(String[] args) {
return "1";
}
}
You will get error as
Error: Main method must return a value of type void in class Test, please
define the main method as:
public static void main(String[] args)
No. The to be a main() method, it must return nothing (ie be void).
However, you could refactor your code if you need the functionality of your method returning something:
public static void main(String[] args) throws IOException {
myMain(args);
}
public static String myMain(String[] args) throws IOException {
// your method, which can now be called from anywhere in your code
}
This is a very interesting scenario. While in general, we can change any method which is returning void to return anything else without much impact, main method is a special case.
In earlier programming languages, the return from main method was supposed to return exit values to the OS or calling environment.
But in case of Java (where multi-threading concept case into picture), returning a value from main method would not be right, as the main method returns to JVM instead of OS. JVM then finishes other threads e.g. deamon threads (if any) and performs other exit tasks before exit to OS.
Hence allowing main method to return, would have lead to a false expectation with the developers. hence it is not allowed.
Yes, it's definitely possible. That is, you can define a method public static String main(String[] args). It's just like defining any other method.
However, it won't be a main method despite its name, and thus won't be run when executing a program like a main method would. Quoting Java language specification, §12.14:
The method main must be declared public, static, and void.
Emphasis mine. You can't have non-void main methods in Java.
If you really, really need it to return something (which you don't), assign the output to a static variable. Then you won't need to return. i.e
static String a = "";
public static void main(String[] args){
//do sth
a = "whatever you want";
}
Now you have String a, use it whereever you want to use but I don't see any usage for this.
Answer is no.
When the program is run, the JVM looks for a method named main() which takes an array of Strings as input and returns nothing (i.e. the return type is void). But if it doesn't find such a method ( the main() method is returning String for example ) so it throws a java.lang.NoSuchMethodError
Before java, in C or C++, main function could be declared int or void. Why? Because main method is invoked by OS which is not responsible for the successful/unsuccessful execution of program. So, to let the OS know that the program executed successfully we provide a return value.
Now, in java, program is loaded by OS, but the execution is done by JRE. JRE itself is responsible for the successful execution of program. So, no need to change the return type.
It will be like telling your problems to god, when god himself is giving you problems to solve them.
;)
This question already has answers here:
Can a main method in Java return something?
(6 answers)
Closed 8 years ago.
class Half {
public int evaluate(int arg) {
return arg/2;
}
}
public class Box {
public static int [] main (int[] arrIn) {
int[] arrOut = new int[arrIn.length];
Half func = new Half();
for (int i=0; i< arrIn.length; i++)
arrOut[i] = func.evaluate(arrIn[i]);
return arrOut;
}
}
So contents of arrOut are the elements in arrIn divided by two.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah)
Is there any way to take direct integers as arguments?
Secondly the above code gives an error.(Obviously)
Error: Main method not found in class Box, please define the main method as:
public static void main(String[] args)
Which brings me to my next question.
Should it always be public static void main(String[] args)? Can't it be public static int main with some arguments other than string type?(Don't explain the static part.. As per my understanding main method needs to be invoked without an object which is why it is static. but if it is forced(somehow) to return an integer, where will it return it?(I mean to which method? or will it directly print to the screen?)I know it doesn't print to the screen (duh!) but then where is the control returned basically after main method finishes execution?
Should it always be public static void main(String[] args)?
Yes, if you want it to act as an entry point.
Can't it be public static int main with some arguments other than string type?
No. Section 12 of the JLS explains JVM start-up, and includes this in 12.1.4:
Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
Basically, the only bits which are optional are:
The name of the parameter
Whether you make it a varargs parameter or not
You can overload the method if you want, providing extra main methods with different parameter types and possibly a return value - but only the void one with a String[] parameter will be treated as an entry point.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah) Is there any way to take direct integers as arguments?
No. You have to do it yourself. It's pretty trivial though:
int[] integers = new int[args.length];
for (int i = 0; i < args.length; i++)
{
integers[i] = Integer.parseInt(args[i]);
}
First thing first:
This must always be public static void main(String[] args)
Second to read integer directly, use:
Scanner in = new Scanner(System.in);
int num = in.nextInt();
I have errors when I run program(1). But when I used program(2), writing 0 after a, it run and produced the correct output. Writing 0, is just my guess and somehow it worked. Why is that?
Program (1):
public static void main(String[] args) {
System.out.println(a);
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
Program (2):
public static void main(String[] args) {
System.out.println(a(0));
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
}
You wrote the function in such a way that it requires a parameter. To call a function that requires a parameter, you have to supply one. That's why the second program worked--you gave the function a a parameter of 0.
To make the first program work, then, you have two options. The first is what you did--supply the required parameter for the function. The second is to modify the function declaration so it does not require a parameter, changing
private static int a(int len) {
to
private static int a() {
public static void main(String[] args) {
System.out.println(a);
}
private static int a(int len) {
String s = "What";
len = s.length();
return (len);
}
The problem here is that a is a function which receives a single integer parameter. This code is therefore a compilation error:
System.out.println(a);
You cannot print a function. What you can do is call a function and print that function's return value. Which is precisely what your second chunk of code does.
However, since your function a ignores its input parameter, you could re-write the code like this:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
int len = s.length();
return len;
}
Note that you still need to call the function using parentheses, a(). But because there is no longer a parameter required, you can leave the parameter list empty.
(Note: this really has nothing to do with the string length part. It's just simple method calling.)
Well look at this code:
public static void main(String[] args) {
System.out.println(a);
}
That's trying to use a as if it's a variable - it's not, it's a method. So you want to invoke that method, and use the return value, which is what you do in your second version.
Admittedly it's pretty odd to pass in an argument and then not use it, and likewise you've got unnecessary parentheses around your return value - return isn't a method call.
So your code can be simplified to:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
return "What".length();
}
Or if you really want the local variable:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
return s.length();
}
You seem to be confusing method parameters with normal variable declarations. You've written a as a method that takes a single int parameter, so you need to pass it a value; but you don't actually use that value in the body of the function.
You probably really want to use a local variable, and not pass a parameter at all, e.g.:
public static void main(String[] args) {
System.out.println(a());
}
private static int a() {
String s = "What";
int len = s.length();
return (len);
Note that you still need to write a() in the call, not just a, to make clear that it is a method call.
The first code can't compile as you are trying to output a variable a that has not been declared (this syntax is not a method call). In the second one you are actually calling the static method a that exists, so it runs.
a is a function not a variable. You cannot call a function without the paranthesis...
you would have to type in a() to call the function.
Now, what happens in the first case is, since there are missing paranthesis it tries to resolve it as a variable and errors out.
The second case is where you call the function in the correct fashion
You need to read up on how to make method calls. This is one of the most basic things you will be doing in java.
When you want to call method a, you need to pass the correct number of arguments(in this case a single int) or the method call will not be recognized and be an error. What IDE are you using to develop your java code? If you are using something like Eclipse you shouldnt even be able to run the code with this error present.
Your function a is defined as a function that takes a single argument, which is named len. When you call it as a(0), you provide that argument and everything works just fine. When you call it as a, you do not provide that argument and compilation fails. The code never runs.
The question is: why have you defined a to take an argument? It isn't used: its value is immediately overwritten with the result of s.length().
It seems like you are attempting to declare a local variable for use by mentioning it in the function signature. That does is not necessary, and does not work, in Java.
I'm currently working on a school project in Eclipse (We have just started using this) and we are running into a small hickup: Because we used BlueJ before, we did not have any main method, we added one but ran into a problem.
We have to send an Int value in the parameter instead of a String[] with args, we tried
public static void main(Int[] args)
This results in the following error:
Error: Main method not found in class Tester, please define the main
method as: public static void main(String[] args)
I'm wondering what we should do/change to get this to work.
Have a look into Integer.parseInt("123"),
see http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29
I hope you'll figure out the rest :)
Java will look for public static void main(String[] args).
You will have to pass the integer value as a String and parse it.
Here is a link to the documentation for Integer.parseInt(String).
As others have said, you cannot change the signature of the main method. To obtain an integer from the String parameters use:
public static void main(String[] args) {
int first = Integer.parseInt(args[0]); // use whatever index you need
}
Just like the error says, the main method that will be invoked when you execute the class must have the signature public static void main(String[] args). You can't just give it different arguments.
If you pass numbers as arguments on the command line, they will be read in as strings by Java. If you want to convert them to a numeric type, you must do so explicitly in your code.
Try sending your integer in the String array.
new String[]{"1"}
Then fetch it:
Integer yourInteger = Integer.valueOf(args[0])
You need to pass your value as a String then parse it as an Integer.
Look this sample of code :
public static void main(String[] args) throws Exception {
int value = Integer.parseInt(args[0]);
System.out.println("My int value: " + value);
}
You need to protect the parseInt with try catch for error management, if parameter is not parsable.
Just pass in a string, and then use Integer.parseInt(string) to get the integer you need back.
write a main method like below
public static void main(String[] args){
}.
and use Integer.parseInt(str)
You must leave the main method as follows:
public static void main(String[] args){
//....
}
As you indicate the error. Now, in the main method can change the type of the arguments to integers.
public static void main(String[] args){
int arg0=Integer.parseInt(args[0]);
int arg1=Integer.parseInt(args[1]);
//... etc.
}
Regards!
This class will print out the integers you put in on the command line:
public class IntegersFromCommandLine
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++)
{
System.out.println(Integer.parseInt(args[i]));
}
}
}
If you give it the command line arguments 1324 21 458 9564 1 0 -789 40, it will give the following output:
1324
21
458
9564
1
0
-789
40
The signature of the main method cannot be changed. This is a constraint of the operating system.
Just parse the String into an integer via Integer.parseInt(...), then invoke the actual method!