public class test
{
public static void main(String[] args)
{
int x = 5;
int y = 10;
multiply(x,y);
}
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z);
}
}
I am new to programming and I am confused on a few things.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
Thank You!
First, the multiply method does not return anything; it prints the product, but does not return any value.
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z); //may look like a return, but actually is a side-effect of the function.
} //there is no return inside this block
Secondly, public static void main provides an entry point into your program. Without it, you cannot run your program. Refer to the Java documentation for more information on the usage of public static void main.
The String[] args here means that it captures the command line arguments and stores it as an array of strings (refer to the same link posted above, in the same section). This array is called args inside your main method (or whatever else you call it. Oracle cites argv as an alternate name)
System.out.print tells the program to print something to the console, while return is the result of the method. For example, if you added print all over your method to debug (a common practice), you are printing things while the program runs, but this does not affect what the program returns, or the result of the program.
Imagine a math problem - every step of the way you are "print"ing your work out onto the paper, but the result - the "answer" - is what you ultimately return.
When a method does not return anything, you specify its return type as "void". Your multiply method is not returning anything. Its last line is a print statement, which simply prints the value of its arguments on the standard output. If the method ended with the line "return z", then you would not be able to compile the program with the "void" return type. You would need to change the method signature to public static int multiply(int x, int y).
All Java programs do require the public static void main(String[] args) if they are to be executable. It is the starting point of any runnable Java program. Here's what it means:
a. public - the main method is callable from any class. main should always be public because it is the method called by the operating system.
b. static - the main method should be static, which means the operating system need not form an object of the class it belongs to. It can call it without making an object.
c. void - the main method does not return anything (although it may throw an Exception which is caught by the operating system)
d. String[] args - when you run the program, you can pass arguments from the command line. For example, if your program is called Run, you can execute the command java Run 3 4. In that case, the arguments would be passed to the program Run in the form of an array of Strings. You would have "3" in args[0] and "4" in args[1].
That said, you could have a Java program without a main, which will not be runnable.
I hope that helps.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
No
multiply method does not return z. However, you are correct, void is in fact used to specify that nothing will be returned.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
yes, all programs must have a main function that looks like public static void main(String[] args).
Like others said, the multiply method does NOT return anything. The other answers explained why that is.
However it would also be helpful to mention that when you use void that method can not return anything. In contrast, if you set your method to return anything (not to void) you are required to return that type of value.
For example:
public static void main(String[] args){
int a;
a = returnInt();
}//End Method
public static int returnInt(){
int z = 5;
return z;
}//End Method
The main method does not return anything, which is why we use void. The returnInt method returns an integer. The integer that the method returns is z. In the main method where a = returnInt(); that sets the value of a to the value returned from returnInt(), in this case, a would equal 5.
Tried to keep it simple, hope it makes sense.
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
void means that the method has no return value. If the method returned an int you would write int instead of void.
The combination of all three of these is most commonly seen on the main method which most tutorials will include.
credits to Mark Bayres
The multiply() method in your example does not return the value of z to the calling method, rather it outputs the value of z (e.g., prints it to the screen).
As you said, the void type keyword means that the method will not return a value. Methods like this are intended to "just do something". In the case of main(), the method will not return a value, because there is no calling method to return it to -- that's where your program begins.
OK, technically, that last comment is not accurate; it actually is possible to have your main return a value to the operating system or process that launched the program, but it isn't always necessary to do so -- especially for simpler console-based programs like those you'll write when you're just getting started! :)
Void class is an uninstantiable class that hold a reference to the Class object representing the primitive Java type void.
and The Main method is the method in which execution to any java program begins.
A main method declaration looks like this
public static void main(String args[]){
}
The method is public because it be accessible to the JVM to begin execution of the program.
It is Static because it be available for execution without an object instance. you may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.
It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method
The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line. We can use both String[] args or String args[]. The Java compiler would accept both forms.
Why is it correct to use void? I thought void is used in order to
specify that nothing will be returned but, the multiply method returns
z.
Your multiply method is correct to have void since it is returning nothing, it is just printing to the console.
Returning something means gives out a result to the programm for further computation.
For example your methode with return of the result would look like this:
public static int multiply(int x, int y)
{
int z = x*y; //multipling x and y
System.out.println(z); //printing the restult to the console
return z; //returning the result to the programm
}
this "new" method can be used like this for example:
public static void main(String[] args)
{
int x = 5;
int y = 10;
int result = multiply(x,y); //storing the returnen value of multiply in result
int a = result + 2; //adding 2 to the result and storing it in a
System.out.println(a); //printing a to the console
}
Output:
50
52
Do all programs require that you have exactly "public static void
main(String[] args)"? What exactly is the purpose of the main method
and what do the parameters "String[] args" mean? Would the program
work if the main method was removed?
This mehtod seves a the etry point for your programm. This meas the first thing that is executet of your programm is this mehtod, removing it would make the programm unrunneable.
String[] args stands for the commandline arguments you can give to you programm befor starting over the OS (OS = Windows for example)
The exact purpose of all of the words is very well explained in the other answers here.
Related
What is the meaning of this?
public static void main(String[] args) throws Exception?
I don't know it. If someone know please help me.
I really want to know about "throws Exception".
public : it is a access specifier that means it can be accessed by
any other class in the program.
static : it is access modifier that means when the java program is
load then it will create the space in memory automatically.
void(return type) : it does not return any value.
main() : it is a method or a function name.(First method to execute by JVM)
string args[] : its a command line argument it is a collection of
variables in the string format.
throws Exception : Use exceptions to notify about things that should
not be ignored.
It's three completely different things:
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
void means that the method has no return value. If the method returned an int you would write int instead of void.
It is simply the usual entry point method public static void main(String[]), except that it explicitly specifies an exception may be thrown. This is required by the compiler if any part of your code explicitly throws an exception without a try-catch block (excluding of course runtime-exceptions). For example, this will not compile:
public static void main(String[] args){
throw new Exception();
}
Those three keywords are pretty much different from one another. Public=This type can be called by any place from the program. not protected from other classes. Static=This type of methods does not have to be instantiated in order to invoke them. Void=This type of methods does not have a return value
The reason this main method is throwing an Exception outside of main is because the rest of the actual program's implementation doesn't actually care at all about what that Exception is about.
For example, if all I was doing in my program was printing something out onto the screen repeatedly every 5 seconds, I wouldn't really care too much about the InteruptedException being thrown due to the Thread.sleep() method. In such cases, we would then just throw it outside of main to just discard of its irrelevance instead of having to write some kind of code to handle it.
There's honestly nothing special about it at all. It's just a way to not have to fool with something meaningless.
public class IrrelevantExceptionExample {
/**
* Main method that repeatedly prints to the console every five seconds from a single Thread.
* #param args - Wise words from above.
* #throws InterruptedException - Uhm… There's only one Thread and it's sleeping! (IrrelevantException)
*/
public static void main(String[] args) throws InterruptedException {
System.out.println("Hey, at start up.");
for (int i = 5; i < 25; i += 5) {
Thread.sleep(5000);
System.out.printf("Hey, again, except %d seconds later!%n", i);
}
}
}
Public: it is an access specifier which can be access throughout the program.
Static: it is a keyword which can be used for single copy of that variable.
Void: it is an empty return type.
I have Googled this several times, but as a newb, I am completely unclear as to how I would pass a parameter, which is an int variable, from one of my methods, into my main method. I have a method, getInput(), which returns an int, but I can't pass it to main. My constructor and main method are as follows
public Mainmenu9(int choice){
//constructor
System.out.println("Choice is :" + choice);
}
public static void main(String args[]){
Mainmenu9 team = new Mainmenu9(choice);
System.out.println("team :" + team.choice);
getInput();
} // end main method
The reason I want to pass this int variable into the main method, is because I have read about serialization and I know that in order to write to a file, I need to convert int variable to an object. My code only works, if I declare the int as a static class variable, but then I lose the returned value, the int is always 0 , as there is no value and it has not been initialised.
I'm not looking for someone to do it for me, just a pointer in the right direction.
You're going about this all wrong. The main method is used to initiate action (ie methods, constructors etc). The goal is to use the main method as an entry point for your program
If you want to pass a parameter into your main method this needs to be done with command line args.
The only scenario where you would call the main method from inside the application is when you're unit testing it.
For any other purposes, use it just to receive parameters from the command line.
"main()" is the "start" of your program.
The only thing that calls in to "main()" is you (by way of the operating system), when you start your program.
For example, this illustrates "passing arguments from the command line":
public class MyClass {
public static void main (String[] args) {
System.out.println ("#/args=" + args.length);
for (String s:args) {
System.out.println ("next arg=" + s);
}
}
}
java MyClass <-- No args
java MyClass a b c <-- Will pass the three arguments "a", "b" then "c"
In the second example, you can pass "a", "b" and/or "c" to any of the objects your "main()" might instantiate. For example, "a" might be the "choice" in your "Menu" class.
I am trying to pass values from my private static void main(...) into a class that has an array stack initialized in the constructor. I was wondering how to take the values I assign to a variable in the main() and push that value onto the array stack within this innerClass?
I know that the array stack works, I have implemented this class before without a problem, but I was only using the arrayStack() I had created and a main(). The addition of the third class is confusing me.
Without getting too deep in my code, I was hopping someone could explain (or point me to some resources) to me how to pass arguments to a stack that is initialized in a constructor, with arguments from the main() method of a different class (same package)?
Example of where I'm trying to get values to:
package program2;
public class Exec {
public Exec(DStack ds) {
/*I have initilized an arrayStack to hold doubles (i.e. DStack).
* I can use ds.push()/pop()/top() etc.
* I cannot take the value from Calculator.java and push that value
* here, which is what I need help understanding?
* */
ds.push(Calculator.i); //I would expect an error here, or the value stored in
//Calculator.i to be added to the stack. Instead program
//terminates.
}
}
Where I would like to take the values from:
package program2;
public class Calculator {
public static double i;
public static void main(String[] args) {
i=9; //I'm expecting that by using Calculator.i in the Exec class that
//I should be able to push 'i' onto the stack.
}
}
This question goes along with a question and answer I was able to get working yesterday here: Get answer from user input and pass to another class. There are three differences, one, I am no longer selecting an answer from the menu and performing an action. Two, I would like know how to get items on a stack versus comparing the String in a series of if/else statements. Lastly, I would like to know a little more detail about the nuts and bolts of this action.
You seem to completely misunderstand how an application works. When you launch your program, java executes your main method. All its instructions are executed in sequence until the end of the method is reached. If you haven't started any other thread from this method, when the last instruction in the main method has been executed, the program terminates.
In this case, the main method contains only one instruction:
i = 9;
So this instruction is executed, and since it's the last one, the program terminates. You don't even reference the Exec class anywhere, so this class isn't even loaded by the JVM.
If you want to use the Exec class, then you have to do something with is somewhere in the program. For example, you could do
i = 9;
DStack dstack = new DStack();
Exec exec = new Exec(dstack);
Note that storing something in a public static variable in order for some other object to be able to get this value is a very poor form of parameter passing. If an Exec object needs a value to work, then it should be an argument of its constructor:
public Exec(DStack ds, double value) {
ds.push(value);
}
and in the main method, you would use a local variable and not a public static variable:
double i = 9;
DStack dstack = new DStack();
Exec exec = new Exec(dstack, i);
If I understand your question correctly, you should create an instance of the Exec class. You can also create an instance of DStack within your program and pass it the Exec constructor after pushing the double value onto the stack.
package program2;
public class Calculator {
public static double i;
public static void main(String[] args) {
DStack dStack = new DStack();
dStrack.push(i);
Exec exec = new Exec(dStack);
}
}
I think you are confusing the concept of class vs. instance. You don't pass values to classes, you pass values to instances (static fields are sometimes called class variables and can make things confusing, but ignore that for now).
In a nutshell, a class is the code for that class you wrote. An instance is the actual thing that was spawned from that definition of class and actually does stuff. So the number one trick is to "instanciate" your class and create an instance. Then you pass whatever values you want to pass it like below:
class Foo {
public static main(String[] args) {
Bar bar = new Bar(); // <-- now you have an instance called bar
bar.arrayStack.push(args[0]); // <-- Now it's passed!
}
class Bar {
ArrayStack arrayStack;
Bar(){
arrayStack = new ArrayStack();
}
}
So i can pass nulls into functions in java. I can also overload functions in java. But consider the following
public static void main(String ... args){
doStuff(null);
}
public static void doStuff(String s){
solveWorldHunger();
}
public static void doStuff(Integer i){
nukeCanada();
}
public static void nukeCanada(){
System.out.println("NO!");
}
public static void solveWorldHunger(){
System.out.println("YAY!");
}
The previous program will always print out YAY no matter what the order of the sorce code...
Can anyone shed some light onto why the jvm consitently decides to run the solveWorldHunger function over the nukeCanada function`?
It's quite clear to the compiler that you can't store null in a primitive int. So, it decides to go with the method which has String as argument.
However, when you change your 2nd method to take Integer as argument, then you will get compiler error. Because both of them are eligible to be invoked with null argument. So, there will be ambiguity.
So, try changing your 2nd method: -
public static void doStuff(String s){
solveWorldHunger();
}
public static void doStuff(Integer i){ // Integer instead of `int`
nukeCanada();
}
And invoke it on null. You will see the compiler error.
So, in that case, you can invoke the appropriate method using typecasting like this: -
doStuff((Integer)null); // Calls Integer version
doStuff((String)null); // Calls String version
Also, note that, if you have your 2nd method take a parameter that is a super type of String, like Object, then there would be no ambiguity, because compiler will now choose the most specific one, i.e., String argument.
So, ambiguity only occurs, when you have two methods with types that are not in the same inheritance hierarchy.
Only your doStuff(String) method can take a NULL argument... the primitive int can never be null. If you had a second method overload that passed an object, you would no longer be able to pass null as a parameter for that method.
Why are "Hi1" and "Hi3" displayed twice by the following code?
static int a=1;
public static void main(String[] args) {
if (a==2) { System.out.println(args[0]); a = 3;}
if (a==1) { main(); }
System.out.println("Hi1");
System.out.println(new PlayingWithMain().main("Hi3"));
}
public static void main() {
a = 2;
String[] a = new String[10];
a[0] = "Hi2";
main(a);
}
String main(String s) {
return s;
}
I have just started preparing for the OCPJP exam.
The first lesson — or trick, depending on how you look at it — of this question is that only one main method is special, no matter how many main methods are present. The special one is the one that takes the form
public static void main( /* multiple arguments */ ) { ... }
In the past, the argument had to be String[] args, but for recent versions, var-args are also acceptable (e.g. String... args). JLS 12.1.4
Now that we know which method to start with, we see that the first line checks the value of a. We see that it's initialized to 1, so we can ignore the a==2 line. Then, on the next line, we jump to the no-argument main.
In the no-arg main, a gets set to 2. The next lesson is that method-local variables can hide class variables. A new a gets declared, and it takes precedence inside the method but only lives as long as the method does. It's an array of strings of size ten, but only the first one is set (to "Hi2"). There's one more lesson in this method: this code is written to make you think the string-arg main gets called next, but it doesn't, because we haven't created an object and it's not static. Instead, we go back to main(String[] args).
This time, a is 2 — remember, we set it in the no-arg main, and a is static so the change sticks around — so we print the first argument, "Hi2." Next, we set a to 3, so the upcoming a==1 test fails. In the following line, we print "Hi1" for the first time and create a new instance of PlayingWithMain, which I assume is the class that the whole code snippet lives in.
Since a is static, its value remains 3 even for the new object. However, since the object is calling main("Hi3"), we don't go to a static version of main; instead, we go to the string-arg main. That method just kicks the input right back to the caller, where it gets immediately printed out.
That does it for the string-array-arg main, so we go back to the method that called it, the no-arg main. It's also finished, so we go back again, to the version of main(String[] args) that the JVM called. Remember, we just completed the line
if (a==1) { main(); }
so we move on to printing "Hi1" again. Finally, we repeat the last line, which creates another new PlayingWithMain object and prints "Hi3" one last time.
main(String[]) calls main() which again calls main(String[]) if a==1, which is true at the beginning.
The a variable is used to make this recursion only happen once and not endlessly.
This is why the main(String[]) method is executed twice, and this is why the output written from that method appears twice.