Let's say I defined a constant int in file A.java:
public final static int CONSTAN_VALUE_IN_A = 0;
when I use this value in another file B.java:
int fooBValue = A.CONSTAN_VALUE_IN_A;
after I compiled my project, in B.class,I have:
fooBValue = 0
I want to know if I can get where the value "0" come from (A.java) when I only have B.class file without the source code.
I heard that when compile with java8, I can know that B.java use some constant value in A.java by reading the constant pool in B.class.
But I'm not really sure about that or how to get the actual class the constant come from by reading the constant pool.
JLS 4.12.4 defines a "constant variable" as follows:
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).
JLS 13.1 describes how these end up in a class file:
3. A reference to a field that is a constant variable (§4.12.4) must be resolved at compile time to the value V denoted by the constant variable's initializer.
If such a field is static, then no reference to the field should be present in the code in a binary file, including the class or interface which declared the field. Such a field must always appear to have been initialized (§12.4.2); the default initial value for the field (if different than V) must never be observed.
The declaration in class A
public final static int CONSTAN_VALUE_IN_A = 0;
meets the definition of a constant variable, so when it's used in class B,
int fooBValue = A.CONSTAN_VALUE_IN_A;
the value is resolved at compile time. No reference to A.CONSTAN_VALUE_IN_A appears in class B, and instead the resolved value of 0 is compiled into class B.
So, no, there's no way to tell where that value in B came from unless you can find the source code.
If you don't like this behavior, you can avoid it by changing things so that the conditions of JLS 4.12.4 aren't met, such as by making it not final, or by changing the type so that it's neither a primitive nor a String. However, the easiest way of making it not a constant variable is to move the initialization into a static initializer:
public final static int CONSTAN_VALUE_IN_A;
static {
CONSTAN_VALUE_IN_A = 0;
}
By the way, this is not new in Java 8; this behavior has been this way for a very long time.
Almost certainly not.
Many static final values are even replaced at compile time by the actual value associated with the constant.
static final int X = 0;
static final int Q = 9;
private void test(String[] args) {
int x = X;
int y = Q;
}
would probably be transformed in the very early stages of compilation into:
private void test(String[] args) {
int x = 0;
int y = 9;
}
so the chances of discovering where the value actually came from are very small.
Related
If I have a class like such:
public class First {
int x = 1;
}
and a second class:
class Main {
public static void main(string args[]) {
First someObject = new First();
someObject.x = 2;
}
}
is only someObject.x equal to 2 or would any object of class First being created afterwards be initialized with it's x attribute being equal to 2. If not, how would one change the default value of x for any object being made of class First?
First of all, you need to read about what "pass by reference" really means. (For example, here.) Passing semantics refer to what happens to arguments in a procedure/method/subroutine/function call. In your example, there is no "passing" going on at all when you are assigning to the x field.
So your
In Java are object attributes passed by reference to other classes
is a meaningless and/or irrelevant question. (But the plain answer is that Java does not support "pass by reference". Period.)
As for what I think you are trying to ask, lets start with some facts:
The Field class declares x as an instance field.
Each instance of First has its own "copy" of the x field.
The x field is part of one and only one instance. It is not shared with any other First instance.
This is irrespective of the declared type of x ... modulo that a field whose declared type is a reference type will contain a reference to an object rather than the object itself. (But int is not a reference type.)
The new First() expression creates a new instance of the First class that is distinct from all other (past, present or future) instances of First and returns its reference.
So, in this code:
First f1 = new First();
First f2 = new First();
f1.x = 2;
System.out.println(f2.x); // prints 1.
We have two instances of First that f1 and f2 refer to (point at) distinct First instances. If you change the x field of one instance does not change the x field of the other intance. They are different fields.
However, if you had declared x as static in First, then x is no longer a distinct field for each First instance. It is now a shared by all instances of First.
As an addendum, how would one change the default value of x in the First class such that any new instance made afterwards would have a difference value of x to start?
Firstly int x = 1; in First is not defining a "default" value in the sense that Java uses that term. It is actually an initialization. (A default value is what you see if you DON'T have an initialization.)
If you wanted to implement application specific default value that is common to all instances of First and that can be changed retrospectively, you need to implement it in Java code. Maybe something like this:
public class First {
static int defaultX = 1;
private int x;
private boolean xSet = false;
public int getX() {
return xSet ? x : defaultX;
}
public void setX(int x) {
this.x = x;
this.xSet = true;
}
}
Note that in order to implement the defaulting behavior we want, we have to hide the x field (make it private) and implement the desired behavior in the getter and setter methods.
This question already has answers here:
What is the difference between constant variables and final variables in java?
(4 answers)
Closed 2 years ago.
I'm a newbie learning Java currently being introduces do the switch/case construct. The book I'm reading uses the following example:
int eingabe = 256;
final byte einKleinesByte = 2;
final char einKleinerCharacter = 'c';
final short einKleinesShort = 500;
switch(eingabe) {
case einKleinesByte:
case einKleinerCharacter:
case einKleinesShort:
The explanation is that these 3 constant are defined with the help of the keyword final, which is essential, because variables cannot be used for the cases.
My question is, what is the difference between final byte einKleinesByte = 2; and byte EIN_KLEINES_BYTE = 2; as they are both defined as constants?
Thanks for the help!
The main difference between final variable and a constant (static and final) is that if you create a final variable without static keyword, though its value is un-modifiable, a separate copy of the variable is created each time you create a new object. Where a constant is un-modifiable and have only one copy through out the program.
They are not both defined as constant. You can easily change the value of the byte EIN_KLEINES_BYTE. You are using the snake uppercase standard which is usually used to define constant but in reallity, there is nothing that stops you from changing the value of this variable. Only the keyworld final would prevent that.
// would work fine
int MY_CONSTANT = 2;
MY_CONSTANT = 3
// Will throw an error
final int myConstant = 2;
myConstant = 3
// recommended
static final int MY_CONSTANT = 2
byte EIN_KLEINES_BYTE is not a constant, it can be overwritten.
final byte EIN_KLEINES_BYTE can't be, that is a constant.
a final variable can not be reassigned. For primitive types, or for unchangeable types, this means that they are constant in value.
For most objects, it doesn't. You can change the state (value) of those objects, but you can't change the object itself for another.
Just by putting a variable name in upper case, does not make it a constant.
EDIT: if you want a final variable to be the same for the entire application, you'll have to declare it as static, as well.
final simply means that the value, once assigned, can not be changed or reassigned
concerning constants, i would refer you to this question
I find the defs circular, the subjects are defined by their verbs but the verbs are undefined! So how do you define them?
The Circular Definitions
initialization: to initialize a variable. It can be done at the time of
declaration.
assignment: to assign value to a variable. It can be done anywhere, only once with the final-identifier.
declaration: to declare value to a variable.
[update, trying to understand the topic with lambda calc]
D(x type) = (λx.x is declared with type)
A(y D(x type)) = (λy.y is assigned to D(x type))
%Then after some beta reductions we get initialization.
D(x type) me human // "me" declared with type "human"
A(y (D(x type) me human)) asking // "asking" assigned to the last declaration
%if the last two statemets are valid, an initialization exists. Right?
assignment: throwing away the old value of a variable and replacing it with a new one
initialization: it's a special kind of assignment: the first. Before initialization objects have null value and primitive types have default values such as 0 or false. Can be done in conjunction with declaration.
declaration: a declaration states the type of a variable, along with its name. A variable can be declared only once. It is used by the compiler to help programmers avoid mistakes such as assigning string values to integer variables. Before reading or assigning a variable, that variable must have been declared.
String declaration;
String initialization = "initialization";
declaration = "initialization"; //late initialization - will initialize the variable.
// Without this, for example, in java, you will get a compile-time error if you try
// to use this variable.
declaration = "assignment"; // Normal assignment.
// Can be done any number of times for a non-final variable
Declaration is not to declare "value" to a variable; it's to declare the type of the variable.
Assignment is simply the storing of a value to a variable.
Initialization is the assignment of a value to a variable at the time of declaration.
These definitions also applies to fields.
int i; // simple declaration
i = 42 // simple assignment
int[] arr = { 1, 2, 3 };
// declaration with initialization, allows special shorthand syntax for arrays
arr = { 4, 5, 6 }; // doesn't compile, special initializer syntax invalid here
arr = new int[] { 4, 5, 6 }; // simple assignment, compiles fine
However, it should be mentioned that "initialization" also has a more relaxed definition of "the first assignment to a variable", regardless of where it happens.
int i; // local variable declaration
if (something) i = 42;
System.out.println(i);
// compile time error: The local variable i may not have been initialized
This, however, compiles:
int i; // the following also compiles if i were declared final
if (something) i = 42;
else i = 666;
System.out.println(i);
Here i can be "initialized" from two possible locations, by simple assignments. Because of that, if i was an array, you can't use the special array initializer shorthand syntax with this construct.
So basically "initialization" has two possible definitions, depending on context:
In its narrowest form, it's when an assignment is comboed with declaration.
It allows, among other things, special array shorthand initializer syntax
More generally, it's when an assignment is first made to a variable.
It allows, among other things, assignments to a final variable at multiple places.
The compiler would do its best to ensure that exactly one of those assignments can happen, thus "initializing" the final variable
There's also JVM-context class and instance initialization, OOP-context object initialization, etc.
Here is a short explanation with some examples.
Declaration:
Declaration is when you declare a variable with a name, and a variable can be declared only once.
Example: int x;, String myName;, Boolean myCondition;
Initialization:
Initialization is when we put a value in a variable, this happens while we declare a variable.
Example: int x = 7;, String myName = "Emi";, Boolean myCondition = false;
Assignment:
Assignment is when we already declared or initialized a variable, and we are changing the value. You can change value of the variable as many time you want or you need.
Example:
int x = 7;
x = 12; .......We just changed the value.
String myName = "Emi";
myName = "John" .......We just changed the value.
Boolean myCondition = false;
myCondition = true; .......We just changed the value.
Note: In memory will be saved the last value that we put.
declaration: whenever you define a new variable with its type
assignment: whenever you change the value of a variable by giving it a new value
initialization: an assignment that is done together with the declaration, or in any case the first assignment that is done with a variable, usually it's a constructor call for an object or a plain assignment for a variable
I come from a C/C++ background, but the ideas should be the same.
Declaration - When a variable is declared, it is telling the compiler to set aside a piece of memory and associate a name (and a variable type) with it. In C/C++ it could look like this:
int x;
The compiler sees this and sets aside an address location for x and knows what methods it should use to perform operations on x (different variable types will use different access operations). This way, when the compiler runs into the line
x = 3 + 5;
It knows to put the integer value 8 (not the floating point value 8) into the memory location also known as 'x'.
Assignment - This is when you stuff a value into the previously declared variable. Assignment is associated with the 'equals sign'. In the previous example, the variable 'x' was assigned the value 8.
Initialization - This is when a variable is preset with a value. There is no guarantee that a variable will every be set to some default value during variable declaration (unless you explicitly make it so). It can be argued that initialization is the first assignment of a variable, but this isn't entirely true, as I will explain shortly. A typical initialization is a blend of the variable declaration with an assignment as follows:
int x = 6;
The distinction between initialization and assignment becomes more important when dealing with constants, such as this...
const int c = 15;
When dealing with constants, you only get to assign their value at the time of declaration/initialization. Otherwise, they can't be touched. This is because constants are often located in program memory vs data memory, and their actual assignment is occurring at compile time vs run time.
Step 1: Declaration : int a;
Step 2: Initialization : a = 5;
Step 3: Assignment: a = b; (ex: int b = 10 ; now a becomes 10)
Declaration
When we first create a variable of any Data Type is call Declaration. Example:
int obj;
String str;
Initialization
When (Declaration is completed) or variable is created the assigned any value to this variable is call Initialization. Example
int obj = 10;
String str = "Azam Khan";
Assignment
Reassign value to that variable that is already initialized is call Assignment. Example
int obj = 15;
obj = 20; // it print **20** value.
String str = "simple"
str = "Azam Khan" // it's result or print **Azam Khan** value...
Simple program
class ABC{
public static void main(String args[]){
int obj; // this is **Declaration:**
int testValue= 12; // After the **Declaration**,
testValue is **Initialize**.
testValue = 25;
System.out.println(textValue);
}
}
the output result is 25.
it saves the value of 25.
I was wondering whether I should initialize class members in java with an initial value and then change that value to some other given value in the constructor, or should I avoid doing such a thing?
code example
public class Test {
private int value = 5;
public Test(int value) {
this.value = value;
}
}
If not specified,:
primitive bytes, shorts, ints, longs, floats and doubles are initialized to 0
booleans are initialized to false
Objects are initialized to null
If we are talking about class fields than all unset variables of
primitive types are set to
0 (numeric ones like int, long, double...)
\u0000 (char)
false (boolean).
object types like String, Integer, or AnyOtherClass are set to null
so actually it doesn't matter if you set it explicitly, because
private int x;
private Integer y;
is equivalent of
private int x = 0;
private Integer y = null;
Java give value class variables, I mean they are initialized by JVM and you can use them. But you must to search their default values to use them correctly.
On the other hand, JVM does not initialize the local variables which is created in methods. So if you create any variable on methods you have to assign them to a value before use them.
A not initialized int is always 0 on heap. It can't never be null. Mind: within a method it must be initialized, not only declared.
First, you cannot initialize an int value with null. The default value of an int is zero, but initializing it in both the field declaration and the constructor is pointless. Assuming the compiler does not omit the field initializer completely, it effectively compiles to this:
public class Test {
private int value;
public Test(int value) {
this.value = /* field initializer value */;
this.value = value;
}
}
Unless you want to initialize a field with a non-default value (non-zero, non-null), there is generally no reason to add an initializer. This is especially true if the initializer is redundant, as is the case above. The default value for a field is the "zeroed out" value of the field type, e.g., 0 for numeric types, false for a boolean, and null for objects. Note that there is an exception with respect to fields: final fields must have an initializer if they are not assigned exactly once in every constructor; final fields have no implicit default value.
Now, it may be necessary to initialize method variables to guarantee they have a value by the time they are read, as variables do not have a default/implied initializer as fields do. Whether an explicit initializer is necessary depends on the control flow of your method.
I find the defs circular, the subjects are defined by their verbs but the verbs are undefined! So how do you define them?
The Circular Definitions
initialization: to initialize a variable. It can be done at the time of
declaration.
assignment: to assign value to a variable. It can be done anywhere, only once with the final-identifier.
declaration: to declare value to a variable.
[update, trying to understand the topic with lambda calc]
D(x type) = (λx.x is declared with type)
A(y D(x type)) = (λy.y is assigned to D(x type))
%Then after some beta reductions we get initialization.
D(x type) me human // "me" declared with type "human"
A(y (D(x type) me human)) asking // "asking" assigned to the last declaration
%if the last two statemets are valid, an initialization exists. Right?
assignment: throwing away the old value of a variable and replacing it with a new one
initialization: it's a special kind of assignment: the first. Before initialization objects have null value and primitive types have default values such as 0 or false. Can be done in conjunction with declaration.
declaration: a declaration states the type of a variable, along with its name. A variable can be declared only once. It is used by the compiler to help programmers avoid mistakes such as assigning string values to integer variables. Before reading or assigning a variable, that variable must have been declared.
String declaration;
String initialization = "initialization";
declaration = "initialization"; //late initialization - will initialize the variable.
// Without this, for example, in java, you will get a compile-time error if you try
// to use this variable.
declaration = "assignment"; // Normal assignment.
// Can be done any number of times for a non-final variable
Declaration is not to declare "value" to a variable; it's to declare the type of the variable.
Assignment is simply the storing of a value to a variable.
Initialization is the assignment of a value to a variable at the time of declaration.
These definitions also applies to fields.
int i; // simple declaration
i = 42 // simple assignment
int[] arr = { 1, 2, 3 };
// declaration with initialization, allows special shorthand syntax for arrays
arr = { 4, 5, 6 }; // doesn't compile, special initializer syntax invalid here
arr = new int[] { 4, 5, 6 }; // simple assignment, compiles fine
However, it should be mentioned that "initialization" also has a more relaxed definition of "the first assignment to a variable", regardless of where it happens.
int i; // local variable declaration
if (something) i = 42;
System.out.println(i);
// compile time error: The local variable i may not have been initialized
This, however, compiles:
int i; // the following also compiles if i were declared final
if (something) i = 42;
else i = 666;
System.out.println(i);
Here i can be "initialized" from two possible locations, by simple assignments. Because of that, if i was an array, you can't use the special array initializer shorthand syntax with this construct.
So basically "initialization" has two possible definitions, depending on context:
In its narrowest form, it's when an assignment is comboed with declaration.
It allows, among other things, special array shorthand initializer syntax
More generally, it's when an assignment is first made to a variable.
It allows, among other things, assignments to a final variable at multiple places.
The compiler would do its best to ensure that exactly one of those assignments can happen, thus "initializing" the final variable
There's also JVM-context class and instance initialization, OOP-context object initialization, etc.
Here is a short explanation with some examples.
Declaration:
Declaration is when you declare a variable with a name, and a variable can be declared only once.
Example: int x;, String myName;, Boolean myCondition;
Initialization:
Initialization is when we put a value in a variable, this happens while we declare a variable.
Example: int x = 7;, String myName = "Emi";, Boolean myCondition = false;
Assignment:
Assignment is when we already declared or initialized a variable, and we are changing the value. You can change value of the variable as many time you want or you need.
Example:
int x = 7;
x = 12; .......We just changed the value.
String myName = "Emi";
myName = "John" .......We just changed the value.
Boolean myCondition = false;
myCondition = true; .......We just changed the value.
Note: In memory will be saved the last value that we put.
declaration: whenever you define a new variable with its type
assignment: whenever you change the value of a variable by giving it a new value
initialization: an assignment that is done together with the declaration, or in any case the first assignment that is done with a variable, usually it's a constructor call for an object or a plain assignment for a variable
I come from a C/C++ background, but the ideas should be the same.
Declaration - When a variable is declared, it is telling the compiler to set aside a piece of memory and associate a name (and a variable type) with it. In C/C++ it could look like this:
int x;
The compiler sees this and sets aside an address location for x and knows what methods it should use to perform operations on x (different variable types will use different access operations). This way, when the compiler runs into the line
x = 3 + 5;
It knows to put the integer value 8 (not the floating point value 8) into the memory location also known as 'x'.
Assignment - This is when you stuff a value into the previously declared variable. Assignment is associated with the 'equals sign'. In the previous example, the variable 'x' was assigned the value 8.
Initialization - This is when a variable is preset with a value. There is no guarantee that a variable will every be set to some default value during variable declaration (unless you explicitly make it so). It can be argued that initialization is the first assignment of a variable, but this isn't entirely true, as I will explain shortly. A typical initialization is a blend of the variable declaration with an assignment as follows:
int x = 6;
The distinction between initialization and assignment becomes more important when dealing with constants, such as this...
const int c = 15;
When dealing with constants, you only get to assign their value at the time of declaration/initialization. Otherwise, they can't be touched. This is because constants are often located in program memory vs data memory, and their actual assignment is occurring at compile time vs run time.
Step 1: Declaration : int a;
Step 2: Initialization : a = 5;
Step 3: Assignment: a = b; (ex: int b = 10 ; now a becomes 10)
Declaration
When we first create a variable of any Data Type is call Declaration. Example:
int obj;
String str;
Initialization
When (Declaration is completed) or variable is created the assigned any value to this variable is call Initialization. Example
int obj = 10;
String str = "Azam Khan";
Assignment
Reassign value to that variable that is already initialized is call Assignment. Example
int obj = 15;
obj = 20; // it print **20** value.
String str = "simple"
str = "Azam Khan" // it's result or print **Azam Khan** value...
Simple program
class ABC{
public static void main(String args[]){
int obj; // this is **Declaration:**
int testValue= 12; // After the **Declaration**,
testValue is **Initialize**.
testValue = 25;
System.out.println(textValue);
}
}
the output result is 25.
it saves the value of 25.