This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java: is using a final static int = 1 better than just a normal 1?
Well I'd like to know what difference between:
final int a=10;
and
final static int a=10;
when they're the member variables of a class, they both hold the same value and cannot be changed anytime during the execution.
Is there any other difference than that the static variable is shared by all the objects and a copy is created in case of non-static variable?
There is no practical difference if you initialize the variable when you declare it.
If the variable is initialized in a constructor, it makes a big difference.
See the example below:
/**
* If you do this, it will make almost no
* difference whether someInt is static or
* not.
*
* This is because the value of someInt is
* set immediately (not in a constructor).
*/
class Foo {
private final int someInt = 4;
}
/**
* If you initialize someInt in a constructor,
* it makes a big difference.
*
* Every instance of Foo can now have its own
* value for someInt. This value can only be
* set from a constructor. This would not be
* possible if someInt is static.
*/
class Foo {
private final int someInt;
public Foo() {
someInt = 0;
}
public Foo(int n) {
someInt = n;
}
}
A static variable is accessible via the dot separator outside of it's class definition.
So if you have a class called myClass and inside it you have static int x = 5;
then you can refer to it with myClass.x;
The final keyword means you are not allowed to change the value of x after it has been defined. The compiler will stop with an error if you attempt to do so.
As a static variable, you don't need an instance of the class to access the value. The only other difference is that the static field is not serialized (if the class is serializable). It's also possible that all references to it in compiled code are optimized away.
The difference doesn't show up if you're only using ints. However, as an example of how it's different:
class PrintsSomething {
PrintsSomething(String msg) {
System.out.println(msg);
}
}
class Foo {
public static final PrintsSomething myStaticObject = new PrintsSomething("this is static");
public final PrintsSomething myLocalObject = new PrintsSomething("this is not");
}
When we run this:
new Foo();
new Foo();
...the output is this:
this is static
this is not
this is not
I would point out, that the static modifier should only be used with explicit needs, and the final only for constants.
Related
In C++(prior to C-11), we needed to initialize the variables outside the Class either through constructors or some methods. What's happens in Java?
Can a Variable be initialized inside a Class in Java?
Yes, like this:
public class MyClass {
private int myVariable = 10;
}
What about Static Variable? If yes, then what's the use for Static Block?
Yes, static variables can be initialized in the class as well:
public class MyClass {
private static int myVariable = 10;
}
Static blocks are used when you want to initialize a static variable, but one line is insufficient. For example:
public class MyClass {
private static HashMap<Integer, Integer> myMap;
static {
myMap = new HashMap<>();
myMap.put(10, 20);
myMap.put(20, 40);
}
}
c++ v/s Java:
Common- both OOP language
difference- c++ is not purely object oriented language, but Java is purely oop language.
Classes are blueprint(like a general map) which defines some attributes/properties(Member variables) and behavior(member functions) of a object of that class.
Class is just a imagination before creation of a object.
Object is real time entity that has physical existence in real world or in simply it's a implementation of class.
Classes in java:
class class_name
{
member variables;
member functions;
};
Ex.
class A
{
int a;
void funct()
{
//body
}
}; //defination is closed with semicolon
but,
classes in java:
ANSWER to ur quesion:
class class_name
{
member variables; //still we define the attributes in class that may be static or non-static
member functions;
};
Significance of static variable:
static variable is alloacated the common memory in ram for all the objects of that class and operation perform by any object on static member is reflected to all other object's static member because of common(same) memory.
significance of static method(functions are called methods in java): static method of a class is a method which is called without creating the object of that class.
In java, main() method is declared as static because after execution of program main() method is called without creating the object of class.
kernal of OS calls the main() method.
Can a Variable be initialized inside a Class in Java?
Yes.
class TestClass {
int abc = 0;
static int def = 1;
}
What about Static Variable?
Yes, you can. Same Example as above.
But this won't be initialized every time an object of the class is created.
TestClass ob1 = new TestClass();
ob1.def = 2; // Always use the class name to access static variables. This is just an example.
TestClass ob2 = new TestClass();
System.out.println(ob2.def); // Output : 2
PS : Always use the class name to access static variables. This is just an example.
What's the use for Static Block?
If the initialization of static variables is complex, then you can create a static block and initialize those variables there. Here is a good reference for the same.
class TestClass {
int abc = 0;
static int def = 1;
static {
int x = 100;
int y = 20;
def = x - y + 10;
}
}
If you wat to initialize the variable you can create something like
public class Animal
{
int age = 21;
static int roll = 23;
}
But remember the difference between instance variables and static variables,
int age - this variable is created for each object you create
static int roll - this variable is created only once and is one for every other object.
This question already has answers here:
Initialize a static final field in the constructor
(8 answers)
Closed 6 years ago.
I was experimenting with initialisation of different type of variables in Java. I can initialise final variable (e.g. final int b) and static variable (e.g. static int c) in constructor but I can't initialise static final variable (e.g. static final int d) in constructor. The IDE also display error message.
Why might Java not allow initialisation of static final variable in constructor?
public class InitialisingFields {
int a;
final int b;
static int c;
static final int d;
InitialisingFields(){
a = 1;
b = 2;
c = 3;
d = 4;
}
public static void main(String[] args) {
InitialisingFields i = new InitialisingFields();
}
}
Error message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot assign a value to final variable d
at JTO.InitialisingFields.<init>(InitialisingFields.java:22)
at JTO.InitialisingFields.main(InitialisingFields.java:26)
Java Result: 1
A static variable is shared by all instances of the class, so each time to create an instance of your class, the same variable will be assigned again. Since it is final, it can only be assigned once. Therefore it is not allowed.
static final variables should be guaranteed to be assigned just once. Therefore they can be assigned either in the same expression in which they are declared, or in a static initializer block, which is only executed once.
Because
the static variable must be set whether or not you create an instance of the class, so it must happen outside a constructor;
it can only be set once, so you couldn't change its value the second time you create an instance.
You can read a static final variable before it is initialised, and its value would be the default value for the type, e.g.
class Nasty {
static final int foo = yuk();
static final int bar = 1;
static int yuk() {
System.out.println(bar); // prints 0.
return 99;
}
}
However, this is a bizarre case, and almost certainly not what is desired.
You can't reassign final field. Final means that variable can't be changed. Remove final and you are ok.
This question already has answers here:
What is an initialization block?
(10 answers)
Closed 7 years ago.
I read that an initializer block is "an unnamed code block that contains th code that initializes the class?
For example :
class A {
final int x;
final int y;
final String n;
{
x = 10;
y = 20;
}
public A(String name ) {
/* etc... etc */
I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?
thanks
I think it can sometimes be helpful to initialize a variable immediately when it is defined.
public class Stooges {
private ArrayList<String> stooges = new ArrayList<>();
{ stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }
// ... etc. other methods.
}
That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!
There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.
A common use for this is the static initializer block:
class A {
static boolean verbose;
final int x;
final int y;
final String n;
static {
verbose = doSomethingToGetThisValue();
}
public A(String name ) {
/* etc... etc */
This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).
See also this SO answer.
Newbie to Java here. I'm in the process of porting my iPhone app to Android. From what I've read, the final keyword is pretty much equivalent to static. But does it work the same inside a method?
For example in Objective-C inside a method... static Class aClass = [[aClass alloc] init]; wouldn't be reallocated again and it wouldn't be disposed at the end of the method.
Would something in Java inside a method like... final Class aClass = new aClass(); act the same?
No. Block-local variables go out of scope when the block is exited and are logically (and usually physically) allocated on the stack.
Java isn't really like Objective C in that respect, and final is more akin to const because it indicates a reference may not be altered. In your example, when the block ends the final variable will be eligible for garbage-collection as it is no longer reachable. I think you want a field variable something like
static final aClass aField = new aClass();
Note that Java class names start with a capital letter by convention...
static final MyClass aField = new MyClass();
You are confusing the meaning of Final and Static.
Final means that the value of the variable cannot be changed after its value is initially declared.
Static means a variable can be accessed and changed without needing to instantiate a class beforehand.
Perhaps the following bit of code will make this more clear.
public class SF1 {
static int x;
final int y = 3;
static final int z = 5;
public static void main(String[] args) {
x = 1;
// works fine
SF1 classInstance = new SF1();
classInstance.y = 4;
// will give an error: "The final field main.y cannot be assigned"
z = 6;
// will give an error: "The final field main.z cannot be assigned"
reassignIntValue();
// x now equals 25, even if called from the main method
System.out.println(x);
}
public static void reassignIntValue() {
x = 25;
}
}
You have to declare your variable in class scope so you can able to access it outside of your method.
class ABC{
int a;
public void method(){
a = 10; // initialize your variable or do any operation you want.
}
public static void main(String args[]){
ABC abc = new ABC();
System.out.println(abc.a) // it will print a result
}
}
Say I wanted to make a class to hold a set of integers that would be accessed from multiple other classes and instances. I don't want them reverting to the value they had when the code was compiled. Does that mean they have to be static, in order to keep them from going back their original value? For example
The original stats holding class here:
public class Stats() {
public static int numOne = 0;
public static int numTwo = 5;
public static int numThree = 3
//etc...
}
It is called on in two places. Here:
public class exampleClass() {
private Stats stats = new Stats();
stats.numOne += 5;
//More variable changes.
}
Also here:
public class exampleClassTwo() {
private Stats stats = new Stats();
stats.numOne -= 3;
//More variable changes.
}
Will these calls reset the variables to their original class value if the variables are not static? If so, does that mean they should always be static?
No, the variables will maintain state without the static modifier
No. You would use static key word for using those values without initializating them.
public class Stats() {
public static int numOne = 0;
public static int numTwo = 5;
public static int numThree = 3
//etc...
}
public class exampleClass() {
int a = 0;
a += Stats.numThree;
System.out.println(a);
}
>>> 3;
No need for static attributes in your case indeed, each class instance will contain a private copy of attributes initialized at instance creation time, and records all subsequent modifications until object is deleted (in java it means no longer referenced).
Main usage for static is either to store constants or global state (e.g. a singleton instance).
Doing,
private Stats stats = new Stats();
stats.numOne += 5;
Kind of defeats the purpose of having numOne as static.
The static field numOne should be accessed in a static way i.e as follows: Stats.numOne
static variables are Class variables and are used when we want to maintain a value across instances of the class. So modifying the value of numOne across various functions will keep on changing the value of class variable numOne. Run the following code to see the effect of having a class variable in a class:
public class StaticVarDemo {
public static int staticCount =0 ;
public StaticVarDemo(){
staticCount++;
}
public static void main(String[] args) {
new StaticVarDemo();
StaticVarDemo.staticCount +=5;
System.out.println("staticCount : " + StaticVarDemo.staticCount);
new StaticVarDemo();
new StaticVarDemo();
System.out.println("staticCount : "+staticCount);
}
}
It will give the output:
staticCount : 6
staticCount : 8
Yes, when you instantiate an object, variables will be initialized to the class values when they are not static.
When a variable has the static keyword, that variable value persists over all instances: the two places you called it each create an object, both objects have the same values for their static variables (even if they are changed).
Variables without the static keyword are unique to the instance: changing it on one object doesn't affect its value on the other.
See here for more info:
What does the 'static' keyword do in a class?
It seems after some research a singleton did the job. Creating one singular instance but calling on it more then once.
See Here:
http://www.tutorialspoint.com/java/java_using_singleton.htm