in Line 7 i get nullpointerexception, how can i fix that ? any ideas?  private void updateHeights(BSTreeNode v) {   BSTreeNode u = v;    while (u != null) {     int bfc=updateNodeHeight(u);     u = u.parent;      if (bfc&lt;=-2) {        if( getHeight(u.left.left) &gt;= getHeight(u.left.right) ) { // Null Pointer Exception         u = rotateRight(u);        } else {         u=LR(u);       }     }   } }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
36280
Specifically, with a SortedMap&lt;Vector&lt;String&gt;, int&gt; I get "dimensions expected after this (int) token." Help!
67536
I have a class with a nullable int? datatype set to serialize as an xml element.  Is there any way to set it up so the xml serializer will not serialize the element if the value is null?    I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute."  [Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score {     private int? iID_m;     ...      /// &lt;summary&gt;     ///      /// &lt;/summary&gt;             public int? ID      {          get          {              return iID_m;          }          set          {              iID_m = value;          }      }      ... }   The above class will serialize to:  &lt;Score xmlns="http://mycomp.com/test/score/v1"&gt;     &lt;ID xsi:nil="true" /&gt; &lt;/Score&gt;   But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like
40162
Please demonstrate how the ternary operator works with a regular if/else block. Example:  Boolean isValueBig = value &gt; 100 ? true : false;     Exact Duplicate:
77222
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.  I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks @Dave Ray  My implementation considerations are typical    performance ease of implementation and maintenance (simplicity?) reliability flexibility (i.e. can I call from a remote machine, etc.)   Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?  (Stuff people have actually done and can provide real-life feedback on would be great!)
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
80203
This error should be a simple one but I cant seem to make it work. The problem lies in the fact that this very same code works earlier in the program. I don's see any reason for it to be sending an error on this instance and not the four previous ones. Reference the code below, and feel free to provide any criticism you may have as it should make me better. If it matters, I am using Sharp Develop 2.2.  Here is an example of the code that works:  void calc2Click(object sender, EventArgs e) {     if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_e.Text))     {         MessageBox.Show("Enter either kVA and Voltage or FLA and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);     }                 if (!String.IsNullOrEmpty(tb2_kva.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_kva.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * 1000) / (1.732050808m * y); //the m at the end of the decimal allows for the multiplication of decimals                 tb2_fla.Text = z.ToString();             tb2_fla.Text = Math.Round(z,2).ToString();     }         else     {         if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_fla.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * y * 1.732050808m) / 1000; //the m at the end of the decimal allows for the multiplication of decimals               tb2_kva.Text = Math.Round(z,2).ToString();      }   Here is the example of the code that sends the error in the subject line of this post:  void Calc4Click(object sender, EventArgs e) {         if (!String.IsNullOrEmpty(tb4_fla.Text) &amp;&amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_kw.Text) &amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_e.Text))         {   //If values are entered improperly, the following message box will appear         MessageBox.Show("Enter either FLA and Voltage or kW and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);         }              if (!String.IsNullOrEmpty(tb4_fla.Text)&amp;&amp; !String.IsNullOrEmpty(tb4_e.Text)&amp;&amp; String.IsNullOrEmpty(tb4_kw.Text))         {//If the user eneters FLA and Voltage calculate for kW              decimal x, y, z;             x = decimal.Parse(tb4_fla.Text);             y = decimal.Parse(tb4_e.Text);             z = (x*y)*(.8 * 1.732050808m);             tb4_kw.Text = Math.Round(z,0).ToString();          }                         if (!String.IsNullOrEmpty(tb4_kw.Text) &amp;&amp; !String.IsNullOrEmpty(tb4_e.Text) &amp;&amp; String.IsNullOrEmpty(tb4_fla.Text))         {;//If the user enters kW and Voltage calculate for FLA             decimal x, y, z;             x = decimal.Parse(tb4_kw.Text);             y = decimal.Parse(tb4_e.Text);             z = (1000 * x)/(y * 1.732050808m)* .8;             tb4_fla.Text = Math.Round(z,0).ToString();         }      }   I appreciate any help that I can get.  Thank you.
11842
I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement makes code look very ugly.
45757
I have a Category entity which has a Nullable ParentId field. When the method below is executing and the categoryId is null, the result seems null however there are categories which has null ParentId value.  What is the problem in here, what am I missing?  public IEnumerable&lt;ICategory&gt; GetSubCategories(long? categoryId) {     var subCategories = this.Repository.Categories.Where(c =&gt; c.ParentId == categoryId)         .ToList().Cast&lt;ICategory&gt;();      return subCategories; }   By the way, when I change the condition to (c.ParentId == null),  result seems normal.
24404
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.  A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.  Update for clarification: The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
2097
I'm getting a NoSuchMethodError error when running my Java program.  What's wrong and how do I fix it?
65166
It seems like my code works to check for null if I do  if ($tx)    or   if (isset($tx))   why would I do the second one when it's harder to write?
77080
This may sound repititve question. But the error incurs after following multiple links found like:  and .  The controller:  public with sharing class SFLoginCtrlr {     public static HTTPResponse getResp(String loginCred){         Map&lt;String, Object&gt; mapLoginCred = (Map&lt;String, Object&gt;)JSON.deserializeUnTyped(loginCred);         String username = ''+mapLoginCred.get('username');         String password = ''+mapLoginCred.get('password');         HttpRequest req = new HttpRequest();         req.setMethod('POST');            req.setTimeout(60000);         req.setEndpoint('https://www.salesforce.com/services/Soap/u/29.0');         req.setHeader('Content-Type', 'text/xml;charset=UTF-8');                 req.setHeader('SOAPAction', '""');         req.setBody('&lt;Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;Header/&gt;&lt;Body&gt;&lt;login xmlns="urn:partner.soap.sforce.com"&gt;&lt;username&gt;' +username+ '&lt;/username&gt;&lt;password&gt;' + password + '&lt;/password&gt;&lt;/login&gt;&lt;/Body&gt;&lt;/Envelope&gt;');                 HttpResponse res = new Http().send(req);         return res;     } }   The mock class:  @isTest global class ExampleCalloutMock implements HttpCalloutMock{   global HttpResponse respond(HTTPRequest req){     HttpResponse res = new HttpResponse();     res.setStatus('OK');     res.setStatusCode(200);     res.setBody('SUCCESS');     return res;   } }   The test class:  @isTest private class SFLoginCtrlrTest{     static testMethod void SFLoginCtrlrTestMethod(){         Test.startTest();          Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());          Map&lt;String, String&gt; logincred = new Map&lt;String, String&gt;();         logincred.put('username', 'dummy@user.com');         logincred.put('password', 'notapassword');          SFLoginCtrlr.getResp(JSON.serialize(logincred));          Test.stopTest();     } }   The error received while running test class:     Methods defined as TestMethod do not support Web service callouts   Not sure, where is the issue...
20439
I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)  Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).  I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below  Trigger code :   trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {       set&lt;string&gt; destinationids = new set&lt;string&gt;();      if(trigger.isInsert) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     } else if(trigger.isDelete) {         for(Supplier_product__c products : Trigger.old) {             destinationids.add(products.Destination__c);         }     }else if(trigger.isUnDelete) {         for(Supplier_product__c products : Trigger.new){             destinationids.add(products.Destination__c);         }      } else if(trigger.isUpdate) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     }      if(destinationids.size() &gt; 0){         Productcounter pc = new Productcounter();         pc.updateproductCount(destinationids);     }    }   Class code :  public class Productcounter {      public void updateproductcount(set&lt;string&gt; productIDs) {           if(productIDs == null){                return;         }          if(productIDs.size() == 0){             return;         }           list&lt;Supplier_Product__c&gt; ProductList = new list&lt;Supplier_Product__c&gt;();         ProductList = [Select ID,Destination__c                     From Supplier_Product__c                     Where Destination__c = :productIDs];          integer totalCount;         map&lt;string, integer&gt; DestinationIDToProductCountMap = new map&lt;string, integer&gt;();                for(Supplier_product__c ProductItem : ProductList){             if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){                 totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);             }else{                 totalCount = 0;             }             totalCount += 1;             DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);         }          list&lt;Destination__c&gt; DestinationUpdateList = new list&lt;Destination__c&gt;();         Destination__c DestinationTemp;         for(string ProductID : DestinationIDToProductCountMap.keySet()){             DestinationTemp.ID = ProductID;             DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);             DestinationUpdateList.add(DestinationTemp);         }         if(DestinationUpdateList.size() &gt; 0){             update DestinationUpdateList;         }           }           }
7576
I have a lookup to a custom object called Project on my Opportunity object. I am trying to write a trigger that updates an Active, Awarded, and Title on the Project object whenever the Active, Awarded, or Title field is updated on Opportunity based some on more logic that isn't in my code below. This is my first trigger and needing a little help due to a NullPointerException where I try to set Project__r.Active__c = true. Any thoughts?      trigger ProjectFieldsTrigger on Opportunity (before insert, before update) {       //List&lt;Opportunity&gt; opp = [SELECT Name, Active__c, Funded__c, Title__c, Project__r.Name, Project__r.Active__c, Project__r.Awarded__c      //  FROM Opportunity WHERE Id IN :Trigger.New];      for(Opportunity o: Trigger.New){          if(o.Project__c != null){              if(o.Active__c == 'Y'){                 o.Project__r.Active__c = true;             }      }  }
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.