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.
;)
Related
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.
I have created an example class for my problem below.
public class testClass {
public void testMethod()
{
int testInteger = 5;
}
String testString = "Hello World" + testInteger;
}
I have an integer inside a method and a string that is in no method as seen above. I want the string to get the integer that inside the method but it cannot. Can someone please help explain why that is so and tell me how to make the string the integer. thanks.
For example:
public class testClass {
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
String testString = "Hello World" + testMethod();
}
The integer is a variable inside the method; it has scope of the method which means it can't be accessed from outside the method. The String is a field; it has scope of the class, so it can be accessed from anywhere inside the class including inside the method.
It's basic Java... the testInteger is defined in the method so not available out of the method. You could let the method return an int (being your testInteger) and call that method.
You cannot access a local variable from another method without returning it.
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
Then you can get the value by calling the method (assuming you have an instance of your class in a reference instance),
String testString = "Hello World" + instance.testMethod();
From The Java Tutorials: Variables,
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Lets break down your code to see what is going on
you have such a function
public void testMethod()
{
int testInteger = 5;
}
as you see the return type is void so nothing will be return to anywhere that is called this method.
you have this line after your testMethod
String testString = "Hello World" + testInteger;
first it looks odd why?
because you do not have any main method so I do not know how your code runs
but Imagine you have main method like this
public static void main(String[] args){
String testString = "Hello World" + testInteger;
}
second, you did not even call your testMethod in order to utilize it inside your main method
Issues
1. you did not call your testMethod at all
2. Even if you called it, it would not help you because your return type is void
3. you need main method in order your code to be ran
Remedies
1. change your return type to int
your function signature:
public int testMethod()
2. if you want to use your method, you have to use it in your main method like
for example:
String testString = "Hello World" + testMethod();
3. do not forget to have your main method because it is necessary for your code to be ran
your main method signature is
public static void main(String[] args)
I am asked to "Write a static method which, given a String as an input parameter, will return another String representing the input string with all vowels removed."
I'm not exactly sure what they mean by this. I wrote this below. What would I need to change to the answer? Thanks
public static void main(String[] args) {
String s = "Hello there";
String s1 = s.replaceAll("[AaEeIiOoUu]", "");
System.out.print(s1);
}
Check answers from #NicksTyagi and others for the static method. However, I wanted to point out that you can optimize your regex like this: (?i)[aeiouy].
(?i) is an inline flag that indicates that the part of the regex that follows it, is case insensitive. By using this flag it's not necessary to put the letters in upper case.
Feel free to remove the y from the regex if it isn't considered as a vowel in your language.
Sample code
public static String removeVowels(String input) {
return input.replaceAll("(?i)[aeiouy]", "");
}
The static method you copied and pasted into your question is called main. It's kind of special, it takes a string[] as an argument, and it always returns void. In order to complete your assignment, you need to write another static method.
First, you need to give it a name.
static myFunction() {
}
Next, give it a return (output) type. Your assignment was to return a String.
static String myfunction() {
}
Then, you need to let it accept a parameter (input) of type String.
static String myFunction(String input) {
}
Almost last, we'll add in the logic to transform the input into an output.
static String myFunction(String input) {
input = input.replaceAll("[AaEeIiOoUu]", "");
}
Finally, we need to return the output.
static String myFunction(String input) {
String output = input.replaceAll("[AaEeIiOoUu]", "");
return output;
}
Viola. You are done! You won't need to know much more about the static keyword until you study object-oriented programming. The correct definition is that static methods are bound to a class, while non-static methods are bound to an instance of a class. Here is a gruesome example.
A static method could accept a Person and return a Person with all of its arms chopped off.
I am a person. I could use my very own non-static method to remove all of my arms.
Hope that helps you remember!
The class must be as below :
public class Demo {
public static String replaceVowel(String input)
{
input = input.replaceAll("[AaEeIiOoUu]", "");
return input;
}
public static void main(String[] args) {
String output = Demo.replaceVowel("Hello World");
System.out.println(output);
}
}
You just need to create another method with the static keyword. Call this method from main.
public static void main(Strings args[]){
removeVowels("Hello World");
}
public static String removeVowels(String textWithVowels){
return textWithVowels.replaceAll("[AaEeIiOoUu]", "");
}
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!