Just started learning Java. Why is the main() inside of a class? - java

I'm learning Java and I noticed that the main() is put inside of a class. Why? I don't consider my main() to be a member of any object. So please tell me how I can get around this.

I don't consider my main() to be a member of any object.
It's not since it's a static method. It does not belong to any object but to the class itself.
Aside from that, all methods, including main must be defined in classes.
More generally, a class is the smallest unit in compiled Java code and contains both information on instances of the class and behavioral code that runs by itself (e.g. the main method).

By nature, Java is highly object oriented. So everything must be encapsulated within a class. All methods must be placed inside of a class. However, the main() is different. There can only be one main function in a class and it must always be static, meaning it is not part of an object and there is only one instance of it. When a java application is executed, the JRE will look for the main class (i.e. the class containing the main function). main() is where the execution starts. But due to the very nature of OO, it must be placed in a class. You can say that this is simply because of the skeletal structure of java. No other reason in particular.

You must put the main() in a class. And, it must be static (which means it is not a member of any Object). When you launch the Java Runtime Environment (JRE) it will load that class and invoke the main().
This is covered by JLS-12.1 - Java Virtual Machine Startup which says in part,
The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings. In the examples in this specification, this first class is typically called Test.

Related

Where does static variables and methods are loaded in java?

I am little bit confused that where did static variables and methods are loaded. we say that static variables and methods are loaded in the static memory. bt public static void main() is loaded into stack .Since main() method is also static then how it is possible that main is loaded into stack.
and alse is static methods and variable are stored in different positions because we say that methods are loaded in different place in memory.
The stack is where things go when they are invoked/executed. It doesn't matter if it is static or not. Any running function goes onto the stack where it's local variables and all are held until the stack frame is popped.
For example, I can have main() call main() recursively over and over. Each one would be a new stack frame. The fact that it is a static function does not change that.
Static variables, on the other hand, are different. There will only be one instance of them and you know it explicitly. So, they can go into special storage and be treated differently (as are other global things like the class definitions and all that).
The actual implementation of this is not liable to be very useful, nor easily understandable. However, a model of it might help you understand the use of these things.
First of all, data and code are quite different animals in Java. Variables are going to have values that change at runtime; code never does that. So when you instantiate a class, you are never going to get another copy of the code.
Consider the class Class - instances of it exist, one per fully-qualified class in the program. I think of all code for one class, static or not, as being associated with its Class instance -- 'loaded' with it, if you prefer. Incidentally, and coincidentally, that's also where I think of its static variables being 'loaded'.
But the instance variables need multiple copies -- whenever you instantiate the class, you need another copy of them. So they are associated (or loaded) with the instance of the class when instantiated -- think of the pointer to the class as a pointer to a structure that contains all the instance variables of that class, plus a pointer to jump tables to its methods, etc.
I do not know what you mean by public static void main being "loaded onto the stack". Do you mean the code? Code never goes onto a stack per se. It wouldn't make any sense to have code from a (normal) class put on the stack, lost when the current method returns, and then have to load it again if the method were called.
I think there's part of your question I'm not getting to because I don't understand what you're asking.

Why is a static method considered a method?

I'm writing an explanation for some code for a course, and have been accidentally using the words method and function interchangeably. I decided to go back over and fix the wording, but ran into a hole in my understanding.
From what I understand, a subroutine is a function if it doesn't act on an instance of a class (its effect is restricted to its explicit input/output), and is a method if it operates on an instance of a class (it may carry out side effects on the instance that make it impure).
There's a good discussion here on the topic. Note that by the accepted answer's definitions, a static method should actually be a function because an instance is never implicitly passed, and it doesn't have access to any instance's members.
With this is mind though, shouldn't static methods actually be functions?
By their definition they don't act on particular instances of a class; they're only "tied" to the class because of relation. I've seen a few good looking sites that refer to static subroutines as "methods" though (Oracle, Fredosaurus, ProgrammingSimplified), so either they're all overlooking the terminology, or I'm missing something (my guess is the latter).
I'd like to make sure I am using the correct wording.
Can anybody clear this up?
This quote from 8.4.3.2 may help:
A method that is declared static is called a class method.
A method that is not declared static is called an instance method [...].
Class methods: associated with a class.
Instance methods: associated with an instance.
Java just wants you to "think object-oriented". Also, static methods have access to a surrounding scope which may include state. In a way, the class is like an object itself.
The simple answer is that when Java decided to call everything a "method", they didn't care about the distinction between a function and a method in theoretical computer science.
Static methods are not exactly functions, the difference is subtle, but important.
A static method using only given input parameters is essentially a function.
But static methods may access static variables and other static functions (also using static variables) so static methods may have a state which is fundamentally different to a function which are by definition stateless.
(ADDENDUM: While programmers are often not so strict with using "function" as definition, a strict function in computer science can access only input parameters). So defining this case of accessing static fields it is not valid to say that static methods are always functions.
Another difference which justifies the usage of "static method" is that you can define in C derivates global functions and global variables which can be accessed everywhere. If you cannot access the class which contain static methods, the methods are inaccessible, too. So "static methods" are limited in their scope by design in contrast to global functions.
In Java, a user-defined class is actually an instance of a subclass of java.lang.Class.
In this sense, static methods are attached to an instance of a conceptual class: they are attached to an instance of a subclass of java.lang.Class.
With this in mind, the term "class method" (an alternate name for Java's static methods) begins to make sense. And the term "class method" can be found in many places: Objective C, Smalltalk, and the JLS -- to name just a few.
In computer science function clearly maps to a static method. But "method" of a class is a bit generic, like "member" (field member, method member). There are wordings like
Data members and method members have two separate name spaces: .x and .x() can coexist.
So the reason is, that as the philosoph Ludwig Wittgenstein said, Language is a tool with different contexts. "Method" is a nice moniker in the citation above to categorize a "member".
Your thinking is right and it makes sense. It's just not established terminology in the Java community. Let me explain some internals that can help understand why the terminology subsists.
Java is a class based object oriented language. A method is always member of a class or instance (This is a general statement valid for other programming languages too). We think of class and instance being both objects.
Instance method (dynamic)
You cannot invoke this method from a class directly, you have to create an instance. Each instance references that method. You can overwrite a method definition with the exact same method signature (when subclassing), i.e. the reference points to a different method (which has the same signature, but can have a different method body). The method is dynamic.
Class method (static)
You only can invoke this method from the class directly, i.e. you don't need to create an instance of that class. There is only one global definition of that method in the whole program. You cannot overwrite the exact same method signature when the method is declared static, because there is only one definition valid for the whole program. Note that the method is member of the class object itself, the instances have all the same unique (and fix) reference to that method.
Here is another take on the terminology, using Scala as a mnemonic:
In Scala you have objects, which are singleton instances of an implicitly defined class 1.
Per your definition, we can call these subroutines belonging to the object methods, as they operate on a single instance of the class.
Additionally the object will also define class A, and create all of the methods in object A as static methods on class A (for interfacing with Java) [2].
Therefore we can say that the static methods of Java class A access the same members as the Scala singleton instance, which per your definition then deserve to be called (static) methods of class A.
Of course, the main difference is - method can use static fields, not only method parameters.
But there is additional one - polymorphism!
Results of evaluation Class A.doTheSameStaticMethod() and ClassB.doTheSameStaticMehod() will be depends of class. In this case function is impotent.
Each class has an object to represent it that is an instance of a subclass of the Class class. Static methods are really instance methods on these objects that are instances of a subclass of Class. They have access to state in the form of static fields, so they are not restricted to being just (stateless) functions. They are methods.

Why does the main function in Java reside in a class?

I just started studying Java. And the main function of the program always resides in a class.
public class t{
public static void main(String[] args){
// do stuff
}
}
I have studied C++, and in there the main function doesn't need to be in a class. Why in Java we have to do that?
Why can't the main function exist in Java without a class, like it does in C++?
Probably for the same reason you put question marks at the end of a question: that's just how they decided it's done.
The main method is the result of a convention that says "this is how the entry point's method signature should look" which doesn't exempt it from language semantics.
Java does not support methods outside of classes/interfaces and as such it has to be contained in one.
The "every method in Java must be in a class because the spec says so" answer is only part of the story. By having main() inside a class it is possible to have multiple entry points within a project. i.e. multiple classes with main() methods. This allows you to select a different main class at runtime rather than compile time. e.g.
java -cp program.jar com.example.Class1
or then if you want to run a different main from the same jar
java -cp program.jar com.example.Class2
Because that is how the language was designed. The JVM first loads the class containing the main function and then calls the main() method. Without loading the class, main() cannot be called, i.e, main() doesn't exist without its enclosing class.
All methods must reside in a class in Java.
main is a method.
Therefore, main must reside in a class.
Furthermore, a class is not just a blueprint of an object. It is by itself a chunk of code that does something. One of the things it does is providing the entry point of the application by containing a main method.
Because everything is inside a class in Java. Java code consists only of classes. They may be nested in themselves or in a packagehierarchy, but nothing is allowed to appear outside of a class.
The only exceptions are the package and import statements.
since java is oop language , u cant do anything unless u create a class. this makes java object oriented language. and java was designed like that to first to load the public class and call main method
Let's consider that following is allowed in java
void main (){
f1();
f2();
}
int f1(){
f2();
return 1;
}
int f2(){
return 3;
}
since there are no prototypes in java how would main call f1 or f2 or how would f1 call f2?
i Think that this is one of the reasons

Why main method is marked as public?

I have a question that why main method is marked as public?
According to an answer on stackoverflow, It is declared as static
"The method is static because otherwise there would be ambiguity: which constructor should be called?"
But, can anyone can explain why it is declared public always?
Because the JLS, Section 12.1.4, says so:
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.
If it's not public, then it won't be found; you'll get
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
I believe, the rational behind enforcing main as public is more to do with the language specification – rather than whether something could be achieved or not.
Refer:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4
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. Therefore, either of the following declarations is acceptable:
Java uses JNI launch java application will never have any issue in calling a private main – but this is more like jail-brake (like another jail-brake, where reflection API let you access private method) and definitely not in spirit of java specification.
If I remember till JDK 1.3 – it was not mandatory from developer’s perspective. i.e. even a private main was being accepted by JRE. Though, it was not inline with JLS 1.3.
I tried searching JLS 1.3 for a reference, but could not get a link. But I found that it was reported as a bug by developers across world:
Please refer: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4155575
So, a fix was made in subsequent version to enforce rule stated by JLS.
Now, the point is why JLS writer enforced this rule at first place – I really have no idea. The only thing I can think of is that – to keep it “obvious” and non-confusing for developers.
The initialization software that starts your program must be able to see main so that it can call it.
Because that is what is known as the "entry point" and if it is private, your program will not be able to run.
Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application.
From coderanch
When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it.
There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.
In Java a function or variable in class in unaccessible untill an Object is created from the class, but the 'main' function is supposed to run at startup(without Object initiation) by JVM. So the 'main' is declared public as well as static so that it can be accessed outside class & without even an Object is created.
Yes the standards say so that main method should be public in Java. But it's not only for Java. However even for C#, main must be public.
So just think about it in real world scenarios.
E.g. you want to enter your room, but you should enter your home main door first (given room is inside the house...and no other means to enter the house)
Main door is the only publicly available access point.
Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public

What is the main difference in object creation between Java and C++?

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

Categories

Resources