Java compilation of methods [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to understand the Java compiler better, and what is happening behind the scenes during compilation and execution, and so I have a question about how Java methods are compiled.
I know that methods need to be called upon or invoked in order for their enclosing code to be executed, and I just want to figure out how this really works
Considering the simple program:
public class Test {
public static void sayHello() {
System.out.println("Hello World");
}
public static void main(String []args){
sayHello();
}
}
Considering that code in java is executed in the order that it appears, why would the contents of sayHello() not be executed, but instead the program waits until the method is invoked for the contents of the method to be executed? So basically I'm asking how does the compiler deal with compiling methods, and what does it do to prevent methods from the contents of a method being run sequentially without them being called on?
Thank you.

Your assertion, "Considering that code in java is executed in the order that it appears", was refuted in comments. However, there is one way in which you could say there is some truth to it, as long as you interpret your statement in a specific way. Let's look at your class:
public class Test {
Here, you're asking the compiler to create a class, and store it in file Test.class.
public static void sayHello() {
This tells the compiler to define a method called sayHello.
System.out.println("Hello World");
This declares to the compiler that this is the content of the method, and to store this content for execution when the method is called.
}
public static void main(String []args){
sayHello();
This tells the compiler to call the method sayHello whenever the method main is called and its body starts getting executed. The method main is called when you run the application with the java command line.
}
}
You see, in a way the contents are "executed" (for some unusual definition of executed) in the order they appear. But that doesn't mean they are run at that time.

The main() function will almost always be executed first.
It is the function that actually contains the code that is run.
Normally you put main() at the top and other functions below it.

Related

JAVA Why should a non public class be executable; isn't it being used outside its package? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In Java, I can a run/execute a non public (i.e. 'default' access) java class from the command line even though it is in a package. Why should this be possible? are we not thereby using a default class outside its package which is not supposed to be correct?
I think you're describing something like the following (See Is a class private or public by default in Java and C++? about the available visibility modifiers on a java class):
class PkgPrivateClass {
public void doIt() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
PkgPrivateClass pkgPrivateClass = new PkgPrivateClass();
pkgPrivateClass.doIt();
}
}
This compiles and prints Hello World!.
Now for the question what is accessible and why:
The main method doesn't and can't do anything other than every static method.
The main method is only visible inside the same package (as the class is package private). Starting a java program - i.e. calling the main method - is hardly comparable to an ordinary method call within a java program.
While package private classes are anyway not used that often (see Pros and cons of package private classes in Java?), I see two arguments why it makes sense to allow calling package private classes from the command line:
You explicitly added the public static void main(String[] args) method. If you don't want this class to be called, you don't add this method.
When starting the JVM, you usually give the fully qualified class name. One could argue that this makes the command line call executed from this package - or asked the other way around: From what package is a main method called?
The access modifier default has another name which is called as package specific.
So if you are in the same package for a default class you can use command line execution. Outside the package you can not execute default class directly.
main() invoked via reflection, that ignores class visibility. You can write own executor instead of java.exe, that will check class visibility too, or do NOT check visibility of main() for example.

I still don't understand public static void main(string [ ] args) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
After almost 1 year working with Java,I still can not explain properly to others or myself why we need this, and how it works.
Obviously, I know what each of keywords does independantly, but I am not sure about the whole thing.
Can someone please describe it in very simple language?
Public : is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only.
String args[] : is the parameter to the main Method.
The other answers are correct, but I'll try to state it in English.
When you create a program, java needs to know where to start the program, so they use this as an entry point. Since it's static method, there doesn't need to be an instantiation of the class. It can simply call that method and know that that's where the program starts.
I knew these already thank you for you response and downvotes.
public
It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in you current class.
static
When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
void
Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
main
It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
String args[]
These are the arguments of type String that your Java application accepts when you run it.
But why there is no simplar method to call main like in other languages, and why we need to get argument and store as String while we sometimes only call methods in the main.
When you start a Java program the JVM needs to know where it should start the execution of the whole thing. This is not obvious because there are thousands of Java classes available on the classpath.
That's why you must give the name of one particular Java class in your command line. For example
java com.stackoverflow.example.Main bla blah
The JVM then just loads this class, looks for its static void main(String[] args) method, and calls it with the remaining parameters taken from the command line
main(new String[]{"bla", "blah"});
The main() method is defined by the java launcher:
The java command starts a Java application. It does this by starting the Java Runtime Environment (JRE), loading the specified class, and calling that class's main() method. The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:
public static void main(String[] args)
That explain why you need it: It's required to start running a Java program.
And how it works: It's called by the launcher at startup.

missing method body, or declare abstract java error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
A snapshot of the code and error being presented
I've tried making class main() I've tried adding {} neither have worked, please help.
You forgot to add a { after main().
public static void main(String[] args) {
//-------------------------------------^
And after return add ; and }.
Looks like you are confusing between Java and .NET. There's no Console.WriteLine() in Java. You need to change it to:
System.out.println();
The Console.WriteLine() is available only in .NET Framework. You need to replace them with the above. For eg:
Console.WriteLine("john smith");
Should be replaced with:
System.out.println("john smith");
If you really want to execute Console.WriteLine, then you need to use Microsoft Visual Studio and create a new C# Console Application.
See more here: How to: Create a C# Console Application:
(source: programcall.com)
And in the Console Program using .NET, it uses the main class as:
class Program {
And not the one which you use. So definitely yours is a Java Application.
You are missing some brackets.
public class MyFirstProgram {
public static void main (String args[]) {
Console.WriteLine("some text");
}
}
EDIT: You should also add semicolons ; to the end of a function/line
For every method with implementation, you need a pair of curly braces.
public static void main(String[] args){
}
The curly braces will indicate the scope of the codes the follows. Also, are you asking a question on C# or Java?
If you are asking a question on Java and not C#, to print a line, you should be using System.out.print() or System.out.println(). Not Console.WriteLine().
It looks like to me you are writing C# codes in Java with a habit carried over from C++. There is no need to write a return statement at the end of your main method in Java.
The return type for main() in Java is void, that means you can't return a value from main().
Your complete program in Java shall look like this:
public class MyFirstProgram
{
public static void main(String[] args)
{ //<--curly bracket needed
System.out.println("john smith");
System.out.println("programming major");
//more println statements below..
} //<--curly bracket needed
}

when program can execute without main in java 6 using static block then why there is need of main method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
for example-
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Someone explain me the reason.
A "program" cannot execute without main() (unless it is a servlet or an applet, in which case the web container or the web browser manages the corresponding entry point). In your example, a static block, it will only be executed once some other running class initializes (usually by referencing) the class A3.
JLS-8.7. Static Initializers reads (in part)
A static initializer declared in a class is executed when the class is initialized (§12.4.2).
Static blocks are executed when a Class is first initialized (after it is loaded). A main() method serves as an entry point for the application. Classes are (implicitly) loaded (and probably initialized) when they are first referenced.
See the difference?. You need to specify an entry point to a program / application by putting main() method in a class. A static initializer is run when a class is initialized, it is not the entry point of the program but a set of statements which are run (usually to do some setup work like initializing static fields (like maps)) when the class is being initialized.
if you want to print simple print statements static block is enough. but the real time program never contains system.out.println statements. and more over you can't access non static variables, methods..etc so it mean it is useless.
The static block isn't necessarily invoked at program startup; it can be delayed to whenever the class is first initialized. It is necessary to specify a main class with a main function to indicate the entry point that should be invoked at program startup and because that's how Java works.

Is this appropriate to create a class with one method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm wondering whether it's a good practice to produce the code which being used like this:
new TemplateProcessor(inputStream).processTemplate("output-path.xhtml");
Here, TemplateProcessor contains only one public method. It seems the code above can be expressed with a static method, but I would like to avoid that. The reason is simple: object may contain encapsulated state, (maybe now, maybe in the future). Dear experts what would You prefer in this case?
It's reasonable to encapsulate the code in a static method, with static imports it becomes very easy to use:
processTemplate(inputStream, "output-path.xhtml");
The above static method would just be a façade, a convenience method to be used for that specific use case that your class is solving, supposedly one that's very common. It does not prevent the class from evolving, even adding state. For more specialized use cases, the consumers can still create instances of the class and use its methods as usual.
To make that separation even more pronounced, you could add the static method to a sibling class, like TemplateProcessorFacade, which is a non-instantiatable utility class:
public final class TemplateProcessorFacade {
private TemplateProcessorFacade() {}
public static void processTemplate(...) {
...
}
}
A class should be seen as an object or module that performs a key role or function in the program. A role that no other class or module fulfils. For example, you can have a class Animal that provides the functions sleep(), run() . But you might want a class for carnivores which also kill() , hunt() etc. So you implement the Carnivores class by extending from Animal, which does what all variables of type Animal do, but also additionally kill and hunt.
If your class has only one public method, but if it's important for the design to have it as a separate module, then having a class for it is good. You can extend it later, if needed.
Also you can, keep the sleep() and run() functions static and public, all Animal's do that, and so you can just do Animal.sleep() and such, without creating a separate instance. But a function like roar() shouldn't be.
Update:
The reason I said, sleep() and run() can be static is, there can be a class Man who also sleeps and runs.
The question to ask:
Does it make sense to call sleep() and run() or any function of a class without initializing an object of that class? If yes, then it makes sense to make it static.

Categories

Resources