9 Things Virtually Null Inward Java

Java as well as cipher are uniquely bonded. There is hardly a Java programmer, who is non troubled yesteryear cipher pointer exception, it is the most infamous fact about. Even inventor of cipher concept has called it his billion dollar mistake, as well as thence why Java kept it? Null was at that topographic point from long fourth dimension as well as I believe Java designer knows that cipher creates to a greater extent than work than it solves, but even thence they went amongst it. It surprise me fifty-fifty to a greater extent than because Java's pattern philosophy was to simplify things, that's why they didn't bothered amongst pointers, operator overloading as well as multiple inheritance of implementation, they why null. Well I actually don't know the response of that question, what I know is that, doesn't thing how much cipher is criticized yesteryear Java developers as well as opened upwards source community, nosotros receive got to alive amongst that. Instead of ruing close cipher it's amend to larn to a greater extent than close it as well as brand certain nosotros purpose it correct. Why you lot should larn close cipher inwards Java? because If you lot don't pay attending to null, Java volition brand certain that you lot volition endure from dreaded java.lang.NullPointerException as well as you lot volition larn your lesson difficult way. Robust programming is an fine art as well as your team, client as well as user volition appreciate that. In my experience, 1 of the main reasons of NullPointerException are non plenty cognition close cipher inwards Java. Many of you lot already familiar amongst cipher but for those, who are not, tin larn some quondam as well as novel things close cipher keyword. Let's revisit or larn some of import things close cipher inwards Java.



What is Null inwards Java

As I said, cipher is really very of import concept inwards Java. It was originally invented to announce absence of something e.g. absence of user, a resources or anything, but over the twelvemonth it has troubled Java programmer a lot amongst nasty cipher pointer exception. In this tutorial, nosotros volition larn basic facts close cipher keyword inwards Java as well as explore some techniques to minimize cipher checks as well as how to avoid nasty cipher pointer exceptions.


1) First thing, first,  null is a keyword inwards Java, much similar public, static or final. It's illustration sensitive, you lot cannot write null as Null or NULL, compiler volition non recognize them as well as laissez passer error.

Object obj = NULL; // Not Ok Object obj1 = null  //Ok

Programmer's which are coming from other linguistic communication receive got this problem, but purpose of modern 24-hour interval IDE's has made it insignificant. Now days, IDE similar Eclipse or Netbeans tin right this mistake, piece you lot type code, but inwards the era of notepad, Vim as well as Emacs, this was a mutual trial which could easily swallow your precious time.


2) Just similar every primitive has default value e.g. int has 0, boolean has false, null is the default value of whatever reference type, loosely spoken to all object every bit well. Just similar if you lot create a boolean variable, it got default value every bit false, whatever reference variable inwards Java has default value null. This is truthful for all sort of variables e.g. member variable or local variable, instance variable or static variable, except that compiler volition warn you lot if you lot purpose a local variable without initializing them. In gild to verify this fact, you lot tin encounter value of reference variable yesteryear creating a variable as well as them printing it's value, every bit shown inwards next code snippet :

 who is non troubled yesteryear cipher pointer exception nine Things close Null inwards Javaprivate static Object myObj; public static void main(String args[]){     System.out.println("What is value of myObjc : " + myObj); }   What is value of myObjc : null

This is truthful for both static as well as non-static object, every bit you lot tin encounter hither that I made myObj a static reference thence that I tin purpose it straight within master copy method, which is static method as well as doesn't allow non-static variable inside.


3) Unlike mutual misconception, null is non Object or neither a type. It's but a especial value, which tin hold out assigned to whatever reference type as well as you tin type form cipher to whatever type, every bit shown below :

String str = null; // cipher tin hold out assigned to String Integer itr = null; // you lot tin assign cipher to Integer also Double dbl = null;  // cipher tin too hold out assigned to Double          String myStr = (String) null; // cipher tin hold out type form to String Integer myItr = (Integer) null; // it tin too hold out type casted to Integer Double myDbl = (Double) null; // yep it's possible, no error

You tin encounter type casting cipher to whatever reference type is fine at both compile fourth dimension as well as runtime, different many of you lot powerfulness receive got thought, it volition too non throw NullPointerException at runtime.


4) cipher tin only hold out assigned to reference type, you lot cannot assign cipher to primitive variables e.g. int, double, float or boolean. Compiler volition complain if you lot practice so, every bit shown below.

int i = null; // type mismatch : cannot convert from cipher to int short sec = null; //  type mismatch : cannot convert from cipher to short byte b = null: // type mismatch : cannot convert from cipher to byte double d = null; //type mismatch : cannot convert from cipher to double          Integer itr = null; // this is ok int j = itr; // this is too ok, but NullPointerException at runtime

As you lot tin see, when you lot straight assign cipher to primitive error it's compile fourth dimension error, but if you lot assign cipher to a wrapper flat object as well as and thence assign that object to respective primitive type, compiler doesn't complain, but you lot would hold out greeted yesteryear cipher pointer exception at runtime. This happens because of autoboxing inwards Java, as well as nosotros volition encounter it inwards adjacent point.


5) Any wrapper flat amongst value cipher volition throw java.lang.NullPointerException when Java unbox them into primitive values. Some programmer makes incorrect supposition that, auto boxing volition convey tending of converting null into default values for respective primitive type e.g. 0 for int, fake for boolean etc, but that's non true, every bit seen below.

Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error

but when you lot run to a higher house code snippet you lot volition encounter Exception inwards thread "main" java.lang.NullPointerException  in your console. This happens a lot piece working amongst HashMap as well as Integer key values. Code similar shown below volition interruption every bit shortly every bit you lot run.

import java.util.HashMap; import java.util.Map;   /**  * An illustration of Autoboxing as well as NullPointerExcpetion  *   * @author WINDOWS 8  */  public class Test {      public static void main(String args[]) throws InterruptedException {                Map numberAndCount = new HashMap<>();        int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};              for(int i : numbers){          int count = numberAndCount.get(i);          numberAndCount.put(i, count++); // NullPointerException here       }            }  }  Output: Exception inwards thread "main" java.lang.NullPointerException  at Test.main(Test.java:25)

This code looks really uncomplicated as well as innocuous. All you lot are doing is finding how many times a release has appeared inwards a array, classic technique to notice duplicates inwards Java array. Developer is getting the previous count, increasing it yesteryear 1 as well as putting it dorsum into Map. He powerfulness receive got idea that auto-boxing volition convey tending of converting Integer to int , every bit it doing piece calling position method, but he forget that when at that topographic point is no count be for a number, get() method of HashMap volition furnish null, non null because default value of Integer is cipher non 0, as well as auto boxing volition throw cipher pointer exception piece trying to convert it into an int variable. Imagine if this code is within an if loop as well as doesn't run inwards QA environs but every bit shortly every bit you lot position into production, BOOM :-)


6)instanceof operator volition furnish fake if used against whatever reference variable amongst null value or null literal itself, e.g.

Integer iAmNull = null; if(iAmNull instanceof Integer){    System.out.println("iAmNull is instance of Integer");                               }else{    System.out.println("iAmNull is NOT an instance of Integer"); }  Output : iAmNull is NOT an instance of Integer

This is an of import holding of instanceof operation which makes it useful for type casting checks.


7) You may know that you lot cannot telephone phone a non-static method on a reference variable amongst null value, it volition throw NullPointerException, but you lot powerfulness non know that, you lot can call static method amongst reference variables amongst null values. Since static methods are bonded using static binding, they won't throw NPE. Here is an illustration :            

public class Testing {                 public static void main(String args[]){       Testing myObject = null;       myObject.iAmStaticMethod();       myObject.iAmNonStaticMethod();                                 }                   private static void iAmStaticMethod(){         System.out.println("I am static method, tin hold out called yesteryear cipher reference");    }                   private void iAmNonStaticMethod(){  System.out.println("I am NON static method, don't appointment to telephone phone me yesteryear null");    }   }  Output: I am static method, tin hold out called yesteryear null reference Exception inwards thread "main" java.lang.NullPointerException                at Testing.main(Testing.java:11)


8) You tin exceed null to methods, which accepts whatever reference type e.g. public void print(Object obj) can hold out called every bit print(null). This is Ok from compiler's yell for of view, but behaviour is alone depends upon method. Null rubber method, doesn't throw NullPointerException inwards such case, they but acquire out gracefully. It is recommended to write cipher rubber method if concern logic allows.

9) You tin compare cipher value using ==  (equal to ) operator as well as !=  (not equal to) operator, but cannot purpose it amongst other arithmetics or logical operator e.g. less than or greater than. Unlike inwards SQL, inwards Java null == null volition furnish true, every bit shown below :

public class Test {      public static void main(String args[]) throws InterruptedException {                 String abc = null;        String cde = null;                if(abc == cde){            System.out.println("null == cipher is truthful inwards Java");        }                if(null != null){            System.out.println("null != cipher is fake inwards Java");         }                // classical cipher check        if(abc == null){            // practice something        }                // non ok, compile fourth dimension error        if(abc > null){                    }     } }  Output: null == null is true inwards Java

That's all close cipher inwards Java. By some sense inwards Java coding as well as yesteryear using simple tricks to avoid NullPointerExcpetion, you lot tin brand your code cipher safe. Since cipher tin hold out treated every bit empty or uninitialized value it's frequently source of confusion, that's why it's to a greater extent than of import to document behaviour of a method for cipher input. Always remember, cipher is default value of whatever reference variable as well as you lot cannot telephone phone whatever instance method, or access an instance variable using cipher reference inwards Java.


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Belum ada Komentar untuk "9 Things Virtually Null Inward Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel