I'm new to JAVA. So, please bear with me.
I wondered whether JAVA println() has multiple arguments support, And did identify that the answer is yes,
This is what I made :)
public class Main {
String Name; // If I declare this inside main() error pops up
public static void main(String[] args) {
System.out.println("Hey Guys!");
Main obj = new Main();
obj.Name = "Monish";
System.out.println("I'm " obj.Name);
}
}
So, my question is why can't we declare "Name" inside main()?
If I do so, I get this error, Name cannot be resolved or is not a field
CodePudding user response:
You can declare Name
inside of main
if you wish. The error "Name cannot be resolved or is not a field" would only occur after declaring Name
inside main
if you didn't update your references to Name
.
public class Main {
public static void main(String[] args) {
String Name;
System.out.println("Hey Guys!");
Main obj = new Main();
Name = "Monish";
System.out.println("I'm " Name);
}
}
Note that this does defeat the purpose of creating an instance of the Main
object with Main obj = new Main()
. The object oriented version uses Name
as a property of class Main
instead of a local variable. Both are valid.
CodePudding user response:
As per your current implementation, Name
is a property of the Main
class. Hence it needs to be accessed using object of Main
class.
You can declare Name
inside main()
method of your Main
class, in which case Name
will become a method-local variable. Such method local variable needs to be accessed using variable name directly.
CodePudding user response:
In your example you declare a method variable, but you try to use a Main's instance variable, and the compiler say it is an Error.
you have 3 different solution
- use a Main's instance variable (your example)
or my
using a method variable:
public class Main { public static void main(String[] args) { System.out.println("Hey Guys!"); String name = "Monish"; System.out.println("I'm " name); } }
using a Main's static variable and in this case you can use name or Main.name as equivalent (of course if there is no other method variable called "name" ).
public class Main { static String name; public static void main(String[] args) { System.out.println("Hey Guys!"); name = "Monish"; System.out.println("I'm " name); } }