9 Things Near Naught Inward Java

Advertisement

Masukkan script iklan 970x90px

9 Things Near Naught Inward Java

Rabu, 10 Juni 2020

Java in addition to aught are uniquely bonded. There is hardly a Java programmer, who is non troubled past times aught pointer exception, it is the most infamous fact about. Even inventor of aught concept has called it his billion dollar mistake, in addition to thus why Java kept it? Null was in that place from long fourth dimension in addition to I believe Java designer knows that aught creates to a greater extent than occupation than it solves, but yet they went alongside 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 alongside pointers, operator overloading in addition to 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 aught is criticized past times Java developers in addition to opened upward source community, nosotros direct keep to alive alongside that. Instead of ruing virtually aught it's meliorate to larn to a greater extent than virtually it in addition to brand certain nosotros role it correct. Why yous should larn virtually aught inward Java? because If yous don't pay attending to null, Java volition brand certain that yous volition endure from dreaded java.lang.NullPointerException in addition to yous volition larn your lesson difficult way. Robust programming is an fine art in addition to your team, client in addition to user volition appreciate that. In my experience, 1 of the main reasons of NullPointerException are non plenty cognition virtually aught inward Java. Many of yous already familiar alongside aught but for those, who are not, tin larn some former in addition to novel things virtually aught keyword. Let's revisit or larn some of import things virtually aught inward Java.



What is Null inward Java

As I said, aught is real very of import concept inward 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 alongside nasty aught pointer exception. In this tutorial, nosotros volition larn basic facts virtually aught keyword inward Java in addition to explore some techniques to minimize aught checks in addition to how to avoid nasty aught pointer exceptions.


1) First thing, first,  null is a keyword inward Java, much similar public, static or final. It's instance sensitive, yous cannot write null as Null or NULL, compiler volition non recognize them in addition to plough over error.

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

Programmer's which are coming from other linguistic communication direct keep this problem, but role of modern solar daytime IDE's has made it insignificant. Now days, IDE similar Eclipse or Netbeans tin right this mistake, spell yous type code, but inward the era of notepad, Vim in addition to Emacs, this was a mutual final result 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 yous create a boolean variable, it got default value every bit false, whatever reference variable inward Java has default value null. This is truthful for all form of variables e.g. member variable or local variable, instance variable or static variable, except that compiler volition warn yous if yous role a local variable without initializing them. In gild to verify this fact, yous tin run into value of reference variable past times creating a variable in addition to them printing it's value, every bit shown inward next code snippet :

 who is non troubled past times aught pointer exception ix Things virtually Null inward 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 in addition to non-static object, every bit yous tin run into hither that I made myObj a static reference thus that I tin role it straight within principal method, which is static method in addition to doesn't allow non-static variable inside.


3) Unlike mutual misconception, null is non Object or neither a type. It's simply a especial value, which tin survive assigned to whatever reference type in addition to you tin type cast aught to whatever type, every bit shown below :

String str = null; // aught tin survive assigned to String Integer itr = null; // yous tin assign aught to Integer also Double dbl = null;  // aught tin too survive assigned to Double          String myStr = (String) null; // aught tin survive type cast to String Integer myItr = (Integer) null; // it tin too survive type casted to Integer Double myDbl = (Double) null; // yep it's possible, no error

You tin run into type casting aught to whatever reference type is fine at both compile fourth dimension in addition to runtime, different many of yous mightiness direct keep thought, it volition too non throw NullPointerException at runtime.


4) aught tin only survive assigned to reference type, yous cannot assign aught to primitive variables e.g. int, double, float or boolean. Compiler volition complain if yous practice so, every bit shown below.

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

As yous tin see, when yous straight assign aught to primitive error it's compile fourth dimension error, but if yous assign aught to a wrapper shape object in addition to and thus assign that object to respective primitive type, compiler doesn't complain, but yous would survive greeted past times aught pointer exception at runtime. This happens because of autoboxing inward Java, in addition to nosotros volition run into it inward adjacent point.


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

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

but when yous run higher upward code snippet yous volition run into Exception inward thread "main" java.lang.NullPointerException  in your console. This happens a lot spell working alongside HashMap in addition to Integer key values. Code similar shown below volition interruption every bit before long every bit yous run.

import java.util.HashMap; import java.util.Map;   /**  * An instance of Autoboxing in addition to 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 inward thread "main" java.lang.NullPointerException  at Test.main(Test.java:25)

This code looks real uncomplicated in addition to innocuous. All yous are doing is finding how many times a let on has appeared inward a array, classic technique to observe duplicates inward Java array. Developer is getting the previous count, increasing it past times 1 in addition to putting it dorsum into Map. He mightiness direct keep idea that auto-boxing volition convey help of converting Integer to int , every bit it doing spell calling position method, but he forget that when in that place is no count be for a number, get() method of HashMap volition provide null, non null because default value of Integer is aught non 0, in addition to auto boxing volition throw aught pointer exception spell trying to convert it into an int variable. Imagine if this code is within an if loop in addition to doesn't run inward QA environs but every bit before long every bit yous position into production, BOOM :-)


6)instanceof operator volition provide faux if used against whatever reference variable alongside 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 belongings of instanceof operation which makes it useful for type casting checks.


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

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 survive called past times aught reference");    }                   private void iAmNonStaticMethod(){  System.out.println("I am NON static method, don't appointment to telephone telephone me past times null");    }   }  Output: I am static method, tin survive called past times null reference Exception inward thread "main" java.lang.NullPointerException                at Testing.main(Testing.java:11)


8) You tin overstep null to methods, which accepts whatever reference type e.g. public void print(Object obj) can survive called every bit print(null). This is Ok from compiler's signal of view, but conduct is exclusively depends upon method. Null condom method, doesn't throw NullPointerException inward such case, they simply leave of absence gracefully. It is recommended to write aught condom method if occupation organization logic allows.

9) You tin compare aught value using ==  (equal to ) operator in addition to !=  (not equal to) operator, but cannot role it alongside other arithmetics or logical operator e.g. less than or greater than. Unlike inward SQL, inward Java null == null volition provide 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 == aught is truthful inward Java");        }                if(null != null){            System.out.println("null != aught is faux inward Java");         }                // classical aught check        if(abc == null){            // practice something        }                // non ok, compile fourth dimension error        if(abc > null){                    }     } }  Output: null == null is true inward Java

That's all virtually aught inward Java. By some sense inward Java coding in addition to past times using simple tricks to avoid NullPointerExcpetion, yous tin brand your code aught safe. Since aught tin survive treated every bit empty or uninitialized value it's oft source of confusion, that's why it's to a greater extent than of import to document conduct of a method for aught input. Always remember, aught is default value of whatever reference variable in addition to yous cannot telephone telephone whatever instance method, or access an instance variable using aught reference inward Java.


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