Posts

Showing posts with the label null

Dose Java has pointer ?

N o, Java does not have pointers. This was an intentional decision by the creators of Java, because most people would agree that having pointers creates a lot of potential for bugs in the code – pointers can be quite confusing, especially to new programmers. Because arrays and strings are provided as class types in Java, there is no need for pointers to those constructs. By not allowing pointers, Java provides effectively provides another level of abstraction to the programmer.Java has references, but not pointers.All  values of non primitive type / reference type are always stored as pointers in the memory.  Here are some of the  differences between references in Java and pointers in C++: 1 .  References store an address.  That address is the address in memory of the object.  So, when a class is declared like so:  "PersonClass y = new PersonClass();" the "y" variable actually stores an  address in memory. If you w...

There is no concept of pointers in Java, but still we get null pointer exceptions. Why?

The premise of the question is wrong, because there  is  a concept of pointers in Java. They are called references, and the places where they are used differ from some other languages, but they are pointers nevertheless. In Java, there are only primitive types and reference types. So all non-primitive values are  references . A "reference" is defined ( JLS 4.3.1 ) as either a  pointer to an object , or the null reference (which is a null pointer, hence the "null pointer exception").

What exactly is null in memory?

Image
Recall what is a variable and what is a value. A common metaphor is that a variable is similar to a box. Just as you can use a box to store something, you can use a variable to store a value. When declaring a variable, we need to set its type. There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references. In this case, the initialization statement declares a variables “x”. “x” stores String reference. It is null here. The following visualization gives a better sense about this concept. If x = "abc", it looks like the following: What exactly is null in memory? Or What is the null value in Java? First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.