How are field variables initialized in Java? - java

I tried to run this program but this gives a runtime error(StackOverflowError). If in class Static I make reference object ob, static, then no error occurs. Can anyone please explain me why is this happening and please explain me how are field variables(whether static or non static and whether reference or non reference variables) initialized?
public class Static {
public Static ob = new Static();
private int a;
public void win(Static obj) {
//System.out.printf("ob.a = %d\n", ob.a);
obj.a = 15;
System.out.printf("ob.a = %d", ob.a);
}
}
public class StaticTest {
public static void main(String args[])
{
Static obj=new Static();
//Static obj1=new Static();
// obj.win(obj1.ob);
}
}

Each time you instantiate an object of Static class (very confusing name BTW) you create an object of Static and instantiate it, which create another object of Static and instantiate it and so on... (so you get a StackOverflow error):
public Static ob = new Static();

Your code creates an instance of Static class.
When the instance is create their attributes are initialized. What your code does is to initialize the 'ob' attribute with pointing to a new Static instance.
Then the new instance of Static class is created, and ... you have an "infinite initialization loop".
If you attach 'static' keyworkd to an attribute you are creating a "class attribute", that is, an attributed shared among all instances of that class.
This means when you execute code and the first instance of Static is goind to be created JAva initialize the ob attribute. Subsequent instances of Static doesn't initialize it because it is shared among all.
See this sample: http://www.roseindia.net/java/beginners/staticvariable.shtml

static fields are initialized once for all instances of the class. This is why changing the type to static stops it from infinite recursion.
When the field is not static you create an infinite recursion which leads to a stack overflow; when you instantiate the object, it instantiates another, which instantiates another, and so on.

Static is at the class level and hence it is initialized when the class is loaded in the memory for the first time. Also static blocks are init in order of there declaration.
As against, the class variables (non static) are per object and are init when the object of that class is created, not in any specific order, I believe.
In your case, if you don't make ob static, it will try to init the Static class object and when try to inti the ob, it again go and create another Static (as it calls new Static()) and this goes on for ever until you run out of stack (StackoverFlow).
if you make ob static, this is init only once (when Static class is loaded in memory) and you are good to go.

If you create an instance level of a field, you are causing never-ending recursion, which ultimately ends up to StackOverFlow memory error.
If on the other hand you define your field as static you are avoiding the recursion, since the static field variables belong to the Class, not to the object instance. Classes in the JVM are only created once as opposed to Object instances, which can be numerous.

Related

Priority queue keeps changing pre entered values to the latest entered value any advice why this is happening [duplicate]

To be specific, I was trying this code:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
Cannot access non-static field in static method main
So I changed the declaration of clock to this:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
static members belong to the class instead of a specific instance.
It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.
Since static methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to. static members can only refer to static members. Instance members can, of course access static members.
Side note: Of course, static members can access instance members through an object reference.
Example:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;
// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class.
So if you were to do a "new Hello" anywhere in your code:
A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but
B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created.
Unless you needed "clock" somewhere outside of main, this would work just as well:
package hello;
public class Hello
{
public static void main(String args[])
{
Clock clock=new Clock();
clock.sayTime();
}
}
The static keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...) without any instance of the Math class, and indeed you can't create an instance of the Math class.
For more information, see the relevant bit of Oracle's Java Tutorial.
Sidenote
Java unfortunately allows you to access static members as if they were instance members, e.g.
// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);
That makes it look as if sleep is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:
// Clearer
Thread.sleep(5000);
The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.
So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances.
Static methods can be used without instantiating an object.
Basic usage of static members...
public class Hello
{
// value / method
public static String staticValue;
public String nonStaticValue;
}
class A
{
Hello hello = new Hello();
hello.staticValue = "abc";
hello.nonStaticValue = "xyz";
}
class B
{
Hello hello2 = new Hello(); // here staticValue = "abc"
hello2.staticValue; // will have value of "abc"
hello2.nonStaticValue; // will have value of null
}
That's how you can have values shared in all class members without sending class instance Hello to other class. And whit static you don't need to create class instance.
Hello hello = new Hello();
hello.staticValue = "abc";
You can just call static values or methods by class name:
Hello.staticValue = "abc";
Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:
Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class
directly, instead of:
Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable
From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.
Static in Java:
Static is a Non Access Modifier.
The static keyword belongs to the class than instance of the class.
can be used to attach a Variable or Method to a Class.
Static keyword CAN be used with:
Method
Variable
Class nested within another Class
Initialization Block
CAN'T be used with:
Class (Not Nested)
Constructor
Interfaces
Method Local Inner Class(Difference then nested class)
Inner Class methods
Instance Variables
Local Variables
Example:
Imagine the following example which has an instance variable named count which in incremented in the constructor:
package pkg;
class StaticExample {
int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 1 1
Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
Now if we change the instance variable count to a static one then the program will produce different output:
package pkg;
class StaticExample {
static int count = 0;// will get memory when instance is created
StaticExample() {
count++;
System.out.println(count);
}
public static void main(String args[]) {
StaticExample c1 = new StaticExample();
StaticExample c2 = new StaticExample();
StaticExample c3 = new StaticExample();
}
}
Output:
1 2 3
In this case static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
Static with Final:
The global variable which is declared as final and static remains unchanged for the whole execution. Because, Static members are stored in the class memory and they are loaded only once in the whole execution. They are common to all objects of the class. If you declare static variables as final, any of the objects can’t change their value as it is final. Therefore, variables declared as final and static are sometimes referred to as Constants. All fields of interfaces are referred as constants, because they are final and static by default.
Picture Resource : Final Static
To add to existing answers, let me try with a picture:
An interest rate of 2% is applied to ALL savings accounts. Hence it is static.
A balance should be individual, so it is not static.
This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.
A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using static the field becomes a class variable, thus there is one and only one clock. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.
In Java, the static keyword can be simply regarded as indicating the following:
"without regard or relationship to any particular instance"
If you think of static in this way, it becomes easier to understand its use in the various contexts in which it is encountered:
A static field is a field that belongs to the class rather than to any particular instance
A static method is a method that has no notion of this; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to it
A static member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it)
The keyword static is used to denote a field or a method as belonging to the class itself and not to any particular instance. Using your code, if the object Clock is static, all of the instances of the Hello class will share this Clock data member (field) in common. If you make it non-static, each individual instance of Hello will have a unique Clock.
You added a main method to your class Hello so that you could run the code. The problem with that is that the main method is static and as such, it cannot refer to non-static fields or methods inside of it. You can resolve this in two ways:
Make all fields and methods of the Hello class static so that they could be referred to inside the main method. This is not a good thing to do (or the wrong reason to make a field and/or a method static)
Create an instance of your Hello class inside the main method and access all its fields and methods the way they were intended to be accessed and used in the first place.
For you, this means the following change to your code:
package hello;
public class Hello {
private Clock clock = new Clock();
public Clock getClock() {
return clock;
}
public static void main(String args[]) {
Hello hello = new Hello();
hello.getClock().sayTime();
}
}
static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page
I have developed a liking for static methods (only, if possible) in "helper" classes.
The calling class need not create another member (instance) variable of the helper class. You just call the methods of the helper class. Also the helper class is improved because you no longer need a constructor, and you need no member (instance) variables.
There are probably other advantages.
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
Hello hello = new Hello();
hello.clock.sayTime();
//Here is an example
public class StaticClass
{
static int version;
public void printVersion() {
System.out.println(version);
}
}
public class MainClass
{
public static void main(String args[]) {
StaticClass staticVar1 = new StaticClass();
staticVar1.version = 10;
staticVar1.printVersion() // Output 10
StaticClass staticVar2 = new StaticClass();
staticVar2.printVersion() // Output 10
staticVar2.version = 20;
staticVar2.printVersion() // Output 20
staticVar1.printVersion() // Output 20
}
}
Can also think of static members not having a "this" pointer. They are shared among all instances.
Understanding Static concepts
public class StaticPractise1 {
public static void main(String[] args) {
StaticPractise2 staticPractise2 = new StaticPractise2();
staticPractise2.printUddhav(); //true
StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */
StaticPractise2.printUddhavsStatic1(); //true
staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static things and it organizes in its own heap. So, class static methods, object can't reference */
}
}
Second Class
public class StaticPractise2 {
public static void printUddhavsStatic1() {
System.out.println("Uddhav");
}
public void printUddhav() {
System.out.println("Uddhav");
}
}
main() is a static method which has two fundamental restrictions:
The static method cannot use a non-static data member or directly call non-static method.
this() and super() cannot be used in static context.
class A {
int a = 40; //non static
public static void main(String args[]) {
System.out.println(a);
}
}
Output: Compile Time Error
A question was asked here about the choice of the word 'static' for this concept. It was dup'd to this question, but I don't think the etymology has been clearly addressed. So...
It's due to keyword reuse, starting with C.
Consider data declarations in C (inside a function body):
void f() {
int foo = 1;
static int bar = 2;
:
}
The variable foo is created on the stack when the function is entered (and destroyed when the function terminates). By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.
Java, and similar languages, have the same concept for data. Data can either be allocated per instance of the class (per object) or once for the entire class. Since Java aims to have familiar syntax for C/C++ programmers, the 'static' keyword is appropriate here.
class C {
int foo = 1;
static int bar = 2;
:
}
Lastly, we come to methods.
class C {
int foo() { ... }
static int bar() { ... }
:
}
There is, conceptually speaking, an instance of foo() for every instance of class C. There is only one instance of bar() for the entire class C. This is parallel to the case we discussed for data, and therefore using 'static' is again a sensible choice, especially if you don't want to add more reserved keywords to your language.
Static Variables Can only be accessed only in static methods, so when we declare the static variables those getter and setter methods will be static methods
static methods is a class level we can access using class name
The following is example for Static Variables Getters And Setters:
public class Static
{
private static String owner;
private static int rent;
private String car;
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public static int getRent() {
return rent;
}
public static void setRent(int rent) {
Static.rent = rent;
}
public static String getOwner() {
return owner;
}
public static void setOwner(String owner) {
Static.owner = owner;
}
}
A member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. When a member is declared static, then it essentially means that the member is shared by all the instances of a class without making copies of per instance.
Thus static is a non-class modifier used in Java and can be applied to the following members:
Variables
Methods
Blocks
Classes (more specifically, nested classes)
When a member is declared static, then it can be accessed without using an object. This means that before a class is instantiated, the static member is active and accessible. Unlike other non-static class members that cease to exist when the object of the class goes out of scope, the static member is still obviously active.
Static Variable in Java
A member variable of a class that is declared as static is called the Static Variable. It is also called as the “Class variable”. Once the variable is declared as static, memory is allocated only once and not every time when a class is instantiated. Hence you can access the static variable without a reference to an object.
The following Java program depicts the usage of Static variables:
class Main
{
// static variables a and b
static int a = 10;
static int b;
static void printStatic()
{
a = a /2;
b = a;
System.out.println("printStatic::Value of a : "+a + " Value of b :
"+b);
}
public static void main(String[] args)
{
printStatic();
b = a*5;
a++;
System.out.println("main::Value of a : "+a + " Value of b : "+b);
}
}
output::
printStatic::Value of a : Value of b : 5
main::Value of a : 6 Value of b : 25
In the above program, we have two static variables i.e. a and b. We modify these variables in a function “printStatic” as well as in “main”. Note that the values of these static variables are preserved across the functions even when the scope of the function ends. The output shows the values of variables in two functions.
Static Method
A method in Java is static when it is preceded by the keyword “static”.
Some points that you need to remember about the static method include:
A static method belongs to the class as against other non-static
methods that are invoked using the instance of a class.
To invoke a static method, you don’t need a class object.
The static data members of the class are accessible to the static
method. The static method can even change the values of the static
data member.
A static method cannot have a reference to ‘this’ or ‘super’ members.
Even if a static method tries to refer them, it will be a compiler
error.
Just like static data, the static method can also call other static
methods. A static method cannot refer to non-static data members or
variables and cannot call non-static methods too.
The following program shows the implementation of the static method in Java:
class Main
{
// static method
static void static_method()
{
System.out.println("Static method in Java...called without any
object");
}
public static void main(String[] args)
{
static_method();
}
}
output:
Static method in Java...called without any object
Static Block In Java
Just as you have function blocks in programming languages like C++, C#, etc. in Java also, there is a special block called “static” block that usually includes a block of code related to static data.
This static block is executed at the moment when the first object of the class is created (precisely at the time of classloading) or when the static member inside the block is used.
The following program shows the usage of a static block.
class Main
{
static int sum = 0;
static int val1 = 5;
static int val2;
// static block
static {
sum = val1 + val2;
System.out.println("In static block, val1: " + val1 + " val2: "+
val2 + " sum:" + sum);
val2 = val1 * 3;
sum = val1 + val2;
}
public static void main(String[] args)
{
System.out.println("In main function, val1: " + val1 + " val2: "+ val2 + " sum:" + sum);
}
}
output:
In static block, val1: 5 val2: 0 sum:5
In main function, val1: val2: 15 sum:20
Static Class
In Java, you have static blocks, static methods, and even static variables. Hence it’s obvious that you can also have static classes. In Java, it is possible to have a class inside another class and this is called a Nested class. The class that encloses the nested class is called the Outer class.
In Java, although you can declare a nested class as Static it is not possible to have the outer class as Static.
Let’s now explore the static nested classes in Java.
Static Nested Class
As already mentioned, you can have a nested class in Java declared as static. The static nested class differs from the non-static nested class(inner class) in certain aspects as listed below.
Unlike the non-static nested class, the nested static class doesn’t need an outer class reference.
A static nested class can access only static members of the outer class as against the non-static classes that can access static as well as non-static members of the outer class.
An example of a static nested class is given below.
class Main{
private static String str = "SoftwareTestingHelp";
//Static nested class
static class NestedClass{
//non-static method
public void display() {
System.out.println("Static string in OuterClass: " + str);
}
}
public static void main(String args[])
{
Main.NestedClassobj = new Main.NestedClass();
obj.display();
}
}
output
Static string in OuterClass: SoftwareTestingHelp
I think this is how static keyword works in java.

if we create an instance in static method will that instance becomes static implicitly?

class A
{
int i = 10;
public static void main(String[] args)
{
A a= new A();
a.i=20;
}
}
is running fine but when try to write following code
class A
{
A a= new A();
int i = 10;
public static void main(String[] args)
{
a.i=20;
}
}
it is giving compile time error. It means that whatever(assume reference variable) we write inside the static method is treated as a static variable implicitly.
You are mixing up class scope, method scope, and instance scope.
First remember that when you have something that is static, it is available to all instances of that class. When something isn't static, it is only available to a specific instance of a class, and is not shared. Because of that, static methods cannot act on instance variables (or methods).
In the first example, you create an A scoped to the main() method. The fact that main() is static has nothing to do with it, this is method-level scoping. When you call .i on that instance of A, you are calling it on the instance local to your scope.
In the second example, you are saying that whenever an A is instantiated, it will have another instance of A within it (which leads to other problems, see below). This is at the object instance scope. When you try to call it from your static-scoped main() method, the compiler has no idea which specific instance of A you want to use. Each one has its own version of i.
And finally, by creating an instance of A within every other instance of A (A a = new A();) your code will never run, you'll get a StackOverflowException.
Edit to answer question:
OK, when you do something like this:
public class Person {
String name = null;
}
You are saying, that for every Person we create (via new), they have a name that is for them, and them only. They don't share it with anybody.
So when you do something like this:
public class A {
A a = new A();
}
You are saying that for every A we create (via new) it has another A that is for that instance and that instance only. See where this is going? You end up infiniately creating A objects until java runs out of room on the stack for them. The first A is created, and tries to create its internal A, which tries to create its internal A and so on and so on.

What is the purpose of static keyword in this simple example? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.

Difference between Static and final?

I'm always confused between static and final keywords in java.
How are they different ?
The static keyword can be used in 4 scenarios
static variables
static methods
static blocks of code
static nested class
Let's look at static variables and static methods first.
Static variable
It is a variable which belongs to the class and not to object (instance).
Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.variable
Static method
It is a method which belongs to the class and not to the object (instance).
A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
A static method can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.methodName()
A static method cannot refer to this or super keywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is static since it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.
A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading
So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.
class C {
public static int n = 42;
}
Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.
final on the other hand indicates that a particular variable cannot change after it is initialized.
class C {
public final int n = 42;
}
Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.
Also, classes can be declared final which indicates that they cannot be extended:
final class C {}
class B extends C {} // error!
Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:
class C {
public final void foo() {}
}
class B extends C {
public void foo() {} // error!
}
static means there is only one copy of the variable in memory shared by all instances of the class.
The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.
final -
1)When we apply "final" keyword to a variable,the value of that variable remains constant.
(or)
Once we declare a variable as final.the value of that variable cannot be changed.
2)It is useful when a variable value does not change during the life time of a program
static -
1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class
Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
Declaring
static final String color = "Black";
will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.
public class Speaker {
static String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //will provide output as "Black"
Speaker.color = "white";
System.out.println(Speaker.color); //will provide output as "White"
}}
Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.
public class Speaker {
static final String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //should provide output as "Black"
Speaker.color = "white"; //Error because the value of color is fixed.
System.out.println(Speaker.color); //Code won't execute.
}}
You may copy/paste this code directly into your emulator and try.
Easy Difference,
Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.
Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again.
you can create object of class but that object will not have different x in them.
if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.
Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.
"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so
Class A has x =5, i can call and change it by A.x=6; "
Static and final have some big differences:
Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:
public class Test{
public final int first = 10;
public static int second = 20;
public Test(){
second = second + 1
first = first + 1;
}
}
The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.
Static is something that any object in a class can call, that inherently belongs to an object type.
A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.
Some example code:
class someClass
{
public static int count=0;
public final String mName;
someClass(String name)
{
mname=name;
count=count+1;
}
public static void main(String args[])
{
someClass obj1=new someClass("obj1");
System.out.println("count="+count+" name="+obj1.mName);
someClass obj2=new someClass("obj2");
System.out.println("count="+count+" name="+obj2.mName);
}
}
Wikipedia contains the complete list of java keywords.
I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.
static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.
final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.
Static variable values can get changed although one copy of the variable traverse through the application, whereas Final Variable values can be initialized once and cannot be changed throughout the application.

Java Static Method Calling

is Calling a static Java method ( a factory class method ) creates an object of that Class ?
I mean a static method returns a value let's say an Array's size ( array is variable of class )
I've checked the code but couldn't see that the Object of that class never instantiated before calling the static method. ?
public static boolean isFiveInstance() {
return _instances.size() == 5;
}
and _instances is class variable
private static ArrayList<LocalMediaPlayer> _instances;
and is being created and filled in the constructer.
No it does not. That is the point behind creating static methods. Static methods use no instance variables of any object of the class they are defined in either, so everything you refer to inside your static method must be static also.
That is why you call a static method like Class.StaticMethod() instead of:
new Class().StaticMethod();
the new will instantiate that class, thus creating a new instance of that object.
No, static invocations do not instantiated objects (because they do not require one).
The first time you refer to a class, including static method invocation, the class is loaded. by the classloader.
That's where the static initializer comes into play:
static {
// do something
}
this block is called whenever the class is initialized (once per classloader)
No, calling a static method does not create an instance of the class. That's where static methods differ from instance methods. They don't need an instance of the class they belong to to be instantiated to be run.

Categories

Resources