Let discuss access modifiers private and public in context of any method not just main() method.
1. When you declare a method public then it is accessible outside the class (By any other class)
2. when you declare a method private it means that method is visible/accessible only by that same class and not outside.
Now next point is, who is going to call your main() method? It is Run time environment (be it java or .net). Run time environment is something that is outside of your class and unless you grant it a permission to access your main() method by making it public, it will not be able to call
Let discuss access modifiers private and public in context of any method not just main() method.
1. When you declare a method public then it is accessible outside the class (By any other class)
2. when you declare a method private it means that method is visible/accessible only by that same class and not outside.
Now next point is, who is going to call your main() method? It is Run time environment (be it java or .net). Run time environment is something that is outside of your class and unless you grant it a permission to access your main() method by making it public, it will not be able to call it.
So, as you know that program's starting point is main() method, it has to be public so that is accessible outside the class where you declare it.
Let me know if it is clear.
Where do I start?
I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.
Here are the biggest mistakes people are making and how to fix them:
Not having a separate high interest savings account
Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.
Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.
Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of th
Where do I start?
I’m a huge financial nerd, and have spent an embarrassing amount of time talking to people about their money habits.
Here are the biggest mistakes people are making and how to fix them:
Not having a separate high interest savings account
Having a separate account allows you to see the results of all your hard work and keep your money separate so you're less tempted to spend it.
Plus with rates above 5.00%, the interest you can earn compared to most banks really adds up.
Here is a list of the top savings accounts available today. Deposit $5 before moving on because this is one of the biggest mistakes and easiest ones to fix.
Overpaying on car insurance
You’ve heard it a million times before, but the average American family still overspends by $417/year on car insurance.
If you’ve been with the same insurer for years, chances are you are one of them.
Pull up Coverage.com, a free site that will compare prices for you, answer the questions on the page, and it will show you how much you could be saving.
That’s it. You’ll likely be saving a bunch of money. Here’s a link to give it a try.
Consistently being in debt
If you’ve got $10K+ in debt (credit cards…medical bills…anything really) you could use a debt relief program and potentially reduce by over 20%.
Here’s how to see if you qualify:
Head over to this Debt Relief comparison website here, then simply answer the questions to see if you qualify.
It’s as simple as that. You’ll likely end up paying less than you owed before and you could be debt free in as little as 2 years.
Missing out on free money to invest
It’s no secret that millionaires love investing, but for the rest of us, it can seem out of reach.
Times have changed. There are a number of investing platforms that will give you a bonus to open an account and get started. All you have to do is open the account and invest at least $25, and you could get up to $1000 in bonus.
Pretty sweet deal right? Here is a link to some of the best options.
Having bad credit
A low credit score can come back to bite you in so many ways in the future.
From that next rental application to getting approved for any type of loan or credit card, if you have a bad history with credit, the good news is you can fix it.
Head over to BankRate.com and answer a few questions to see if you qualify. It only takes a few minutes and could save you from a major upset down the line.
How to get started
Hope this helps! Here are the links to get started:
Have a separate savings account
Stop overpaying for car insurance
Finally get out of debt
Start investing with a free bonus
Fix your credit
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time tr
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time trying.
A simple answer to why and when is 'whenever it makes sense". If a method needs to be in a class, but not tied to an object, then it makes sense. If the method is more logically part of an object, then it shouldn't be
Main is static because someone at Sun decided it would be better if the JVM could call main without creating an object first. It probably simplified the design of the JVM.
Now on why should be use :
To use a particular method in Java we first create a object to class which that method belongs to.Then by using object name.method name we call that method.
Example:
class Demo1
{
static dummyMethod1()
{
----------
-------
}
}
class Sample
{
public static void main()
{
//Use demo class method using classname.methodname
Demo1.dummyMethod1();
2.what all situations in which we can use static methods ?
The advantage of static method is we can use that method using classname.methodname without creating object to class to which it belongs.
Example:
class Demo
{
int dummyMethod()
{
----------
-------
}
}
class Sample
{
public static void main()
{
//create object to demo class
Demo obj=new Demo();
//Use demo class method using object
obj.dummyMethod();
3.why main is static?
To call a method in java we need an object.Program execution starts from main method we dont have a object to call main method in the begining.When JVM sees main method in program it starts execution from there.Since main method is static we can execute it without creating an object.
4.where should we must use static and where satic methods should not be used?
NOW YOU can answer this question i guess.
Everything that we define in a class is called a member of the class. Members of a class can be of two types:
- Instance Member
- Class Member
Instance Member
A member which describe some property or behavior of an object of the defined class, is called an Instance Member. E.g. let India be a class then all the Indians are its objects. Each Indian has some properties such as name, age, qualification etc. Value of these properties differ from Indian to Indian i.e. object to object. These properties are examples of Instance members.
Class Member
A member which describe some property or behavior of the def
Everything that we define in a class is called a member of the class. Members of a class can be of two types:
- Instance Member
- Class Member
Instance Member
A member which describe some property or behavior of an object of the defined class, is called an Instance Member. E.g. let India be a class then all the Indians are its objects. Each Indian has some properties such as name, age, qualification etc. Value of these properties differ from Indian to Indian i.e. object to object. These properties are examples of Instance members.
Class Member
A member which describe some property or behavior of the defined class as a whole, is called a Class Member. E.g. India as a class also has some properties such as currency, capital, flag etc. Value of these properties is common for all the Indians i.e all the objects. These properties are examples of class members.
By default each member of a class is assumed to be Instance Member. To define class members static keyword is used.
Infact behavior is not only associated with objects but it is also associated with classes and family of classes.
The main() method of a class denotes the entry point of the class. It is like opening a school. Once the school is opened, employees, teachers and students arrive as objects to manifest their behavior. As class members are associated to the class, no object is required to access them. By default each member is associated to object hence to associate the main() method to the class, it is qualified by static keyword.
In other words, main method represents the execution of the class not the execution of a particular objects of the class, bcz it represents execution of the class,it means it should be a class member, and class member won’t create automatically we have to specify them. That’s why static keyword is used.
The reason main() method is static in Java is, so that you can call the main method without the need to create an object of the class in which main() method resides.
The main() method is the entry point of the program…it does not makes sense to create an object just for the sake of starting the execution of a program.
When you create a class like: -
- class Demo
- {
- public static void main(String args[])
- {
- System.out.println("I am main method");
- }
- }
In order to execute the above code the JVM would simply use the following statement to execute the main() method of the class: -
- Demo.main();
If th
The reason main() method is static in Java is, so that you can call the main method without the need to create an object of the class in which main() method resides.
The main() method is the entry point of the program…it does not makes sense to create an object just for the sake of starting the execution of a program.
When you create a class like: -
- class Demo
- {
- public static void main(String args[])
- {
- System.out.println("I am main method");
- }
- }
In order to execute the above code the JVM would simply use the following statement to execute the main() method of the class: -
- Demo.main();
If the main method was non-static then the JVM would first have to create an object of Demo class and then using that object it would have to call the main() method.
- Demo obj=new Demo();
- obj.main();
This certainly does not makes sense and is just an overhead.
The keyword static let's you call a method without the need to create an object of the class hence main method is always made static.
Hope this helps you!!!
Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.
And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.
Don’t wait like I did. Go ahead and start using these money secrets today!
1. Cancel Your Car Insurance
You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily,
Here’s the thing: I wish I had known these money secrets sooner. They’ve helped so many people save hundreds, secure their family’s future, and grow their bank accounts—myself included.
And honestly? Putting them to use was way easier than I expected. I bet you can knock out at least three or four of these right now—yes, even from your phone.
Don’t wait like I did. Go ahead and start using these money secrets today!
1. Cancel Your Car Insurance
You might not even realize it, but your car insurance company is probably overcharging you. In fact, they’re kind of counting on you not noticing. Luckily, this problem is easy to fix.
Don’t waste your time browsing insurance sites for a better deal. A company called Insurify shows you all your options at once — people who do this save up to $996 per year.
If you tell them a bit about yourself and your vehicle, they’ll send you personalized quotes so you can compare them and find the best one for you.
Tired of overpaying for car insurance? It takes just five minutes to compare your options with Insurify and see how much you could save on car insurance.
2. Ask This Company to Get a Big Chunk of Your Debt Forgiven
A company called National Debt Relief could convince your lenders to simply get rid of a big chunk of what you owe. No bankruptcy, no loans — you don’t even need to have good credit.
If you owe at least $10,000 in unsecured debt (credit card debt, personal loans, medical bills, etc.), National Debt Relief’s experts will build you a monthly payment plan. As your payments add up, they negotiate with your creditors to reduce the amount you owe. You then pay off the rest in a lump sum.
On average, you could become debt-free within 24 to 48 months. It takes less than a minute to sign up and see how much debt you could get rid of.
3. You Can Become a Real Estate Investor for as Little as $10
Take a look at some of the world’s wealthiest people. What do they have in common? Many invest in large private real estate deals. And here’s the thing: There’s no reason you can’t, too — for as little as $10.
An investment called the Fundrise Flagship Fund lets you get started in the world of real estate by giving you access to a low-cost, diversified portfolio of private real estate. The best part? You don’t have to be the landlord. The Flagship Fund does all the heavy lifting.
With an initial investment as low as $10, your money will be invested in the Fund, which already owns more than $1 billion worth of real estate around the country, from apartment complexes to the thriving housing rental market to larger last-mile e-commerce logistics centers.
Want to invest more? Many investors choose to invest $1,000 or more. This is a Fund that can fit any type of investor’s needs. Once invested, you can track your performance from your phone and watch as properties are acquired, improved, and operated. As properties generate cash flow, you could earn money through quarterly dividend payments. And over time, you could earn money off the potential appreciation of the properties.
So if you want to get started in the world of real-estate investing, it takes just a few minutes to sign up and create an account with the Fundrise Flagship Fund.
This is a paid advertisement. Carefully consider the investment objectives, risks, charges and expenses of the Fundrise Real Estate Fund before investing. This and other information can be found in the Fund’s prospectus. Read them carefully before investing.
4. Earn Up to $50 this Month By Answering Survey Questions About the News — It’s Anonymous
The news is a heated subject these days. It’s hard not to have an opinion on it.
Good news: A website called YouGov will pay you up to $50 or more this month just to answer survey questions about politics, the economy, and other hot news topics.
Plus, it’s totally anonymous, so no one will judge you for that hot take.
When you take a quick survey (some are less than three minutes), you’ll earn points you can exchange for up to $50 in cash or gift cards to places like Walmart and Amazon. Plus, Penny Hoarder readers will get an extra 500 points for registering and another 1,000 points after completing their first survey.
It takes just a few minutes to sign up and take your first survey, and you’ll receive your points immediately.
5. Get Up to $300 Just for Setting Up Direct Deposit With This Account
If you bank at a traditional brick-and-mortar bank, your money probably isn’t growing much (c’mon, 0.40% is basically nothing).
But there’s good news: With SoFi Checking and Savings (member FDIC), you stand to gain up to a hefty 3.80% APY on savings when you set up a direct deposit or have $5,000 or more in Qualifying Deposits and 0.50% APY on checking balances — savings APY is 10 times more than the national average.
Right now, a direct deposit of at least $1K not only sets you up for higher returns but also brings you closer to earning up to a $300 welcome bonus (terms apply).
You can easily deposit checks via your phone’s camera, transfer funds, and get customer service via chat or phone call. There are no account fees, no monthly fees and no overdraft fees. And your money is FDIC insured (up to $3M of additional FDIC insurance through the SoFi Insured Deposit Program).
It’s quick and easy to open an account with SoFi Checking and Savings (member FDIC) and watch your money grow faster than ever.
Read Disclaimer
5. Stop Paying Your Credit Card Company
If you have credit card debt, you know. The anxiety, the interest rates, the fear you’re never going to escape… but a website called AmONE wants to help.
If you owe your credit card companies $100,000 or less, AmONE will match you with a low-interest loan you can use to pay off every single one of your balances.
The benefit? You’ll be left with one bill to pay each month. And because personal loans have lower interest rates (AmONE rates start at 6.40% APR), you’ll get out of debt that much faster.
It takes less than a minute and just 10 questions to see what loans you qualify for.
6. Lock In Affordable Term Life Insurance in Minutes.
Let’s be honest—life insurance probably isn’t on your list of fun things to research. But locking in a policy now could mean huge peace of mind for your family down the road. And getting covered is actually a lot easier than you might think.
With Best Money’s term life insurance marketplace, you can compare top-rated policies in minutes and find coverage that works for you. No long phone calls. No confusing paperwork. Just straightforward quotes, starting at just $7 a month, from trusted providers so you can make an informed decision.
The best part? You’re in control. Answer a few quick questions, see your options, get coverage up to $3 million, and choose the coverage that fits your life and budget—on your terms.
You already protect your car, your home, even your phone. Why not make sure your family’s financial future is covered, too? Compare term life insurance rates with Best Money today and find a policy that fits.
The main()
method in Java is often declared as static
because it needs to be accessible without creating an instance of the class. The static
keyword allows the method to be called directly by the class itself, without needing to instantiate an object. This is essential for the entry point of a Java program, as it enables the Java Virtual Machine (JVM) to invoke the method without having an object of the class.
In other words, marking main()
as static
ensures that it can be executed without the need for an instance of the class, making it suitable for starting the program
Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined.
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main must be declared as public, since it must be called by code outside of its class when the program is started.
Example -
package com.kmanishsingh1.Quora;
- public class
Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined.
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main must be declared as public, since it must be called by code outside of its class when the program is started.
Example -
package com.kmanishsingh1.Quora;
- public class DriverClass {
- static void sayHello(){
- System.out.println("Hello");
- }
- public static void main(String[] args) {
- sayHello();
- }
- }
Follow me Manish K Singh
Like many of you reading this, I’ve been looking for ways to earn money online in addition to my part-time job. But you know how it is – the internet is full of scams and shady-grady stuff, so I spent weeks trying to find something legit. And I finally did!
Freecash surprised me in all the right ways. I’ve earned over $1,000 in one month without ‘living’ on the platform. I was skeptical right up until the moment I cashed out to my PayPal.
What is Freecash all about?
Basically, it’s a platform that pays you for testing apps and games and completing surveys. This helps developers improve their appl
Like many of you reading this, I’ve been looking for ways to earn money online in addition to my part-time job. But you know how it is – the internet is full of scams and shady-grady stuff, so I spent weeks trying to find something legit. And I finally did!
Freecash surprised me in all the right ways. I’ve earned over $1,000 in one month without ‘living’ on the platform. I was skeptical right up until the moment I cashed out to my PayPal.
What is Freecash all about?
Basically, it’s a platform that pays you for testing apps and games and completing surveys. This helps developers improve their applications while you make some money.
- You can earn by downloading apps, testing games, or completing surveys. I love playing games, so that’s where most of my earnings came from (oh, and my favorites were Warpath, Wild Fish, and Domino Dreams).
- There’s a variety of offers (usually, the higher-paying ones take more time).
- Some games can pay up to $1,000 for completing a task, but these typically require more hours to finish.
- On average, you can easily earn $30–50/day.
- You pick your options — you’re free to choose whatever apps, games, and surveys you like.
Of course, it’s not like you can spend 5 minutes a day and become a millionaire. But you can build a stable income in reasonable time, especially if you turn it into a daily habit.
Why did I like Freecash?
- It’s easy. I mean it. You don’t have to do anything complicated. All you need is to follow the task and have some free time to spend on it. For some reason, I especially enjoyed the game Domino Dreams. My initial goal was to complete chapter 10 to get my first $30, but I couldn’t stop playing and ended up completing chapter 15. It was lots of fun and also free money: $400 from that game alone.
- No experience needed. Even if you’ve never done any ‘testing’ before, you can do this. You get straightforward task descriptions, so it’s impossible to go wrong. A task you might expect is something like: Download this game and complete all challenges in 14 days.
- You can do it from anywhere. I was earning money while taking the bus, chilling on the couch, and during my breaks.
- Fast cashing out. I had my earnings in my PayPal account in less than 1 day. I’m not sure how long it takes for other withdrawal methods (crypto, gift cards, etc.), but it should be fast as well.
- You can earn a lot if you’re consistent. I’ve literally seen users in the Leaderboard making $3,000 in just one month. Of course, to get there, you need time, but making a couple of hundred dollars is really easy and relatively fast for anyone.
Don’t miss these PRO tips to earn more:
I feel like most users don’t know about these additional ways to make more money with Freecash:
- Free promo codes: You can follow Freecash on social media to get weekly promo codes for free coins, which you can later exchange for money.
- Daily rewards and bonuses: If you use the platform daily, you’ll get additional bonuses that help you earn more.
- In-app purchases to speed up processes: While playing, you can buy items to help speed up task completion. It’s optional, but it really saved me time, and I earned 4x more than I spent.
- Choose the highest-paying offers: Check New Offers and Featured Offers to get the best opportunities that pay the most.
Honestly, I still can’t believe I was able to earn this much so easily. And I’ve actually enjoyed the whole process. So, if you’re looking for some truly legit ways to earn money online, Freecash is a very good option.
Static members(like variables, methods, class) can be called in three ways:
- Directly
- Class name
- Through object
whereas non-static members can be called only by object of the same class or other class(depending on access specifier used).
In Java JVM is responsible to call the main() method and it calls it only by class name so main() method is static in Java.
Suppose we have a class called demo and it is saved as demo.java, so to compile it we write:
javac demo.java
and to run the demo class, we write:
java demo (i.e., we are calling the main() method to execute the program by class name)
Because.,,
public : “public” is an access specifier which can be used outside the class. when main method is declared public it means it can be used outside the class.
static : To call a method we require object. sometimes it may be require to call a method without the help of object. Then we declare a method as static. JVM calls the main() method without creating object by declaring keyword static.
void : void return type is used when a method doesn't return any value.main() method doesn't return any value,so main() is declared as void. Signature : public static void main(string[] args) {……}
As you already must have figured out by now is that the 'main' method you are talking about is entry point of your code. Here is small example of little java class with main method :
- public class A //The class name is in you control
- {
- public A(int param1, int param2)
- //Number of arguments and their data type is in your control
- {
- }
- public static void main(int[] args)
- {
- }
- }
Now, have a look for the signature of 'main' method. Lets assume the method is not 'static' and JVM has to call that function. Than JVM has to create a object of class 'A' and that can only be done by knowing constructor of th
As you already must have figured out by now is that the 'main' method you are talking about is entry point of your code. Here is small example of little java class with main method :
- public class A //The class name is in you control
- {
- public A(int param1, int param2)
- //Number of arguments and their data type is in your control
- {
- }
- public static void main(int[] args)
- {
- }
- }
Now, have a look for the signature of 'main' method. Lets assume the method is not 'static' and JVM has to call that function. Than JVM has to create a object of class 'A' and that can only be done by knowing constructor of that class and now JVM has to decide what to pass as param1 and param2 in that constructor.
So, by above example it is clear that the method has to be accessible without creating the object of the class in which it resides and that can only be done by having it as 'static'
Thanks for A2A!
If we make main method private , JVM won't be able to call that main method so the code wont be executed to avoid this it will give you compile time error as follows.
The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
I hope my explanation helped you. Please feel free to correct me!
Nothing hard and fast about a "public static void main" -- it is merely a convention.
If you want even you can write wrapper for the JVM which uses a different method or calling convention or which does things totally differently.
The "AppletViewer" as well as the browser's "applet running functionality" and also browser's calling conventions for java Web apps are examples of wrappers that use different calling conventions than above.
Servlet containers etc are still other examples of other calling conventions.
Advantage of having a static method main is that there is just one indisputable entry
Nothing hard and fast about a "public static void main" -- it is merely a convention.
If you want even you can write wrapper for the JVM which uses a different method or calling convention or which does things totally differently.
The "AppletViewer" as well as the browser's "applet running functionality" and also browser's calling conventions for java Web apps are examples of wrappers that use different calling conventions than above.
Servlet containers etc are still other examples of other calling conventions.
Advantage of having a static method main is that there is just one indisputable entry point to code.
Having a class method that needed class instantiation would mean that possibly class variables would also get initialized before constructor and so many constructors could be the possible entry point making things harder to debug.
But like I said... it is merely a convention. .. If you want, write something different.
Reasons:
1. Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
2. Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
3. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
4. Anything which is declared in class in java comes under reference type and
Reasons:
1. Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
2. Since C and C++ also has similar main method which serves as entry point for program execution, following that convention will only help Java.
3. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
4. Anything which is declared in class in java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
More refer from here: Why is the Java main method static?
The role of adding static before any entity is to make that entity a class entity. It means that adding static before methods and variables make them class methods and class variables respectively, instead of instance methods and instance variables.
Hence, static methods and variables can be directly accessed with the help of Class, which means that there is no need to create objects in order to access static methods or variables.
- // Making a static function class GfG { static void func() {} } // Calling a static function GfG.func();
- Static main() method: When the static keyword is added in the
The role of adding static before any entity is to make that entity a class entity. It means that adding static before methods and variables make them class methods and class variables respectively, instead of instance methods and instance variables.
Hence, static methods and variables can be directly accessed with the help of Class, which means that there is no need to create objects in order to access static methods or variables.
- // Making a static function class GfG { static void func() {} } // Calling a static function GfG.func();
- Static main() method: When the static keyword is added in the function definition of main() method, then it is known as static main() method.
- class GfG {
// Making a static main function public static void main(String[] args) {}
}
It must be static due to how instancing works! In java static methods are loaded once in memory, and accessed from that point! Having multiple instances of a main method would obviously lead to severe problems!
First of all, main() is just a starting point of a program which tell the JVM where to start. Now if you want to the main() to be called via an object,then for it, a class needs to be made. Suppose you have a program having multiple classes in a single .java file, then how would JVM know where to start? It is made static so that it is available to the JVM at koad time! Also, JVM needs to know where to start the execution! :)
jvm knows main method which is a public static method. so when run your java program then it will call the main method.
Making it public and static make is usable from anywhere.
in thread queue it calls the run method. so these things are defined while designing the language.
Even c has public main method.
There can be different ways of doing it this was the best at the time of designing it.
If it is not static and needs an instance then where will you create that instance ? it is kind of a chicken/egg situation on which comes first.
Making it static simply solves the issue and determines one (and always one) entry point in the class that you want your program to start with.
Simple !
In java, the java compiler starts its execution from the main function (just like void main() in C an C++) .
To your question of why is it public static void main, I’ll separate the words :
- public : a keyword in java which is used to denote that the things after it are accessible anywhere in the program.
eg. public int x = 10; can be accessible to any method in the class
- static : a keyword which specifies that there is no need to create an instance of the method or variable which is declared static and it can be accessed anywhere in the program.
eg. if static int x = 10, and it is shared to two dif
In java, the java compiler starts its execution from the main function (just like void main() in C an C++) .
To your question of why is it public static void main, I’ll separate the words :
- public : a keyword in java which is used to denote that the things after it are accessible anywhere in the program.
eg. public int x = 10; can be accessible to any method in the class
- static : a keyword which specifies that there is no need to create an instance of the method or variable which is declared static and it can be accessed anywhere in the program.
eg. if static int x = 10, and it is shared to two different functions A() and B(), then even if x gets changed to x= 20 in B() then it gets also gets changed in A().
- void : just like it means i.e. empty which is generally prefixed after a method which we don’t want to return anything.
- main(): the main method is where the program actually starts to execute.
So, based on the above information you can conclude that the public static void main() means that main function (which is called foremost in every program) is accessible in all program, which does not needs to be instantiated and returns nothing .
/*Feel free to ask it again if you do not get it or not getting it properly.*/
Always remember ... there are no private or protected top level classes in java. (INNER classes can be private or protected).
A top-level class as private would be completely useless because nothing would have access to it. SO whether it has main method or any other method...we don't declare classes private. On the contrary inner classes can be accessed by outer classes so they can be private or protected.
Every Java program has one starting point:
public static void main(String args[])
Here's what that means....
- public: means the method is accessible to all classes
- static: allows main() to be called without instantiating the class
- void: means that no value is to be returned
- main(): is the method name
- String args[ ]: means an array of String objects that are passed from the command line
Static methods can be directly called without a object since main() is going to be the first thing that will be called (program execution starts from main()) so it is referred directly without any object (when we execute command java <program name>, hence main() class name and .java file name is same) and starts execution ie creating classes and calling other methods. Moreover static methods bind at compile time so it adds to the sense of keeping main() as static, public (so that java runtime has access to it) and void (so that we need not pass any input barring the case of command line argume
Static methods can be directly called without a object since main() is going to be the first thing that will be called (program execution starts from main()) so it is referred directly without any object (when we execute command java <program name>, hence main() class name and .java file name is same) and starts execution ie creating classes and calling other methods. Moreover static methods bind at compile time so it adds to the sense of keeping main() as static, public (so that java runtime has access to it) and void (so that we need not pass any input barring the case of command line arguments
edit:any more suggestions are welcome to make this answer foolproof and perfect good to learn new thinhs ;)
Since in java the methods which are static does not need any object to be created to instantiate them, they can be directly accessed. For jvm to access it directly without making any object of the class we make it static. It also provides separate memory area for main method. It is the entry point of the program and needs to be invoked first so it needs to be static. If we don't make it static than the jvm would need to make the object of the class first and than access it.
Static functions can be called without creating object of that class.
main() function is static in Java so that JVM can call the main method without creating an object of that class. It eases the job of the JVM.
HAPPY CODING!!
It is a Java standard that the user specifies which class of an application should be started first. The main
method serves in this capacity and provides an entry point to launch the application.
However, an application starts without any objects in existence, thus the launching method must be a class method rather than an instance method belonging to an object. Therefore main
is static and public so that it can be invoked from outside the application, e.g. from the command line
static:Static keyword allows main() to be called before an object of the class has been created.
This is neccesary because main() is called by the JVM before any objects are made.Since it is static so directly invoked from class.
The Java® Language Specification says nothing about the type of the class which contains the main method. However, main method must be public. (See section 12.1 from the specification.)
The main method being static, the JVM can call the method without creating an instance of the class containing it. Hence the class being non-public does not make a difference as far as the entry point of JVM is concerned.
Logical reason:
Since it is the entry point of application it has to be static , as one application cannot have more than one entry point.
Technical reason:
If it is not static then to call entry point of application there needs an object of that class, however at the entry point there won't be any scope of doing so hence we cannot have non static method to load/initialise the application.
Hope this clarifies, it not feel free to comment your thoughts/doubts
hey , this is really the Good question as per teacher said that it is always ask during interviews.
public :It is a keyword , Make our main method available for every member of class.
Static:it is also a keyword , create only one copy of main method .
void: As you know it is the return type of functions, here it is used as the return type of main method.
main(): Name of the Function.
Because otherwise the runtime startup code would have to instantiate the corresponding object. No problem if there‘s a public default constructor, but what if there isn‘t? Many special cases would have to be considered without need.
Public:- so that jvm can call it.
Static:- without existing the object of the class in which main method is defined jvm can call it.
If any methods written as static that means they don’t need object for accessing. So the main method needed to be only static because then only we can access that without any object creation.
given answers are good ..so we can say that to make it(main method) available to JVM we declare it public because JVM calls main method from outside the program if we declare it private then it will not be available to JVM
If main() function would not have been static in Java, then it would have been the programmer’s responsibility to create an object of it and execute it, but as we all know that a main function is the starting point of a Java program, then where we would have created it's object and execute it, that is why it has been made as a static function, so that it can get executed without any manual intervention and without the need of on creation.
public - So that the method will be accessible from anywhere.
static - because there will not be any object created to call main method, so in order to get that called. it should static.
If you recognise the Basics of Java which says to invoke any method from the class needs an instance of that class. When you write main function, Java compiler should be able to call it without creating the instance of the class which contains main function. Hence there should be a way to directly call main function. So we declare main function as a static. So that company can call it without creating an instance of that class.
Hope this info helps .
If we want to call a method, we should have an object, since we can not create an object without going into main method, it will become a problem. If we make the main method as static then we can call it with out creating any object.
If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory.
Main methods needs a static bec static methods and members do not need an instance of their class to invoke them and main is the first method ,which is invoked...
The reason it must be public not private is in reality very simple: how would the JVM know how to call it if it were private? It would not. So it has to be public.