Can i declare a static variable inside static member function in Java? - java

private static int Fibonoci(int n) {
static int first=0;
static int second=1;
static int sum;
if(n>0)
i am getting a error "Illegal Modifier" and if i remove static keyword there is no error and i need those variables to be static

You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.
static int first=0;
static int second=1;
static int sum;
private static int Fibonoci(int n) {
//do somthing
}
You are trying to write code for fibonacci series and for that you don't need static variables for that just here is some links who describes the sol for that
http://crunchify.com/write-java-program-to-print-fibonacci-series-upto-n-number/
http://electrofriends.com/source-codes/software-programs/java/basic-programs/java-program-find-fibonacci-series-number/

statics at function scope are disallowed in Java.

The Root cause: Static Variables are allocated memory at class loading time because they are part of the class and not its object.
Now, if static variable is inside a method, then that variable comes under the method's scope and JVM will be unable to allocate memory to it.

You can't declare a static variable inside a method, static means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects.
This means that static keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.
I don't know what you are trying to achieve, but if you really want these variables to be static then you can declare them as static fields in your class.

Local variables cannot be declared static. In other words Static doesn't apply to local variables.
And I didn't see any use of declaring them static there.
Follow JLs on static fields
A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

You have to define static variables as members in class. Variables those are defined within method are local variables and their lifecycles ends at the end of the method. local variables are call specific, member variables are object specific and static variables are class specific variables.

You need to declare the static variables outside of the function:
static int first=0;
static int second=1;
static int sum;
private static int Fibonoci(int n) {
if(n>0)

You can not declare varibale as static inside a method. In otherwords we can say that,
Local variables cannot be declared static.

This varibles called Local Variables, they are inside method scop or constructor, they can't be instance or class variables.
private static int COUNT;// Class Variable
private static int Fibonoci(int n) {
int a =3 ; // local variable
}
I need those variables to be static, okey , Why do you need this? because static variables used for special purpuse, however, you can create static fields like I did above code.

Related

Java-Cannot assign a value to final variable

class SomeClass{
final static int temp;
//temp=30;
SomeClass(int a){
System.out.println("here");
temp=a;
}
}
public class HelloWorld{
public static void main(String args[]){
SomeClass t1 = new SomeClass(10);
SomeClass t2 = new SomeClass(20);
System.out.println("t1:"+t1.temp);
System.out.println("t2:"+t2.temp);
}
}
When I create object t2 of SomeClass I can't assign value 20 to it. What could be the reason here? I cannot understand the final static int type.
You have to understand the two modifiers of the temp variable:
static means makes this a class variable so when you make the assignment in the object constructor, this is not a member of the object, but of the class. On the creation of t2 you make a second assignment to the one and only class variable (not a member variable of the object).
final means that the variable can be assigned a value only once, and therefore the assignment in the construction of t2 fails.
Do you intend for temp to be a member field of the object? Then remove static.
If you intend for temp to be a class variable that is reassigned? Then remove final.
static means belonging at class level. And, final means you only can instantiate it once. So, when you use final static, you are instantiating it once when you create t1. Then, that cannot be reinitialized. See this article.
If you want to have a variable that cannot be changed at object level, remove static.
when you define a variable final static, it means that you define it as a CONSTANT. Only one copy of variable exists which can’t be reinitialize.

static variable inside static method in java

While declaring a variable as static inside static method is giving error(compile time error).
My code is here:-
public class MainStatic {
public static void main(String[] args) {
System.out.println("Value of static variable is"+print(10));
}
public static void print(int number ) {
static int x = number;
++x;
System.out.println(x);
}
}
I am getting compile time error as :-
"Illegal modifier for parameter x; only final is permitted".
As a static method doesn't depend on instance of class then why i am not able to declare a static variable inside static method ?
But it is accessible if i declare the variable inside class out of the method ?
Local variables exist only at the time of invocation. Static doesn't (and can't) affect them.
A static variable belongs to the class and can be modified by anyone allowed according to the variable's access modifier. A local method variable only exists within the method (and during the execution of it) and can't be accessed by anyone outside of this method. It simply doesn't make sense.

Assign a static variable before declaring

I'm learning Java and write the simple code below:
public class Test {
private int a = b;
private final static int b = 10;
public int getA() {
return a;
}
}
public class Hello {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getA());
}
}
The result: 10. Well done! It run successfully and have no error.
Can anyone please explain why I can assign a static variable before declaring it?
The assignment
private int a = b;
takes place when you create a new instance of Test (just before the constructor is called).
The declaration and initialization of the static variable b, takes place before the instance is created, when the class is loaded.
The order of the statements doesn't matter, since static variables are always initialized first.
Javavariables are initialised this order:
Static variables of the superclasses if any
static variables of the current class.
Static variables, and static blocks in the order that they are
declared
Instance variables of the superclasses
All instance variables of the current class.
Instance variables, and instance level initialisation blocks, in
declaration order
Therefore "b" is intialized before the "a".
Hope this helps.
Static variables are bound to a class - which of course always exists before instances of the class. Thus, you can freely assign it to instance fields.
The order of declaring variables doesn't really matter in your code as in reality the static variable is going to be initialized before non-static ones.
The code you wrote works well because
private final static int b = 10;
is a class variable (static field). Those type of variables are initialised for first.
Then is executed the line
private int a = b;
which initialise the instance variable (field) a.
In short, it doesn't matter the order in which those variables are declared in your code. Class variables are always declared before instance variables.

Interface Variables

public interface A
{
public final int a = 0;
}
Many books say that all variables (constants) in an interface are implicitly public static final yet when I type the above statement explicitly but do not include the keyword static it compiles with no errors and can be referenced by the static way, A.a which indicates that it is still static.
Is it static or not, as to me it has to be since you cannot instantiate an interface, as if you had this "instance" variable then you could therefore never access the data member "a" as it is a non-static field.
Many books say that all variables (constants) in an interface are implicitly public static final
Yes, and what you're observing is exactly consistent with that. The key word is implicitly: it is a static variable whether or not you write the word static.

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.

Categories

Resources