If we define a variable as constant variable, when we use this variable in methods do we have to put method as static ?
static final int AGE=35;
private int daysOfLife(){
return AGE*365;
}
can we define method as like this ?
Even though it is not giving me any errors but is it a good practice to read static data from instance methods?
You shouldn't be only worried about variable / method being static or non - static but about other things too.
I would categorize your actions as - READ & WRITE and here you are trying to READ a default scoped , final & static variable in an INSTANCE , private method.
Concept of statics exits to logically group variables and methods so if your method has only that line and there isn't going to be anything else in that method, I would suggest to keep that grouping consistent and make either that variable an instance variable ( which doesn't make sense if variable is constant among all objects ) and change its scope to private ( if you don't wish variable to be available in same package classes ) OR mark that method as static.
Reading a final & static variable in an instance method is perfectly OK even though writing is questionable ( though final can't be written to but in case variable is not final ) .
Making that variable an instance one is favored if that variable is not going to be accessed by class name somewhere else and then if its going to be class level constant , make it static and change method to be static ( Initializing same constant field in every object will unnecessary cost you memory ) .
As much as i know ....
The 'static' means it is used in a class scope. Meaning it can be used in the entire program. So technically they can be stored in a non-static method, but they'll still be able to be used outside of that instance.
1) there is no need to put method as static because static means it's for class when ever class start running static will run so static block is the thing will run first and only initialize once that's why it's not showing error in compile time
2) other way around we can't put initialize or use non static variable inside static block because static block will run before instance variable so compile time will catch the error
3) Variables that are declared final and are mutable can still be change in some ways; however, the variable can never point at a different object at any time .
4) so there nothing to worry about making method static
Related
I have a variable that is used in one method. So my linter is telling me to make it local. However I like it being a class level variable in case it any one else modifies the code and needs to use that variable. If it is not class level they might miss it in the method and make a new duplicate variable?
Is my logic reasonable or should I just make it a local variable?
Here is the code :
public class CustomPasswordTransformationMethod extends PasswordTransformationMethod {
. . .
private final char DOT_CHAR = '●';
. . .
public char charAt(int index) {
if (index < ((length()) - unObfuscated)) return DOT_CHAR;
return mSource.charAt(index);
}
}
Change to:
private static final char DOT_CHAR = '●';
and now you've created a class constant the right way and the linter will no longer suggest changing it.
Basically the linter is telling you that a private instance variable that is only used in one place is a waste of allocation and should be local to the one place that uses it. By declaring it static, you are telling the compiler you one one copy of a constant for the class which is slightly different. A static constant is allocated once - whereas an instance constant would be created for each instance (and continue to be allocated for the life of each instance), and a local constant would be created for each method call and cleaned up at the end of the call. All of this is in theory - the real implementation of the compiler may optimize things.
Whether to make the constant class-wide or local to a method is a matter of preference for the most part. But to have a non-static final constant only makes sense in very limited cases like if it gets assigned in the constructor and varies from instance to instance.
I'd use as a local variable, accessing a local variable is faster than accessing a field.
In your case, as you are defining a constant, I think it's fine to declare it at a class level. Your logic is reasonable.
Further reading that can help: What is the best way to implement constants in Java?
Or
https://google.github.io/styleguide/javaguide.html
Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.
I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?
A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?
The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.
public static void main(String args[])
{
final int a=0; //ok
int b=1; //ok
static int c=2; //wrong
final static int x=0; //wrong
}
You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.
Anyways, these are the concepts you are mixing up:
variables
final variables
fields
final fields
static fields
final static fields
The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).
Let's try to rapidly describe them.
variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)
final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).
fields define the mutable state of objects, and are declared in classes (class x { int myField; }).
final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).
static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).
final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).
There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.
Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).
Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.
Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant".
I'm unable to differentiate between a final and a final static member.
The final static member is the one which is a static member declared
as final or something else? In which particular situations should they
be used specifically?
Use a final static when you want it to be static. Use a final (non-static) when you don't want it to be static.
A static variable or a final static variable can never be declared
inside a method neither inside a static method nor inside an instance
method. Why?
Design decision. There's just no way to answer that without asking James Gosling.
The following segment of code accordingly, will not be compiled and an
compile-time error will be issued by the compiler, if an attempt is
made to compile it.
Because it violates the rule you just described.
final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant.
On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.
In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.
A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.
final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.
Just to add a minor information to #Bruno Reis 's answer, which I sought to complete the answer, as he spoke about important condition to initialize final fields before constructor ends, final static fields must also be initialized before before static blocks' execution finishes.
You cannot declare static fields in static block, static fields can only belong to a class, hence the compiler error.
A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere. But why should the same variable be declared as final, which will not allow the variable to be changed else where (constant value)?
static so that the variable or method can be accessed without creating a class instance, and there is only one variable for the class instead of one for each instance.
A final class cannot be extended. A final variable cannot have its value changed, it behaves as a constant. And a final method cannot be over-ridden.
The minute a variable is defined as final, it should probably not be referred to as "variable", since it no longer "varies" :)
A static variable is not tied to any particular instance of a class -- it is only tied to the class itself and only from a scoping standpoint.
So there you are -- a static and final variable is actually a value that is not tied to any particular instance of class and does not vary. It is a constant value, to be referenced from anywhere in your Java code.
At some point, when you should decide to change the value of this constant, it only takes one change to propagate this change correctly to all other classes that use this constant.
A variable declared as static means that its value is shared by all instances of this class. Declaring a variable as final gives a slightly better performance and makes your code better readable.
local variables are on the stack and are not static.
You can have a static field which may or may not be final. You would make the field final if it is not going to change.
static fields can be modified (e.g. public static fields can be modified by any class). static final fields cannot be modified after initialization.
Like you mention yourself, this is done to create constants. You create a single field to hold a value with a specific meaning. This way you don't have to declare that value everywhere, but instead you can reference the static.
Static has nothing to do with getting the latest and single copy unless "single copy" here means one and the same value for all the instances of a class (however, I think you may be confusing it with volatile). Static means class variable. You make it final when you want that to be a constant (that's actually the way Java constants are declared: static final).
static final is used in Java to express constants. Static is used to express class variables, so that there is no need to instantiate an object for that class in order to access that variable.
Final methods can't be overriden and final variables can only be initialised once.
If you only use the static keyword, that value will not be a constant as it can be initialised again.
May be to provide something similar to constants.
Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.
for example user.lastName lastName should be field because it is needed during object lifecycle
Variables should be declared as static only if they’re not required for use in more than one method of the class or if the program should not save their values between calls to the class’s methods.
for example Math.max(num1,num2) Im not intristed in num1 and num2 after compleating this operation
Final stops any classes inheriting from it
You create static final variable to make its value accessible without instantiating an object.
E.G.:
public class MyClass
{
public static final String endpoint= "http://localhost:8080/myClass":
/* ...*/
}
Then you can access to the data using this line:
MyClass.endpoint
When you declare a final variable (constant) in a class, for example:
private static final int MyVar = 255;
How much memory will this require if I have 100,000 instances of the class which declared this?
Will it link the variable to the class and thus have 1*MyVar memory usage (disregarding internal pointers), or will it link to the instance of this variable and create 100,000*MyVar copies of this variable?
Unbelievably fast response! The consensus seems to be that if a variable is both static and final then it will require 1*MyVar. Thanks all!
The final keyword is irrelevant to the amount of memory used, since it only means that you can't change the value of the variable.
However, since the variable is declared static, there will be only one such variable that belongs to the class and not to a specific instance.
Taken from here:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized . A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
There will be only 1*MyVar memory usage because it is declared as static.
The static declaration means it will only have one instance for that class and it's subclasses (unless they override MyVar).
An int is a 32-bit signed 2's complement integer primitive, so it takes 4 bytes to hold it, if your example wasn't using static you'd just multiply that by the number of instances you have (for your example of 100,000 instances that's 0.38 of a megabyte - for the field alone, extra overhead for actual classes).
The final modifier on a field means it cannot be repointed to another value (whereas final on a class of method means it cannot be overridden).
It's static and thus class scope -> 1.
Edit: actually, it depends on the class loaders. In the general case you have one copy of the class but if you have multiple class loaders/class repositories (might be the case in application servers etc.) you could end up with more.
In addition to the fact that static fields belong to their classes, and thus there is only one instance of static varaible per class (and per classloader), it's important to understand that static final variables initialized by compile-time constant expressions are inlined into classes that use them.
JLS §13.1 The Form of a Binary:
References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed.
So, in practice, the instance of static final variable that belong to its class is not the only instance of value of that variable - there are other instances of that value inlined into constant pools (or code) of classes that use the variable in question.
class Foo {
public static final String S = "Hello, world!";
}
class Bar {
public static void main(String[] args) {
// No real access to class Foo here
// String "Hello, world!" is inlined into the constant pool of class Bar
String s = Foo.S;
System.out.println(s);
}
}
In practice it means that if you change the value of Foo.S in class Foo, but don't recompile class Bar, class Bar will print the old value of Foo.S.
static means you will have only one instatnce
final just means, that you can't reassign that value.
The crucial part here is that you declared the variable as static because static variables are shared among all instances of the class, thus requiring only as much space as one instance of the variable. Declaring a variable final makes it immutable outside its declaration or constructor.
final makes is 1*instances memory usage.
However, static makes it simply 1.
The keyword "final" helps you to declare a constant with a specific amount of memory, where as the keyword "static" as its prefix will gives a single instance of this constant, what ever be the amount of memory consumed...!!!
Static means, one instance per class, static variable created once and can be shared between different object.
Final variable, once value is initialized it can't be changed. Final static variable use to create constant (Immutable) and refer directly without using the object.
It's static, so there will be only one instance created, so however many bytes are required to hold one int primitive will be allocated
You will have one instance per class. If you have the class loaded more than once (in different class loaders) it will be loaded once per class loader which loads it.
BTW: Memory is surprising cheap these days. Even if there was a copy per instance, the time it takes you to ask the question is worth more than the memory you save. You should make it static final for clarity rather than performance. Clearer code is easier to maintain and is often more efficient as well.
I want to know what could be the equivalent keyword in java which could perform same function as "Static keyword in C".. I want to do recursion in java, performing same function that a static keyword in C does...
Please help..
C has two entirely different uses of the static keyword, and C++ adds a third use:
// Use 1: declare a variable or function to be local to a given module
// At global scope:
static int global_var;
static void func();
In this case, the global variable global_var and the function void func() can only be accessed inside the file in which they are declared; they cannot be accessed by any other file.
// Use 2: declare a variable inside a function with global scope
void func(void)
{
static int x;
}
In this case, the variable x is effectively a global variable, in that there is only one instance of it -- multiple calls to func() (including recursive calls) will always access the same variable.
// Use 3 (C++ only): declare a global variable with class scope
class Widget
{
public:
static int var;
};
In this case, this declares the variable Widget::var as a global variable, but its scope is different. Outside of class member functions, it has to be named as Widget::var; inside class member functions, it can be named as just var. It can also be made protected or private to limit its scope even more.
Now, what are the analogs of these 3 uses in Java?
Case 1 has no direct analog; the closest is declaring objects with package scope, which is done by omitting a public, protected, or private:
class Widget // Declare a class with package scope
{
int x; // Declare a member variable with package scope
void func() {} // Declare a member function with package scope
}
In this case, the declared objects are only accessible by classes within the same package; they are not accessible to other packages.
Case 2 also does not have an analog in Java. The closest you can get is by declaring a global variable (that is, a static class variable, since Java doesn't have true global variables in the strictest sense):
class Widget
{
private static int func_x;
public static void func()
{
// use func_x here in place of 'static int x' in the C example
}
}
Case 3 is the only case that has a direct analog in Java. In this case, the static keyword serves exactly the same purpose.
The "static" keyword in C actually serves two functions depending on where it's used. Those functions are visibility and duration (these are my terms based on quite a bit of teaching, the standard, if you're interested in that level of detail, uses different terms which I often find confuses new students, hence my reticence in using them).
When used at file level, it marks an item (variable or function) as non-exported so that a linker cannot see it. This is static as in visibility, duration is the same as the program (i.e., until the program exits). This is useful for encapsulating the item within a single compilation unit (a source file, in its simplest definition). The item is available to the whole compilation unit (assuming it's declared before use).
When used within a function, it controls duration (visibility is limited to within the function). In this case, the item is also created once and endures until the program exits. Non-static variables within a function are created and destroyed on function entry and exit.
I gather what you're after is the first type, basically a global variable since I can't immediately see much of a use for the other variant in recursion..
It can't be done since, in Java, everything must belong to a class. The workaround is to create a class holding the "globals" and either:
pass that object around so you can reference its members; or
construct a singleton item so you can access its members.
Java doesn't have global variables, so there isn't a direct equivalent. However, there's a static keyword in Java that shares the state of a field with all instances of a class, which is a good approximation to what you're describing.
I want to do recursion in java, performing same function that a static keyword in C does...
However, if you're looking to do recursion, are you sure that static variables are what you need? Any special state needed for a recursive function call is almost always passed back to itself, not maintained separately.
The concept of static in Java doesn't adhere with the concept of static in C. However, there is a static keyword in Java as well. But its more like a static in C++ then C, with some differences.
You can simulate a static class in java as follows:
/**
* Utility class: this class contains only static methods and behaves as a static class.
*/
public abstract class Utilities
{
// prevent inheritance
private Utilities()
{
}
// ... all your static methods here
public static Person convert(string) {...}
}
This class cannot be inherited (like final because although abstract it has a private constuctor), cannot be instantiated (like static because abstract) so only static methods in it can be called.