If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException. You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null). Reference variables can be set to null which means " I am referencing nothing". Now here is where things get interesting. All primitives have to be initialized to a usable value before they are manipulated. These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. For example variables of type Object are references.Ĭonsider the following code where you declare a variable of primitive type int and don't initialize it: int x By convention reference types are usually denoted with a type that starts in uppercase. to access a method or field, or using [ to index an array. If you want to manipulate the Object that a reference variable refers to you must dereference it. References: variables that contain the memory address of an Object i.e. For example variables of type int or char are primitives. By convention primitive types start with a lowercase letter. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. There are two overarching types of variables in Java:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |