calling main method inside main in java - java

Can we call main method inside main?
public static void main(String[] args) {
main({"a","b","c"});
}
Tried to google.Can't find the link.
Sorry if the question is trivial

You can but using the correct format
main(new String[] {"a","b","c"});
should give StackOverFlowError (not tested)

You will get StackOverFlowError. If you call endless recursive calls/deep function recursions.
Thrown when a stack overflow occurs because an application recurses
too deeply.
You need to pass String array like
main(new String[] {"a","b","c"});

You can. And it is very much legal.
Also, it doesn't necessarily give a StackOverFlowError:
public static void main(String args[]){
int randomNum = (int)(Math.random()*10);
if(randomNum >= 8)
System.exit(0);
System.out.print("Heyhey!");
main(new String[]{"Anakin", "Ahsoka", "Obi-Wan"});
}
Just saying.

Kugathasan is right.
Yes it does give StackOverflow Exception. I tested it right now in Eclipse.
class CallingMain
{
public static void main(String[] args)
{
main(new String[] {"a","b","c"});
}
}
I have one suggestion, I think the best way to eliminate the confusion is to try coding and running it. Helps with lots of doubts.

You can simply pass the argument like main(new String[1]) - this line will call main method of your program. But if you pass "new String[-1]" this will give NegativeArraySizeException. Here I'mm giving an example of Nested Inner Class where I am calling the Main method:
class Outer
{
static class NestedInner
{
public static void main(String[] args)
{
System.out.println("inside main method of Nested class");
}//inner main
}//NestedInner
public static void main(String[] args)
{
NestedInner.main(new String[1] );//**calling of Main method**
System.out.println("Hello World!");
}//outer main
}//Outer
Output:-
inside main method of Nested class
Hello World!

Related

Why error "cannot find symbol class out" occur?

I was writing a code in which I print a statement "Hello World" but an error occur named cannot find symbol. I tried hard to remove this error but failed.
public class Input{
System.out.println("Hello World");}
This is the statement and the error
Please anyone can help me in resolving this error and tell me why this error occur so I will not repeat this mistake in future.
Use this :
public class Input {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
You can't print in the scope of a class. You need to inform more about the difference between a function and a class.
A "class" is sort of like a noun. It's the person, place or thing.
public class myThing {
//This is a comment
//put stuff that describes the thing in the curly braces
}
In order to make the thing do something, you must put it in a method
public void myMethod(){
//code in here gets run when myMethod runs
}
Methods must be in a class though. A method can usually be though of as "something a thing can do"
public class myThing {
public void myThingCanDoThis(){
//does this stuff only when called from somewhere else
}
}
The main method is a special type of method that always looks like this:
public static void main(String[] args) {
//This special method gets run automatically when your program runs
}
Your hello world should define a thing. It should have the method, or "verb", of "main".
public class myThing {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
For now just assume that all your java code must go inside of the main method. Learn the basics and then when you learn more start to pay attention to things like "public", "static", "class" , "void" etc. It will all make sense in time

How to execute a particular function before main() in C and JAVA ?

I want to execute one function before main function in C and JAVA language.
I know one way that is, by using #pragma directive in C language. Is there any other way to do that in both languages?
I can think of two simple(-ish) ways to do it in Java:
Method #1 - static initializers
For example:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
Method #2 - A proxy main.
public class ProxyMain {
public static void main(String[] args) {
String classname = args[0];
// Do some other stuff.
// Load the class
// Reflectively find the 'public static void main(String[])' method
// Reflectively invoke it with the rest of the args.
}
}
You then launch this as:
java <jvm-options> ... ProxyMain <real-Main> arg ...
There is also a 3rd method, but it requires some "extreme measures". Basically you have to create your own JVM launcher that uses a different scheme for starting the application. Have this do the extra stuff before loading the entry point class and calling its main method. (Or do something different entirely.)
You could even replace the default classloader; e.g. How to change default class loader in Java?
in java you can use static block
public class JavaApplication2 {
static {
System.out.println("in static ");
}
public static void main(String[] args) {
System.out.println("in main ");
}
}
As an extension to the C standard gcc provides the function attribute constructor which allows functions to be called before main().
For details please see here (scroll down). Also this SO question and its answers help on this.
Try combining a static block and a static method containing what you want executed before your main method.
package test;
public class Main {
static {
beforeMain();
}
public static void main(String[] args) {
System.out.println("after");
}
private static void beforeMain() {
System.out.println("before");
}
}
Output:
before
after
It could be the first thing you call from your main function. That way it will run before your "real" main function.
Use that method(what you want to run before main method) as your main method.
Then it is so simple
Or use static block before main()
In java, execution of any other method is possible before main() method execution. We need a static initializer block for that. It starts with a static keyword.
Like:
static {
// statements
}
Now try to understand with actual code implementation.
public class BefourMain {
static int sum;
static {
sum = add(4,5,6);
System.out.println("Calling add() method: " + sum);
System.out.println("\ncalling main");
main(null);
System.out.println("Main end\n");
System.out.println("Now JVM calling main()\n");
}
public static void main(String[] args) {
int sum = add(1,2,3);
System.out.println(sum);
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
Now try to understand with actual code implementation.
When we start executing this code the static initializer block will start execution first, in the static initializer block we are calling the add() method and storing the value in the static variable, and printing it. Next, we are calling the main() method, which will execute. when the static initializer block execution will complete JVM will call the main() method again.
Output
Output of the above code

Java command prompt compile error

I started learning Java lately, and trying to make my first program based on book which is the "Hello World" program.
After writing the script on notepad, i try to compile it on the command prompt and then this notice appeared.
first I type: javac javaCode.java
then there a notice said:
javaCode.java:2: error: <identifier> expected
public class static void main(string[] args) {
^
javaCode.java:6: error: reached end of file while parsing
}
^
2 errors
I don't have any ideas what going on here so please give detailed information and how to fix this thing.
public class static void main(string[] args)
Remove class
public static void main(string[] args)
class is different from method. main method syntax doesn't contain class.
Your main method needs to go inside a class: Java won't let you do things any other way.
Try:
public class HelloWorld{
public static void main (String[] args){
//your code goes here
}
}
this the basic structure for a simple program like this.
the class identifier, has to be on the declaration of the class.
public class Caculator {
public static void main(String[] args) {
// Your code here
}
}
It probably should be:
public class JavaCode {
public static void main(String[]args){
}
}
That should do it. ;)

Not able understand the error in java

I was trying to know what would happen if I have two classes with the main function.
I used the following code:
class A {
public static void main(String[] args){
System.out.println("Hello,World!");
}
}
class Hello {
public static void main(String[] args){
System.out.println("Hello,World!");
}
}
I compiled it using javac First.java (since no class is specified as public , I named the file as First.java); it got compiled without any error and i ran only the class A.Expecting the Hello class to run itself. DIDN'T HAPPEN(?),maybe the program ran out of scope.
So,
I tried compiling the following java code(I am a beginner) but i got the following error.
Code:
class Hello {
public static void main(String[] args) {
System.out.println("Hello,World!");
}
}
class A {
public static void main(String[] args) {
System.out.println("Hello,World!");
Hello.main();
}
}
I compiled it through javac First.javaand got the following error:
method main in class Hello cannot be applied to given types;
Hello.main();
^
I wanted the program to run first the class A's main function and then class Hello's.
What's going wrong here?
Look at the declaration of Hello.main:
public static void main(String[] args)
Now you're trying to call it like this:
Hello.main();
What would you expect the value of args to be, within the method? You need to provide it with a value for args... and fortunately, you already have one, as you're within a method which uses args as a parameter, also of type String[]. So you should just be able to change your code to:
Hello.main(args);
Note that the two args parameters - one for Hello.main and one for A.main are entirely separate. We happen to use pass the value of one to the provide the initial value for the other, but we could easily have written:
Hello.main(null);
or
Hello.main(new String[] { "Some", "other", "strings" });
instead.
Do this in your second class:
public static void main(String[] args) throws IOException {
MyOtherClass.main(args);
}

Can we overload the main() method in Java?

The following code simply prints the word "hi" when run.
import java.util.*;
import java.io.*;
class poly
{
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[]) throws Exception
{
System.out.println("hi");
}
}
Is there a way to overload the main() method?
Your program only starts at one location, so that makes no sense. Furthermore, polymorphism is a totally different concept; that's called overloading, not polymorphism.
What you are trying to do is overloading the main method, not making it polymorphic. And no, you can't do it (or to be precise: overload you can, just the JVM won't call the overloaded versions). The JVM is looking for a main method with a specific signature, namely taking a String[] parameter.
Maybe if you tell us more about the actual problem you are trying to solve, we can offer alternative solutions.
The code is correct, you've overloaded the main method. But, as Peter mentioned, the main thread of an application will always start at the method with the signature
public static void main(String[] args)
and nothing else. For starting an application, JVM will ignore all other main methods. To execute the content, you'll have to call it in your code, like so:
public static void main(String args[]) {
main("me");
}
(Should print "this is me" to the console)
In brief you can overload a main function like:
class A
{
public static void main(String s) {
System.out.println(s);
}
public static void main(int s) {
System.out.println(s);
}
public static void main(String args[])
{
System.out.println("inside main entry");
main("me");
}
}
Output:
inside main entry
me
We can have any number of main method and that can be overloaded but the main thread of an application will always start at the method with the signature:
public static void main(String[] args)
and nothing else.
In Java args contains the supplied command-line arguments as an array of String objects.
You can overload a main method in Java; however, getting the classloader to start from the overloaded main method is going to be quite a trick.
The class you pass the the java executable is inspected, it's static methods are read, and control is passed off to only the one that looks like
public static void main(String[] args) { ... }
Since this is a static method, and Java does not have the concept of inheriting static methods, you have no way to overload this method. Since Java does not have the concept of inheritance of static methods, sub-classing the static bits of a class is a nonsensical idea.
Maybe you want something like this?
import java.util.*;
import java.io.*;
class poly {
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
public static void main(String args[])throws Exception
{
if (args.length == 1) {
poly.main(args[0]);
}
else {
System.out.println("hi");
}
}
}
The java runtime environment only looks for the exact match to public static void main(String[]), which is defined as the entry-point for standalone java applications.
To simulate the behaviour you want you have to call the other main yourself:
/**
* Your method called main, ignored by the java runtime since
* it does not match the signature. Called by the valid main(String[])
**/
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
/**
* Starting point of your program, called by the java runtime.
*/
public static void main(String args[])throws Exception
{
if(args.length >= 1){
main(args[0]);
}else{
System.out.println("hi");
}
}
As others point out having several methods with the same name but different parameters is called over*loading* and not polymorphism (over*writing*).
I'm not quite sure what you are asking but I don`t see any reason why you cannot overload the main method.
The "main method I think you are referring to is
public static void main(String c)
{
System.out.println("enter a char");
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(ir);
//char l= br.readLine();
System.out.println("this is "+c);
}
To overload this method I would create a method such as
public static void main(){}
This must be in the same class as the other main method to make it overloaded.
The static keyword means common to the class.....(there is no need to use an object to access the method from the main(String[] args) method.
In my ind creating an overloaded method in a class is the same as creating a different method.
Different arguments, parameter list ====> different signature ======> different method.
I hope this helps.

Categories

Resources