When initialising variables with default values:
What is the difference between:
private static String thing = null;
and
private static String thing = "";
I'm not understanding which is better and why nor what is the best way to deal with other data types.
private static int number = 0;
private static double number = 0;
private static char thing = 0;
Sorry I struggle learning new languages.
Except for initializing String to an empty string
private static String thing = "";
the other assignments are unnecessary: Java will set all member variables of primitive types to their default values, and all reference types (including java.String) to null.
The decision to initialize a String to a null or to an empty string is up to you: there is a difference between "nothing" and "empty string" *, so you have to decide which one you want.
* The differences between "nothing" and "empty string" stem from the observation that no operations are possible on a null string - for example, its length is undefined, and you cannot iterate over its characters. In contrast, the length of an empty string is well-defined (zero), and you can iterate over its characters (it's an empty iteration).
When you make:
private static String ptNo = "";
you are creating a variable ptNo and making it to refer an object String "".
When you make:
private static String ptNo = null;
you are creating a variable, but it doesn't refer to anything.
null is the reserved constant used in Java to represent a void reference i.e a pointer to nothing.
In Java null and an empty are not the same thing.
From suns java tutorial
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.
"" is an actual string with empty value.
null means that the String variable points to nothing.
As an example,
String a="";
String b=null;
a.equals(b) returns false because "" and null do not occupy the same space in memory.
Related
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.
I need to create a class that initializes the instance variable in it. In the if statement I am getting a Type mismatch error: cannot convert from int to boolean.
public class ProccessForm {
private String UserInfo[];
public ProccessForm(String[] UserInfo) {
UserInfo = new String[6];
if(UserInfo.length){
}
}
// if length of array passed does not equal length of current array
if (UserInfo.length != this.length) {
// do this
}
Right now in your if statement UserInfo.length returns an integer, if statements deal with Boolean logic so you need to use a conditional operator such as (<, >, <=, >=, ==, or !=) when working with primitives.
You are getting a type mismatch error because you're trying to compare an int value to a boolean value. The length field of primitive arrays returns an int data type and if blocks evaluate boolean value so you need to compare it with another object of the same raw type. Learn more about if-then and if-then-else statements as well as Arrays.
The following code should show you how your code should look like but there are a couple of more issues with your code that need to be addressed.
public class ProcessForm {
private String[] userInfo = new String[6];
public ProcessForm(String[] userInfo) {
if (this.userInfo.length == userInfo.length) {
// Do something here...
}
}
}
You should stick to a standard Java naming convention.
You also had a typo in the class name; process is spelled with a single c.
Java does not use C-style array declarations so you should declare your variable like this: String[] userInfo instead of String userInfo[] like you would in C language.
There is no need to initialize the class field inside a constructor when you're not using any parameter values in the initialization process. You can just declare and initialize it on the same line.
Remember to always use this keyword when you want to address class fields that have the same names as local variables otherwise you will be addressing local variables instead.
I have a doubt about null assigning to variable in Java. In my program I have assigned null to String variable as String str_variable = null;. For the learning purpose i assigned null integer variable as int int_variable = null; It shows error Add cast with Integer. So that rewrite the above int declaration as Integer int_variable = null;. This does not shows errors. I do not know the reason of these two kind of declaration.
Please the difference between to me.
String str_variable = null;
int int_variable = null; // error.
Integer int_variable1 = null; // no error.
String and Integer are both classes, in a way they are not native data types that is why it is always okay for you to set null as an initial value, however for int you must always initialize it with a number, one good way to find out their appropriate initialization value is to create variables outside your main(), example String var1; int var2; then use System.out.println(var1); System.out.println(var2); within the main()
to see what was placed as an initial value when you run the program.
int is a primitive, Integer is a class.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
int is a primitive type, Integer is a wrapper class type extending Object class. Non-referencing objects can be null but primitives cannot. That's why you get an error message saying you need casting.
You can use a line like int num = (Integer) null;, this is how casting is done, however you will get NullPointerException when you try to use num anywhere in your code since a non-referencing(null) Integer object doesn't hold / wrap a primitive value.
Is it null for Object type?
class C {
int i;
String s;
public C() {}
}
Will s be always null?
What about simple types as int? What will that be? Zero or an arbitrary value?
What about local variables in methods?
public void meth() {
int i;
}
What is the unitialized value of i?
Relying on such default values, however, is generally considered bad
programming style.
Ok, what do you suggest we do?
class A {
String s = "";
int i = 0;
}
OR:
class A {
String s;
int i;
public A() {
// default constructor
s = "";
i = 0;
}
}
Which is better and why?
From suns java tutorial
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'
boolean false
String (or any object) null
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.
For member variables:
The default value for String is null. The default value for primitives is 0 (or 0.0 for floating point values).
For local variables:
You must explicitly initialise a local variable before using it.
As to the second part of your question:
You can always say String s = ""; in the member variable definition, or s = ""; in the constructor. Then you know it will have a non-null value. (Also, in your setter you'd need to ensure that someone doesn't try and set it back to null.)
Fields: Objects default to null; ints, longs and shorts to 0; Strings to null; booleans to false. It's all here.
The compiler will force you to initialise variables declared in methods, local variables, yourself.
Primitive fields are initialized to 0 / false. Objects are initialized to null . But frankly, you could have tried that one..
As for the setter-method question: The whole point of setters is that they can check if the object passed conforms to the requirements of the class. e.g.
public void setS(String s) {
if (s == null)
throw new IllegalArgumentException("S must not be null");
this.s = s;
}
Or, with Google Collections/Google Guava:
public void setS(String s) {
this.s = Preconditions.checkNotNull(s, "S must not be null");
}
Of course, you can define arbitrary constraints, e.g.:
/**
* Sets the foo. Legal foo strings must have a length of exactly 3 characters.
*/
public void setFoo(String foo) {
if (foo == null)
throw new IllegalArgumentException("Foo must not be null");
if (foo.length() != 3)
throw new IllegalArgumentException("Foo must have exactly 3 characters");
...
Of course in such a case you should always state the correct range of values for your properties in the JavaDoc of the setter and/or of the class.
JLS 4.12.5. Initial Values of Variables
Each class variable, instance variable, or array component is
initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of
(byte)0.
For type short, the default value is zero, that is, the value of
(short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is,
'\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.
What is difference between in the following statements
String name = "Tiger";
final String name ="Tiger";
Although the String class is final class, why do we need to create a String "CONSTANT" variable as final?
final in this context means that the variable name can only be assigned once. Assigning a different String object to it again results in a compile error.
I think the source of the confusion here is that the final keyword can be used in several different contexts:
final class: The class cannot be subclassed.
final method: The method cannot be overridden.
final variable: The variable can only be assigned once.
See the Wikipedia article on final in Java for examples on each case.
"final" means different things in the two cases.
The java.lang.String class is final. This means you can't inherit from it.
The variable "name" is final, meaning that you can't change it to point to a different instance of String. So a non-final String variable isn't a constant, because you could read it at two different times and get different values.
As it happens, Java string objects are also immutable. This means that you cannot modify the value which a particular String object represents. Compare this with an array - you can replace the first element of an array object with a different object, but you can't replace the first character of a String object with a different char. This is why String.replace() returns a new string - it can't modify the old one.
One reason that String is final is to prevent an instance of a subclass of String, which implements mutable behaviour, being passed in place of a String.
But whether you can modify a particular object, and whether you can assign a different object to a variable, are completely different concepts. One is a property of String objects, and the other is a property of String variables, which are references to String objects.
Remember that Java final keyword serves two purposes in this case:
it means the reference cannot be set to another String-- i.e. you cannot subsequently do "name = ...";
but crucially, it means that the reference is correctly published to other threads (see linked article for more details, or works such as Goetz et al, "Java Concurrency in Practice".
You are confusing immutable with final.
String, like Integer and Long, is an immutable class in that the internal data is protected from modification through encapsulation.
However, like Ayman said, final refers to the pointer to the string.
Have a look at The final word on the final keyword.
String name = "scott";
name = "tiger"; // OK
final String gender = "male";
gender = "female"; // won't compile you cannot reassign gender cause it's final
If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.
NOTE :
If you mark variable of a reference type as final, that variable cannot refer to any other object. However, you can change the object's contents, because only the reference itself is final.
SOURCE : Final Keyword in Java
To deduce that String objects are Final by default is in itself a vague statement. The basics of Java dictate that if an instance variable is not pointing to a memory location it becomes eligible for Garbage collection. The same thing happens with the String objects. They are immutable but their references can be changed. To overcome this we can use "Final String s1 = "Final String" " the final keyword won't allow any assignment to s1 except at the time of First Declaration, making it truly immutable.
public class DemoStringF
{
String s1; //Declaring an Instance Variable to type String.
public static void main(String... args)
{
DemoStringF d = new DemoStringF ();
d.s1 = "Intializing s1 here"; //Initializing the s1
System.out.println("Value ref. by s1 is " +d.s1); //Displays the String
by which s1 is
initialized.
System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays the
value of the s1.
d.s1 = d.s1.concat(" Adding String to s1"); //Changing the value ref. by
s1.
System.out.println("Value ref. by s1 after concat() is " +d.s1);
//Displays a new value of s1.
System.out.println("Value of s1 is " +d.s1.hashCode()); //Displays
the value of the s1.
}
}