Java Error - Illegal Modifier for Parameter - Only final Permitted - java

What's wrong with the below Code
public static void main(String[] args){
public static final String Name = "Robin Wilson";
}
String Reference Name shows Compilation Error - Java Error - Illegal Modifier for Parameter Name - Only final Permitted
Am okay with the below given suggestions, but I want to understand why its not permitted, though both are static?

Your have modified your question to ask:
I want to understand why it is not permitted, though both are static?
Variables inside a method exist only on the stack frame. The JVM creates a new stack frame every time a method is invoked, and it is discarded once the method completes.
The public keyword is used on classes, methods and fields to control access. There is no concept of access that could be applied to a stack (local) variable. It only exists inside the method when it's called, and can only be accessed from within the method.
The static keyword is used on fields to denote that only one such member exists across all instances of a class, and on methods to create them as members of the class that do not require an instance. There is no concept of a static state for anything on the stack; it is temporary. The stack frame and all the local variables on it cease to exist once you return from a method call.
Basically, neither make any sense when talking about a local variable.

How to fix it
public and static cannot be used inside a method definition. So this error is telling you that the only modifier allowed for a variable defined inside of a method is final.
You fix it by either by removing the offending modifiers:
class MyClass
{
public static void main(String[] args){
final String Name = "Robin Wilson";
}
}
or moving the variable definition out of the method like this
class MyClass
{
public static void main(String[] args){
}
public static final Name = "Robin Wilson";
}
Explanation
To understand why, you need to understand what each of the three modifiers (public and static and final) means on its own. String Name just says that we are keeping track of a String and calling it Name.
public
class MyClass
{
public String Name = "Robin Wilson";
}
public says that any part of the program can read it (otherwise it could only be read by code written in the MyClass class).
public specifies what other code has access to it. Inside a method this doesn't make sense. Variables defined inside methods can only be accessed while inside that method, and once the method is complete they are thrown out. So it would be impossible for those variables to be public.
static
class MyClass
{
static String Name = "Robin Wilson";
}
static says that the Name variable is a part of the class itself, not of an instance of the class. In other words, all instances of the MyClass class share the same Name variable.
static specifies how it is accessed (either on an instance of the class or through the class itself). Inside a method this doesn't make sense, because local variables are discarded after the method closes, so nothing else will be accessing it.
final
class MyClass
{
final String Name = "Robin Wilson";
}
final says that the value of Name will never change once it has been assigned.
final describes how the variable is going to be used. It makes sense within a method, because it is not about access.

You can't declare this inside main, put it outside the method, you want it as a [class member]:
public static final String Name = "Robin Wilson";
public static void main(String[] args) throws IOException { }
Otherwise(I don't think this is what you want) just remove public static from there and simply write:
public static void main(String[] args){
final String Name = "Robin Wilson";
}

you can not use public static modifier for a local variable. Do any of the followings
public static void main(String[] args){
final String Name = "Robin Wilson";
}
or declare it as a member variable
public static final String Name = "Robin Wilson";
public static void main(String[] args){
}
Remember that the final is the only modifer of the local variables

Your can not declare a local variable(variables inside methods are local variables) as public static. Instead, the following code will work:
public static void main(String[] args){
final String Name = "Robin Wilson";
}

as you are Declaring the String variable as public static final String Name = "Robin Wilson";
According to java rules, This String name is Local variable as you are declaring it in Main method. So only final is permitted here.
you can define it as ** final String name="Robin Wilson";** in main method.
for Local variables only final is permitted.

Static declaration of a component makes in available on a class level. Declaring component in a method makes in available in method's stack memory hence can only be accessed through an object. Static belongs to the whole class. Therefore their is no point in declaring a variable static. You'll even get the compile time error if you try to do so.
Final keyword has nothing related to memory.

its mean you should write your static function outside the "main" block. It will work fine. Enjoy

The modifiers private, protected, and public cannot be used on variables inside of a method. This is because you can only have local variables inside of methods.
Java is simply telling you that the only modifier allowed at that time is the final keyword.

Related

Getting error: non-static variable this cannot be referenced from a static context when trying to construct a class inside a static method [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

non-static variable this cannot be referenced from a static context. I don't know how to solve [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

Cannot make a static reference to the non-static field "n" [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

How to make a private variable in a public method

I have a public method but there is a variable inside that I don't want other classes to access. Could I do that like this?
public static void example() {
private {
String privateString = "Can I do it like this?";
}
}
Thanks.
No need, method local variables are local.
public static void example() {
String privateString = "Can I do it like this?"; // <-- like this
}
Or, you could make it a class level variable visible to every method in the same class,
private static String privateString = "Can I do it like this?";
A local variable is scoped to the method (or constructor) that declares it. No other methods can access it. Your problem is a non issue.
The use of private is for class scoped variables (and methods). The method's locally declared variable's scope is restricted to the method only (so it is already kinda private).
variable declared inside method is local,scope of this variable within a body only. so no need to make it as private
public void show() {
String x="Hii"; }//<--like this
variable x is local to that method. so that no one can access this variable.
we can make it as private in class level also
class Global{
private String x="hii";
public static void main(String... n){
System.out.println("x ="+x);}}
we use this variable anywhere inside a class but we cannot access outside the class.

Static method in java

I heard that static methods should use only static variables in java.
But, main method is also static, right?
Your question: is the statement " static methods should use only static variables" correct?
No. The statement is not correct.
The correct statement will be "static methods can only use those instance variables that are defined static"
Take a look at following code and read the comments:
Class A{
int i;
static int j;
public static void methodA(){
i = 5; //cannot use since i is not static
j = 2; //can use.
int k = 3; //k is local variable and can be used no problem
**EDIT:**//if you want to access i
A a = new A();
//A.i = 5; //can use.
a.i = 5; // it should be non-capital "a" right?
}
}
First of all, a technicality: it's NOT true that "main method is also static". You can define a non-static main method, with whatever signature you choose; it just won't be a valid Java application entry point.
With regards to "static methods should use only static variables", this is also NOT true. The key concept here is that static methods and fields are class-specific, not instance-specific. You simply can't access an instance variable/method if you don't actually have an instance of that class; it's a compilation error.
So to be precise, without an instance, you can't access instance fields/methods. You can access static fields/methods without an instance. If you need to access instance fields/methods from a static method, you have to get an instance of that class one way or another, either by simply instantiating it, or by getting a reference to it from a static field or method parameter.
Let's take a look at this simple example:
public static void main(String args[]) {
System.out.println(args.length);
}
length is NOT a static field; it's an instance field of array instances, which args is. The static method main is able to get this instance (and thus access its instance methods and fields) because it's passed in as an argument.
Also, println is NOT a static method; it's an instance method of PrintStream instances. The static method main is able to get this instance by accessing the static field out of the class System.
To summarize:
A Java application entry point is a method that:
is named main
is public and static
returns void and takes a String[] argument as parameter
A method named main doesn't have to be a Java application entry point
(but it's best to reserve this name for that purpose)
Furthermore,
Instance fields/methods can only be accessed through an instance
Static fields/methods can be accessed without an instance
Static methods can get an instance of a class by one of the following ways:
creating a new instance
having it passed as an argument
accessing it through a static field of a class
accepting it as the return value of a static method of a class
catching it as a thrown Throwable
Maybe this piece of code will enlighten you:
public class Main {
private String instanceField = "Joe";
private void instanceMethod() {
System.out.println("Instance name=" + instanceField);
}
public static void main(String[] args) {
// cannot change instance field without an instance
instanceField = "Indy"; // compilation error
// cannot call an instance method without an instance
instanceMethod(); // compilation error
// create an instance
Main instance = new Main();
// change instance field
instance.instanceField = "Sydney";
// call instance method
instance.instanceMethod();
}
}
So you cannot access instance members without an instance. Within the context of a static method you don't have a reference to an instance unless you receive or create one.
Hope this helps.
To access non-static fields (instance variables) you need to have an instance.
Inside a non-static method, this is used as default instance:
class AnyClass {
private String nonStaticField = "Non static";
void nonStaticMethod() {
this.nonStaticField = "a text"; // accessing field of this
nonStaticField = "a text"; // same as before
}
}
Inside a static method there is no this to use as default instance, but you can1 still access instance variables if you provide the instance:
class AnyClass {
private String nonStaticField = "Non static";
static void staticMethod() {
AnyClass example = new AnyClass();
example.nonStaticField = "new value for non-static field";
}
}
1 - the field must also be accessible by Java's access control (declared public or in the same class ...)
A static method is called on a class instance and not to an object of a class. This means, that a static method is not able to access instance variables, because they are only instantiated in an object.
If you want to access an instance variable with a static method, you have to declare that variable as static.
public class Test {
private static int value = 0;
public static void main(String[] args) {
value++;
}
}
But to be honest, it's not the best idea to write everything in static methods. It's better to use the main method to instantiate new objects.
One important thing is that unless u create an instance of an class the instance variables don't exist practically it means JVM doesn't that there os an variable like int i unless u create an instance for that class. so, using an instance variable in a static method is an compilation error.
class A{
int i;
static int j;
static int b(){
i=10; // cannot be found
A a= new A();
a.i=10;//can be found in a's instance
}
}
But, we can use instance variables in instance methods because, instance methods are only called when object created so there is no problem in using instance variables inside it.
Hope ur clear about these things!
Yes static method cannot call non-static methods or variables of the class directly.
EDIT : One can create any local variables.
The static method can't access non-static variables outsides because you can use static method without class initialization, but it doesn't work for non-static outside variable. But you can define and use non-static variable in the static method.

Categories