initializing a final field - java

This Q rather for verification:
A static final field can be initialized when it's declared:
public static final int i=87;
or in the static block:
public static final int i;
//..........
static {
...
i=87;
...
}
Is there anywhere, other than the static block, a static final field
public static final int i;
can be initialized?
Thanks in advance.
Note: saw Initialize a static final field in the constructor. it's not specific that the static block is the only place to initialized it outside the declaration.
//==============
ADD:
extending #noone's fine answer, in response to #Saposhiente's below:
mixing in some non-static context:
public class FinalTest {
private static final int INT = new FinalTest().test();
private int test() {
return 5;
}
}

The Java Language Specification states
It is a compile-time error if a blank final (§4.12.4) class variable
is not definitely assigned (§16.8) by a static initializer (§8.7) of
the class in which it is declared.
So the answer to
Is there anywhere, other than the static block, a static final field
can be initialized?
No, there isn't.

It could be "initialized" in any random static method, but only indirectly by using the static block, or the variable initialization.
public class FinalTest {
private static final int INT = test();
private static int test() {
return 5;
}
}
Or like this:
public class FinalTest {
private static final int INT;
static {
INT = test();
}
private static int test() {
return 5;
}
}
Technically, it is not really an initialization in test(), but it acts like one.

No. A field that is static belongs to the class, and a field that is final must be assigned by the time it becomes visible, so a static final field must be initialized either with the declaration or in a static initializer (which both get compiled to the same thing) so that it has a value when the class is finished loading.

It can only be initialized in a set of static code that is always run exactly once. This is usually in its declaration or in a static block, but you could also do something weird like
static final int i;
static int j = i = 1;
which is technically neither of those. Either way, you can't initialize it in any sort of function or constructor because that function might be run more than once; you have to use a static declaration or block of code to run the function and use the return value to initialize it.

Related

Is it possible to access a private static variable and method?

We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?
The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.
private static int a = 5;
public static int getA () {
return a;
}
You can then statically call this method and retrieve the private static field.
// ...
System.out.println(A.getA());
Usually private static fields are rarely used though.
One more thing I'd like to add is the general use of static here.
As you actually create an instance of the class A the static modifier is redundant.
You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package
means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

What is initializers for static fields in Java

I have got the following line from Oracle Java tutorial
You can find this here Execution under the heading "12.4. Initialization of Classes and Interfaces"
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.
It will be great if someone explain me How "initializers for static fields" is referring to "class variables".
A "class variable" is a variable that is declared as a static property of a class. By "initializers for static fields" they are referring to the initialization of these static variables, which happens when the class is loaded. Here's an example:
public class MyClass {
private static int num = 0; //This is a class variable being initialized when it is declared
}
Another way to initialize static fields is to use static blocks:
public class MyClass {
private static int num;
static {
num = 0; //This a class variable being initialized in a static block
}
}
These static blocks are run from top to bottom when the class is loaded.
In the end, the quote is trying to say that "class variable" is just another name for "static field."
A static member is a variable that belongs to the class as a whole, not a specific instance. It's initialized once, when the classloader loads the class.
E.g.:
public class MyClass {
// Note the static modifier here!
private static int someVariable = 7;
}
One common usecase for such variables is static final members of immutable types or primitives used to represent constants:
public class Human {
public static final String SPECIES = "Homo sapiens";
public static final int LEGAL_DRINKING_AGE = 21; // U.S centric code :-(
}

Why I can not assign the value in public location in java

public class Test {
int a=10;
a=20;
}
why I can not assign the value as above;
When you declare an instance variable (class member) like this:
public class Test {
int a=10;
}
it means that any instance of class Test will have its own copy of this variable and it will be instantiated to 10.
Java allows an assignment upon declaration of instance variables, but after the variable was already declared it can be assigned only in:
an initializer block
a constructor
a method
which is why the second line will fail to compile.
The value would need to be static or inside of a method to assign the value in this portion of a class. You won't be able to change the value of a in that way unless you declare a static block of code.
try:
public class Test {
private static int a = 20;
}
or
public class Test {
private int a = 10;
public static void Main(String[] args) {
a = 20;
}
or
public class Test {
static {
int a = 10;
a = 20;
}
Try this. It is called initialization block
public class Test {
int a=10;
{a=20;}
}
EDITED:
You can alter variables values only in methods. Java is objective language not procedural.

How to create a class which is not inheritable and static in java?

Can you please help me how to create a class which is not inheritable and should be static in behavior (Means we should not be able to create instance of it). I need this class to store constant values. Thanks.
public final class MyClass {
private MyClass() { }
}
The final keyword makes it not inheritable, and making the constructor(s) private will help stopping it from being instantiated.
you can use final keyword to class can not be inherited.
But I would recommend you to Use Enums. Enums can not be inherited and only one instance exists per constant value. Also you can do lot more with enums.
public enum DaysOfweek
{
SUNDAY,MONDAY.....
}
You can read more about Enums here Enum Types
Why not use an interface which has a couple of static and final variables?
For the first case, you can use final class as they can't be inherited..
For your second case, you can use interface, they are very well used to store Constants.
But you cannot have both of them together (As having an interface which cannot be implemented does not make sense)..
So, the best is you can mix the property of both in one class.. You can have a final class with public static final variables, as this is what makes a variable constant in interface, will serve the purpose of constants..
public final class A {
public static final int YOUR_CONST = 5;
}
If you don't want to make instance of this class, you can have a private 0-arg constructor in it..
public final class A {
public static final int YOUR_CONST = 5;
private A() {}
}
Declare it as final which will not allow other classes to extend it, and make its constructors private so no one else (except your own class) will be able to instantiate it:
public final class MyClass {
private MyClass() {
// Private so noone else can instantiate this
}
}
Below is an example of the class to contain a constant value:
public final class Trial // it is the FINAL
{
private static final int CONSTANT_VALUE = 666;
private Trial() // it is PRIVATE instead of PUBLIC
{
}
public static int getConstantValue()
{
return CONSTANT_VALUE;
}
}
And below is an example of how to test the above class:
public class Bully //extends Trial ////"extends" WILL NOT COMPILE
{
public static void main(String[] args)
{
//Trial trial = new Trial(); ////"new Trial()" WILL NOT COMPILE
// The only thing can be done is getting a constant value from "Trial"
int acquiredValue = Trial.getConstantValue();
System.out.println(acquiredValue);
}
}
Hope that helps :))
public final class MyClass {
public static string MY_STRING;
public static int MY_INT;
private MyClass() {}
}
final : Make a class final that means this class can not be inherite further more.
static : If all methods are static the you do not need to create instance of this class. and should be static in behavior.
Singleton pattern : If your all methods are not static and you do not want to create more than one instance then you can make constructor private and keep one variable of class object in the class. And create once if it is null, and if not null then return same instance always.
Thanks

static() method (without any decleration)

I have the following class:
public abstract class A()
{
public static final SomeString = null;
static()
{
SomeString = "aaa";
}
}
When is this static method invoked and how?
What is the purpose in creating such a static method (without name / return type)?
That is not a method, it's a static initialization block, and your syntax is wrong
public abstract class A()
{
public static String SomeString = null;
static
{
SomeString = "aaa";
}
}
The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:
public class InitializationWithConstants{
public static int staticIntField = 100;
private boolean instanceBoolField = true;
}
This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic - like initializing only selected elements of a complex array using some logic in a for loop.
Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.
It's a normal block of code enclosed within a pair of braces and preceded by a 'static' keyword. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.
public class InitializationWithStaticInitBlock{
public static int staticIntField;
private boolean instanceBoolField = true;
static{
//compute the value of an int variable 'x'
staticIntField = x;
}
}
Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.
Your syntax is incorrect; it should be:
public abstract class A()
{
public static final String SomeString;
static
{
SomeString = "aaa";
}
}
The static block allows static variables to be initialised when the class is loaded when that initialisation is more complication than simply = something;.
Reference
Syntax aside, you're looking at a static initializer block. They're mentioned here.
Essentially, a static initializer block is a piece of code that executes when a class is loaded, and can be used to initialize static fields in the class.
Example:
public abstract class A
{
public static final String SomeString;
static
{
System.out.println("static{}");
SomeString = "aaa";
}
public static void main(String[]args)
{
System.out.println("main");
}
}
Output:
static{}
main
yeas it's not a method. it is static block and i'st evaluated once when the owner class is loaded.
u can use it for initialize static variable dynamically ...

Categories

Resources