I was confusing since from last several days that how initialization of instance properties through constructor is being done.
Just consider this case
class Demo
{
int a;
int b;
Demo(int a,int b)
{
this.a*=a;//this produces 0 here
this.b*=b;//this produces 0 here
}
public static void main(String[] args)
{
Demo d1=new Demo(20,30);
d1.show();
}
public void show()
{
System.out.println(this.a);
System.out.println(this.b);
}
}
How this is initializing here. As i know constructor initialize a value once.assignments can be possible several times.
The initial value for an integer is 0. Your actual assignment is this:
a = 0 * 20
which will always return 0.
Some documentation:
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.
Integral fields are initialized to 0 by default (as per JLS ยง4.12.5), so multiplying this.a (0) and this.b (0) by a and b respectively will not change their value of 0. Zero times any number is still zero.
Initially this.a (the class variable) is zero so it will produce zero when you multiply it by a (the argument). This is your problem here.
Because the default value of int is 0.
So the line
this.a*=a;
is equivalent to
0 * 20
which equals 0.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The initial value for an integer is 0. Your actual assignment is this:
a = 0 * 20
which will always return 0.
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.
Related
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.
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
Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.