So I am making a program that takes in polynomial functions and does different things with it.   Right now, I am trying to make a method that checks the Polynomial that is input, which is stored as an ArrayList, and condensing it so everything with the same exponent gets added together.  I keep receiving a NullPointer Exception whenever I run the program, and I am not sure why I am receiving this. I know what the error means, but I have looked through my code and cannot see why the Polynomial is being seen as null.  This is my constructor  public ArrayList&lt;PolyTerm&gt; terms;  public Poly(ArrayList&lt;PolyTerm&gt; terms) {     sort(terms);     condenseExponents();     this.terms = terms; }   And in my main class I have my Poly objects created like this:  PolyTerm poly1 = new PolyTerm(4, 3); PolyTerm poly2 = new PolyTerm(-3, 1); PolyTerm poly3 = new PolyTerm(15, 3); PolyTerm poly4 = new PolyTerm(7, 2);  PolyTerm poly5 = new PolyTerm(14, 12); PolyTerm poly6 = new PolyTerm(2, 0); PolyTerm poly7 = new PolyTerm(19, 2);  ArrayList&lt;PolyTerm&gt; terms = new ArrayList&lt;&gt;();     terms.add(poly1);     terms.add(poly2);     terms.add(poly3);     terms.add(poly4);  ArrayList&lt;PolyTerm&gt; terms1 = new ArrayList&lt;&gt;();     terms1.add(poly5);     terms1.add(poly6);     terms1.add(poly7);    Poly test = new Poly(terms); Poly test2 = new Poly(terms1);   Where the first thing being taken in by the PolyTerm is the coefficient, and the second thing being taken in is the exponent.  So back to the Poly class.  In my constructor, I call condenseExponents() which is meant to condense to ArrayList and combine the coefficients of all similar exponents. Here is that method  private void condenseExponents() {     for(int i = 0; i &lt; terms.size() - 1; i++)     {         for(int j = i + 1; j &lt; terms.size(); j++)         {             if(terms.get(i).getExponent() == terms.get(j).getExponent())                 terms.set(i, new PolyTerm(terms.get(i).getCoef() + terms.get(j).getCoef(), terms.get(i).getExponent()));                 terms.remove(j);         }     } }   The NullPointer Exception keeps being thrown on the first line of the for loop in that method.  Does anybody know why?
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?
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.
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?
18943
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:  import org.apache.commons.lang.builder.EqualsBuilder;  public class Foo {     public class Bar {         private Bar() {}          public Foo getMyFoo() {             return Foo.this         }          private int myInt = 0;          public boolean equals(Object o) {             if (o == null || o.getClass() != getClass) return false;              Bar other = (Bar) o;             return new EqualsBuilder()                 .append(getMyFoo(), other.getMyFoo())                 .append(myInt, other.myInt)                 .isEquals();         }     }      public Bar createBar(...) {         //sensible implementation     }      public Bar createOtherBar(...) {         //another implementation     }      public boolean equals(Object o) {         //sensible equals implementation     } }   Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?
97382
If $p(x)$ is a polynomial of degree $n$ and $p(k) = k/(k + 1)$ for $k = 0, 1, 2, \ldots,n$, find $p(n + 1)$.  I'm not looking for a solution, I just want help starting it.    *Edit: Typo in original post,
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
57401
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()      ListNode:    public class ListNode{   public String data;   public ListNode next; }   Right now my reverse function just calls a helper function that takes an argument to allow recursion.  public AddressList reverse(){   return new AddressList(this.reverse(this.head)); }   With my helper function having the signature of private ListNode reverse(ListNode current).  At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.  Edit: Nevermind, I figured it out in the meantime.  private AddressList reverse(ListNode current, AddressList reversedList){   if(current == null)        return reversedList;   reversedList.addToFront(current.getData());   return this.reverse(current.getNext(), reversedList); }   While I'm here, does anyone see any problems with this route?
7653
public class doublePrecision {     public static void main(String[] args) {          double total = 0;         total += 5.6;         total += 5.8;         System.out.println(total);     } }   The above code prints:  11.399999999999   How would I get this to just print (or be able to use it as) 11.4?
109534
I am trying to write a test class.  My Apex class has the following constructor:  public NController(ApexPages.StandardController controller) {      cas =  (Case) controller.getRecord();     csId = cas.Id;     owner = cas.OwnerId;      N_SSettings__c nhdsms = N_SSettings__c.getValues('Int');     rate=nhdsms.Rate_Code__c;     accId=nhdsms.Acc_Id__c;  }   Here N_SSettings__c is a custom settings which has two fields Rate_Code__c and Acc_Id__c. It has a record called 'Int' with both Rate_Code__c and Acc_Id__c field values populated.  I am using the following test class method:  @isTest public class NHSsendSMSController_Test {     public static testMethod void NHSsendSMSControllerTest()     {         Case caseObj = new Case();         insert caseObj;         ApexPages.StandardController sc = new ApexPages.standardController(caseObj);         NController nControllerObj = new NController(sc);         nControllerObj.methodName();     } }   When I run the test method, it is throwing a null pointer exception on the line :  rate = nhdsms.Rate_Code__c;   The custom setting is definitely present with the required values of both the fields of Int.
120449
I am getting this error with the code below. I've looked into the other cases on here. In my case I am referring to a relationship name (__r) which I am assuming is pulling correctly. It's a field which is a lookup to User :   Agreement_CSH_to_be_completed_by__r  Here is the code which is giving me problems :   public void doManagedClients() {         addMsg('Starting processing of Managed Clients.');         Integer startSize = CSH_Data.size();          String SOQL = 'Select Id, OwnerId, Owner.UserName, Account__c, RecordTypeId, Name, Agreement_Client_Status_History__c ' +             'From Contract_Terms__c Where ' +             '   ( recordtypeid = \''+ ((String)A_N_Rectype).substring(0,15) + '\' ) and ' +                '   Agreement_Client_Status_History__c = \'Monthly\' ' +             'order by createddate desc nulls first' ; system.debug('#####333#### ');               addMsg(DEBUG,'Managed Query is: ' + SOQL + '\n');         for (Contract_Terms__c a: Database.Query(SOQL)) {             if (!a.Agreement_CSH_to_be_completed_by__r.isActive) {                 totalInactiveOwners++;                  addMsg('Account: ' + a.Name +  ', has an inactive owner.  Username: ' + a.Agreement_CSH_to_be_completed_by__r.isActive + '.');             } else {                             totalManagedCSHs++;                 addMsg(DEBUG,'Creating a Managed CSH for Account: ' + a);                 CSH_Data.add(new CSH_and_Share_Pair(a, createClientStatusHistory(a)));                 needflush(false);                 if (error) break;             }         }         needflush(true);         addMsg('End of Managed Clients.');           }   Is it just because I don't have a.Agreement_CSH_to_be_completed_by__r included in the SOQL ? I thought I got different errors for that, so I'm a little confused.  Thank you for your help.
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!)
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
12184
I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.