I am a beginner in Java, struggling to understand the following problem with variable initialisation, would appreciate an expert help.
Given the code from an exam:
public class SimpleCalc {
public int value;
public void calculate() { value += 7; }
}
AND
public class MultiCalc extends SimpleCalc {
public void calculate() { value -= 3; }
public void calculate(int multiplier) {
calculate();
super.calculate();
value *= multiplier;
}
public static void main (String[] args) {
MultiCalc calculator = new MultiCalc ();
calculator.calculate(2);
System.out.println(calculator.value);
}
}
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;). But, the code works and behaves as if the variable "value" is assigned 0 (same as public int value=0;). Could someone explain please why does this happen? Many thanks
. But, the code works and behaves as if the variable "value" is
assigned 0 (same as public int value=0;).
instance variables in java get default values. i.e, int get 0 as default value, float get 0.0 and so on. thus if you don't initialize, they get default values.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;).
Failing to initialise a variable which must be initialised is checked by the compiler and is a compile time error.
Runtime errors are thrown at Runtime. i.e. when you run a program which has been successfully compiled. The only runtime error you will get from failing to set a value is a NullPointerException (for accessing a null reference), or rarely an ArithmeticException if you divide by an integer which is zero.
final fields and local variables must be initialised, but non final fields will value their default value.
Primitive types in Java always get assigned a default value. For an int this is always 0.
If you were to use a Integer object (rather than int) you would see a null pointer exception being thrown if it wasn't initialised.
This kind of initializations happen for instance variables, in java. The variable 'value' is an instance variable which exists in each of the object of that class. Instance variables of data type int have default value 0 assigned to it. Different data types(of instance variables) have different default values.
Example
Related
Why is there a difference between the following two programs A & B. Shouldn't they run identical? For some reason the changer in the case of the array is changing the original value of the input array.
Program A:
public static void changer(int tester) {
tester = tester*2;
}
public static void main() {
int value = 1;
out.println(value);
changer(value);
out.println(value);
}
which gives me the output:
1
1
Program B:
public static void changer(int[] tester) {
tester[0] = tester[0]*2;
}
public static void main(){
int[] value = {1};
out.println(value[0]);
changer(value);
out.println(value[0]);
}
which gives me the output:
1
2
Changing a value in a called method does not change the value in the calling method. In Program B, you're not changing the array, you're changing a value inside the array, and that is visible in the calling method.
In your first example, you passed an int (tester) to the function, and then assigned a new value to it. Since java is pass-by-value, assignment has not effect outside of the callee scope, and so the original value was not changed in the call site.
In the second example, you passed an int array to the function, and then you did not assign to it, but modeified its content, by assigning to a specific cell inside of it, so the value was changed in the call site as well.
Passing primitive data type ( i.e int, double, long, float, ....) to a function or method will be " PASSED BY VALUE". In program A, the argument passed to method is a primitive data (int), so you just passed a copy of the origin value. Any change to it, will not affect the origin number.
But passing Reference/Object data type (i.e, Array, ArrayList, HashMap,...) to a function will be " PASSED OBJECT BY VALUE," which means the method is given copy of the reference to the object. So any change to it, will change the origin reference. In program B, you passed a reference copy of an array. That is why it has been modified.
When arrays work like pointers. When you use
tester[0] = tester[0]*2;
You are basically telling compiler to update element in memory on location tester[0]
This question had been asked so many times. Java passes everything by value and this is especially true for primitive such as int.
When you pass an int argument, you are passing in the value, not the reference of the variable.
public static void main(String[] args){
int value= 5;
changer(val);
}
public static void changer (int tester){
//A variable call tester holding the value of 5
}
A local variable call tester with value of 5 will be created, because you passed in a value of 5. Variable val itself was not passed in.
Any changes done within the method is merely changing the local variable tester.
This explains why the value of val remains unchanged.
When you pass in an array, it still passes by value, but the value does not contain all the values of individual array element. It will be very inefficient to copy the entire array's value for every method invocation. The value holds the reference of the array. Thus, tester now holds the reference of the val.
public static void main(String[] args){
int[] val= 5;
changer(val);
}
public static void changer (int[] tester){
//A variable call tester holding the reference of val array.
}
Since tester is now pointing at the original array: val. Anything you changed in the method will affect the original array.
Is it possible to create an int variable with no value, then quantify it in my code, and then "unquantify" it so that it no longer has a value?
Example:
class Test {
int integer;
public static void main (String[] args) {
integer = 1;
...
//do stuff
...
integer = null; //Does this line set integer's value to nothing?
// I want to be able to reset the value of integer back to what it was when I defined it (the value was nothing, it had no value)
}
}
EDIT: grammar
You cannot assign null to a primitive type.
You could use the Integer object like this:
Integer i = null;
If you have an int as classmember and you access it inside a method the value of the int will be 0.
Also you have to make your variable static to access it in your main.
As an alternative to null you might like to look at the Optional class that was added in Java 8. It is useful for declaring variables that may or may not have a value:
Optional<Integer> value = Optional.empty();
value = Optional.of(4);
value.ifPresent(n -> method(n));
If used well it can make the code handling optional values much more obvious and transparent than using null.
Code:
public class A {
public static void main(String[] args) {
int i;
System.out.println(i);
}
}
When I run this, instead of printing the default value of int i.e, 0, it cries an error that The local variable i may not have been initialized.
How come and if initialization is mandatory, then why do the primitive data types have default values at all? They might as well have garbage values as C++ does.
Default values are used not for a local variables, only for a fields in a class:
public class A {
int i;
public static void main(String[] args) {
System.out.println(i);
}
}
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
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.
My question is: how to assign default zero to an static integer variable?
This is my code:
class Point {
static int i;
public static void main(String[] args) {
System.out.println("" + i);
}
}
The output must be:
0
All class level numbered primitives will be initialized to 0.
All class level Objects will be initialized to null;
Other default values are
byte 0
char '\u0000'
boolean false
Class' primitive members (static or non-static) are set with default value as described here.
int values are set to 0 by default.
Since i is an integer it allocates the default value to zero
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
This happened only if you are doing at class level
If it is a local variable,you have to initalize before you use. Otherwise compile time error.