eclipse acting weird when creating methods - java

I don't see what could be wrong here, I was working on a different method but had some problems so I tried to simplify it to check where could the mistake be but I ended going up into this very simple method and still I have the same error.
When I put the mouse over the redX at line 6 I get a message saying:
multiple markers at this line
-Syntax error on token "(",;expected
-Syntax error on token ")",;expected`
mouse at line 7 says:
void method cannot return a value
2 quick fixes available
change method return type to 'int'
change to 'return;'
I changed public static void to public static int and also changed the method's modifier but the error at line 6 appears everytime.
I don't see anything wrong here but I think I'm making a mistake that just needs a simple fix, am I going crazy? never had this particular problem before

The problem is that you are declaring a method called y within the main method. In Java, you cannot nest method declerations.
You will have to move it outside the main method scope or else, declare a private inner class which will hold your y method.
In short:
public class gat {
public static void main(String args[]) {
...
}
int y(int a) {
return a + 5;
}
}
Or:
public class gat {
public static void main(String args[]) {
class inner {
int y (int a) {
return a + 5;
}
}
}
}
The first approach is the most common, however you sometimes do end up using the second approach, especially when dealing with Swing Events and other threading aspects.

Related

Execution of static blocks

Why is this code a compilation error?
class Test1{
static {
System.out.println(x);
}
static int x = 10;
}
While the below code compiles and runs fine?
class Test2{
static int x = 10;
static {
m1();
System.out.println("base SB");
}
public static void main(String args[]){
m1();
System.out.println("base main method");
}
public static void m1(){
System.out.println(y);
}
static int y = 20;
}
If it declares y here, why not in the previous code.
The output of below code is:
0
base SB
20
base main method
I think Java does not support forward referencing.
It may be an unsatisfying answer, but this is just how the language was defined, specifically here.
The restrictions above are designed to catch, at compile time, circular or otherwise malformed initializations
But you can get around the restriction quite easily like in the question, or just by using Test21.x instead of just x, so it is not particularly robust:
class Test21{
static {
// This is legal, but it is uninitialized, and thus prints 0.
System.out.println(Test21.x);
}
static int x=10;
}
On balance, it is probably better to force you to jump through a small hoop, to make you stop and think about what you are doing, and only to proceed if you really intend to do that.
Ultimately, the language can't entirely stop you shooting yourself in the foot. It can only make it harder to do so.
Your second test case prints zero first which I would assume would not be idiomatic for most people.
This is simply a case of the compiler not being smart enough to catch a probable mistake which you have made.
It is able to detect the forward reference in the first case -- lucky! If it didn't, your program would have printed zero at runtime since the variable would not have been initialized yet. So the compiler saved you from a probable bug.
It is not able to detect it in the second case, since you have introduced a level of indirection with the additional method call to m1 -- unlucky!
In an ideal world, the second code sample wouldn't compile either.

public static void main(String[] args) throws Exception

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.

Loose blocks of code

When I try running this piece of code, it prints "x y c g ". I know that x has priority over y because it is static and the constructor (c) prints before the method (g), but what exactly is the purpose of putting two lines in their own blocks, and what does this help achieve?
public class Sequence {
Sequence() { System.out.print("c "); }
{ System.out.print("y ");}
public static void main(String[] args) {
new Sequence().go();
}
void go() { System.out.print("g "); }
static { System.out.print("x "); }
}
Your question is closely related to this one, but not exactly a duplicate: Why java Instance initializers?
When you first reference a class, it gets loaded and the static components get initialized in the static initializer. These blocks can be very useful, for setting up collections or loading native code.
An instance initializer is a bit of code that works similar to the static initializer except it operates on every instance before the constructor is invoked. It appears that there is no absolute need for this in Java since it can just be placed in the beginning of your constructor.

Can a method be called by an object inside of the same class?

What I'm trying to understand is why I'm receiving an error when I try to call a method by an object whilst residing in the same class.
My syntax looks correct. I understand the local variables inside of the method are uninitialized, and wanted to see if the compiler would be able to pick this up.
My issue however is, I receive a stupid error from the compiler, when I try to invoke the method on an object of the same class, within the class, as such.
class Wool {
public static void main (String [] args) {
int add() {
int x;
int a = x + 3;
return a;
}
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
There error that I receive from the compiler is:
c Wool.java
Wool.java:5: ';' expected
int add() {
^
I can do the above fine, if the object of type Wool is instantiated in another class, and the object has no issue in invoking the method, to show me the compilation error that the local variables need a value in that method.
I just don't understand why I can't do it in one class. And if it is possible, please could you educate me.
Help would be immensely grateful.
Thank you.
You can't define a method inside another one. You must declare the add method outside of the main method.
Change your code to
class Wool {
int add() {
int x = 0; // give a value to avoid another error
int a = x + 3;
return a;
}
public static void main (String [] args) {
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
You are declaring a method inside main(). You can not do that.
Methods must be declared inside classes, not inside other methods.
Because add() is not defined as a class method, but you define it as "local" method within main, which is not allowed in java. You must change it to
class Woo{
void add(){
....
}
public static void main(String[] args){
new Woo().add();
...
}
}
You have a method directly inside a method:
main(){
add() {
}
}
that's illegal in java.
Put your method add in the body of your class but not in the body of your method main. Or better : leave Java alone :)
You can't declare a method inside a method.
Try this:
public static void main (String[] arts) {
//
}
int add() {
//
}

What is the purpose of void?

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.

Categories