I declare and initialize a variable in a static method. How can I use this variable in another static method? I have tried to call the variable by the static method's name.
How do I use a variable that is declared and initialized in one static
method and use it in another static method?
You can't . Cause the variable's scope belongs only to the method where was declared.
An alternative is making the variable as a class variable , then all methods can use this variable.
public class Test {
private static int variable;
public static void method1(){
variable++;
}
public static void method2(){
variable--;
}
}
Take care if multiple threads access to these methods.
you can't because if you declaer in one method is this varible local, you must declare as global varibl and initilized in method.
you have to have the variable outside of the method and make it static too.
ex:
public static int accessMeOutside = 0;
public static void methodOne(){
accessMeOutside = 1;
}
public static void methodTwo(){
if(accessMeOutside == 1)
accessMeOutside = 2;
}
if you call methodOne, then methodTwo, accessMeOutside will end up correctly being set as 2.
Related
I have a simple question that I just can't figure out a good answer for. Why does the following Java program display 20? I would prefer a detailed response if possible please.
class Something{
public int x;
public Something(){
x=aMethod();
}
public static int aMethod(){
return 20;
}
}
class SomethingElse extends Something{
public static int aMethod(){
return 40;
}
public static void main(String[] args){
SomethingElse m;
m=new SomethingElse();
System.out.println(m.x);
}
}
Because polymorphism only applies to instance methods.
The static method aMethod invoked here
public Something(){
x=aMethod();
}
refers to the aMethod declared in Something.
The inheritance for static methods works differently then non-static one. In particular the superclass static method are NOT overridden by the subclass. The result of the static method call depends on the object class it is invoke on. Variable x is created during the Something object creation, and therefore that class (Something) static method is called to determine its value.
Consider following code:
public static void main(String[] args){
SomethingElse se = new SomethingElse();
Something sg = se;
System.out.println(se.aMethod());
System.out.println(sg.aMethod());
}
It will correctly print the 40, 20 as each object class invokes its own static method. Java documentation describes this behavior in the hiding static methods part.
Because int x is declared in the class Something. When you make the SomethingElse object, you first make a Something object (which has to set x, and it uses the aMethod() from Something instead of SomethingElse (Because you are creating a Something)). This is because aMethod() is static, and polymorphism doesn't work for static methods. Then, when you print the x from m, you print 20 since you never changed the value of x.
I have created one interface which looks like below:
public interface CalculatorInterface
{
int x=10; int y=15; int z=x+y;
public void add1();
}
Then i created one class which is implementing it. The class looks like below:
public class AdvClass2 implements CalculatorInterface {
public static void main(String[] args) {
int x=50;
System.out.println("X value is" +x);
}
#Override
public void add1() {
System.out.println("I am in Add Method");
}}
But the rule says i am not allowed to change interface variable value right. Can somebody tell me what am i doing wrong?
Variables in interface are by default static final ( you can call it as static constant ) variables ,so you can assign value to it only once , it's value cant be changed afterwards.
check this site for final keyword - https://www.javatpoint.com/final-keyword
You are actually changing the local variable in the main function. This variable is different from the one you declared in the interface which is indeed public, static and final by default. But there are no such restrictions on local variables.
Also if there is a variable with same name in the local scope then that variable is preferred over the variable with same name in the outer scope.
Edit:
As I explained earlier you are declaring x as local variable in main function and it is different from the variable x in the interface. In your main function do the following if you want a compile error while trying to change the interface x variable:
public static void main(String[] args) {
x=50;
System.out.println("X value is" +x);
}
Now you will see a compile error telling you the interface's x variable cannot be assigned.
Since an interface can not be instantiated directly, the interface variables are static and final by default. We are not allowed to change them.
Interfaces can't contain any implementation. A Java interface can only contain method signatures and fields.
I think you need a better design. So the interface should be like:
public interface ICalculator {
public int add1(int a, int b); // this is the method signature, not the implementation.
}
Then in the AdvClass2 you can implement the add1 method:
#Override
public int add1(int a, int b) {
int result = a + b;
return result;
}
I can see that static object of non-static class cannot be created inside a method?
Code:
public class Rent {
public void abc() {
System.out.println("Non static method");
}
public static void def() {
System.out.println("this is static method");
}
}
public class SampleJava {
public static void main(String[] args) {
Rent r1 = new Rent();
public static Rent r2; //not allowed in static method
}
public static Rent r3; //allowed outside method
public void def() {
Rent r4 = new Rent();
public static Rent r5; //not allowed in non-static method either
}
}
There are few points you have to consider:
Static Data is similar to a Static Method. It has nothing to do with the instance. A value that is declared static has no associated instance. It exists for every instance, and is only declared in a single place in memory. If it ever gets changed, it will change for every instance of that class.
The access modifiers you have used are only allowed for class level and not method level.
In your example:
public static void main(String[] args) {
Rent r1 = new Rent();
public static Rent r2; //Will give compile time error.
}
Considering the purpose of "Static", if you are declaring the static object inside the method then its scope will be bind to that particular method only.
Usually the static objects are used to maintain the state.
For e.g. your database connection logic may have a singleton class and the object of this class should keep your state of database connection.
These objects needs to be and must be at class level.
The errors you are getting have nothing to do static/instance access. They are just compile time errors because of invalid Java syntax.
You cannot use field modifiers like public and static for declarations of local variables inside a method (be it a static or an instance method).
Just remove the unnecessary modifiers:
public static void main(String[] args) {
Rent r1 = new Rent();
Rent r2;
}
public static Rent r3;
public void def() {
Rent r4 = new Rent();
Rent r5;
}
First of all you are not allowed to declare variables with access modifiers(public, private, protected) within a method. You are also not supposed to declare variables as static within a method.
Those variables you declared outside the methods are members of a class.
There are 2 types of variables:
Instance variables (non-static members)
Class variables (static members)
I can see that static object of non-static class cannot be created inside a method?
static means it belongs to the class. It exist even before you instantiate the object. That is why you could invoke a static method through the class directly.
So what are static members?
static members are shared by all objects from the same class.
it exist even before you instantiate (create) an object.
it belongs to the class, and not any individual object.
Example:
class Pond
{
static double waterTemp = 17.5; //Every Pond object shares the same value
int numFishes; //Belongs to each individual Pond object
}
How to access static members:
System.out.println(Pond.waterTemp); //Preferred
System.out.println(Pond.numFished); //Not allowed
//OR
Pond pond = new Pond();
System.out.println(pond.waterTemp); //Not necessary, but allowed
System.out.println(pond.numFished); //The only way to get numFishes
A non-static method is associated with an instance and hence is required that an instance be created before it can be accessed. However, a static method is related to class and not hence it should be available for use even without an instance. These constraints cause the static method to not be created inside an non-static method.
public class A{
public static void main(String[] args){
static final int MAX_VALUE = 100; //COMPILE TIME ERROR
System.out.println("MAX_VALUE");
}
}
Why static final int MAX_VALUE=100; gives compile time error, it gives the error as "illegal modifier for parameter MAX_VALUE;only final is permitted "
You cannot declare static variable inside methods.
Static variables belong to the class; variables declared inside a method are local variables and belong to that method.
Static variables belong to the class.Not methods
The variables declared inside a method are local variables and belong to that method.
So it becomes
final int MAX_VALUE = 100;
Prefer to read : Docs on Understanding Instance and Class Members
The keyword static cannot be used inside methods. This would be valid code:
public class A{
static final int MAX_VALUE = 100; // This line can't go in a method.
public static void main(String[] args){
System.out.println("MAX_VALUE: "+MAX_VALUE);
}
}
A local variable can not be static. You can either create a final local variable, or a final static class variable (which are actually constants, btw.), but not a local static variable:
public class A{
static final int CLASS_CONST = 42;
public static void main(String[] args){
final int LOCAL_CONST = 43;
...
}
}
You can't delcare static things inside a method. Move it up a line.
Change
public class A{
public static void main(String[] args){
static final int MAX_VALUE = 100; //COMPILE TIME ERROR
System.out.println("MAX_VALUE");
}
}
To
public class A{
static final int MAX_VALUE = 100; //NO ERROR YAY!!
public static void main(String[] args){
System.out.println("MAX_VALUE");
}
}
you can't create static final in a method, you must create it outside the method:
public class A {
static final int MAX_VALUE = 100;
public static void main(String[] args){
System.out.println("MAX_VALUE");
}
}
static variables are class level variables ,you can't declare them at method.
According Docs
Sometimes, you want to have variables that are common to all objects.
This is accomplished with the static modifier. Fields that have the static
modifier in their declaration are called static fields or class variables.
They are associated with the class, rather than with any object
Others already pointed out that static members belong to the class instead of a specific instance. So you don't have to create a class instance to use a static member, rather you can call SomeClass.SOME_STATIC_MEMBER directly.
You cannot call any other member of a class that is not static without instantiating that class. Meaning if you have-
public class SomeClass {
public int add (int x, int y){
return x + y;
}
}
For you to use add method of SomeClass above, you have to instantiate first-
SomeClass someClass = new SomeClass();
int sum = someClass.add(5, 10);
So, there is no point of allowing us to declare static members in a non-static method as for us to use that method, we have to instatiate the class where that method belongs to.
you should declare this constant in the class A, not in the main() method
public class A{
static final int MAX_VALUE = 100; //COMPILE TIME ERROR
public static void main(String[] args){
System.out.println("MAX_VALUE");
}
}
I just read in a document that "A static method can call only other static methods and can not call a non-static method from it". But when I tried to test it I think saw something different.
I have a class C which is described below
import pckage1.*;
public class C
{
public static void main(String par[])
{
}
public static void cc()
{
A ob = new A();
ob.accessA(0);
}
}
where class A is
package pckage1;
public class A
{
public A()
{
}
public void accessA(int x)
{
}
}
Now here from cc STATIC method in class C, a NON STATIC method accessA() is called. How could that be possible if the statement about static method is true?
A static method can call only other static methods and can not call a non-static method from it
That's wrong.
Static methods can call non-static methods as long as they have objects to call the methods on (as you discovered in your code snippet). How else would a non-static method ever be called?
You can't do nonStaticFoo() from a static method, since it is interpreted as this.nonStaticFoo() and since there is no this available in a static method.
Very similar question from earlier today:
Static method access to non-static constructor?
You didn't call a non-static method of your Class.
Try with this :
import pckage1.*;
public class C
{
public static void main(String par[])
{
}
public static void cc()
{
A ob = new A();
ob.accessA(0);
print();
}
public void print()
{
}
}
It won't work, because you're callign a non-static method from a static method, and you don't have an instance of the C class to work with in your static method.
Since every Java program starts executing from a static method, if the statement you cite were true, there would have been no way for any Java program to ever execute an instance method!
A static method has no default context in C, and not this.
However any method can use an intsnace of a class to call a method.
You're calling an instance method, on an instance--you're not trying to call an instance method directly.
You're creating an instance of class A and call a method on it.
So the method you are calling is instance method (not static method).
But you cannot call a non static method of class C.