I am trying to call methods of one class in another class but every time I am getting the same Exception in thread &quot;main&quot; java.lang.NullPointerException error... Please look into the code below and guide me.... Class: 1 public class CurrencyConverter {     double[] exchangeRates;          void setExchangeRates(double[] rates) { //set instance methods         exchangeRates = rates;     }          void updateExchangeRates(int arrayIndex, double newVal) {         exchangeRates[arrayIndex] = newVal;     }          double getExchnageRates(int arrayIndex) {         return exchangeRates[arrayIndex];     }          double computeTransferAmount(int arrayIndex, double amount) {         return amount * getExchnageRates(arrayIndex);     }          void printCurrencies() {         System.out.println(&quot;\nrupee: &quot; + exchangeRates[0]);         System.out.println(&quot;dirham: &quot; + exchangeRates[1]);         System.out.println(&quot;real: &quot; + exchangeRates[2]);         System.out.println(&quot;chilean_peso: &quot; + exchangeRates[3]);         System.out.println(&quot;mexican_peso: &quot; + exchangeRates[4]);         System.out.println(&quot;_yen: &quot; + exchangeRates[5]);         System.out.println(&quot;$australian: &quot; + exchangeRates[exchangeRates.length-1]);     }                  public static void main(String[] args){         CurrencyConverter cc = new CurrencyConverter();         double[] rates = {63.0, 3.0, 3.0, 595.5, 18.0, 107.0, 2.0};         cc.setExchangeRates(rates);     //calling setExchangeRates methods         rates = new double[]{65.0, 3.0, 3.0, 595.5, 18.0, 107.0, 2.0};         rates = new double[]{65.0, 3.0, 3.0, 595.5, 18.0, 107.0, 2.0};         cc.setExchangeRates(rates);         cc.printCurrencies();         cc.updateExchangeRates(0, 66.0);         cc.printCurrencies();         double amount = cc.computeTransferAmount(0, 1000);         System.out.println(&quot;\nTransferred Amount: &quot; + amount);     } }  Class 2 : public class MoneyTransferService {     CurrencyConverter cc = new CurrencyConverter();          double computeTransferAmount(int countryIndex, double amount) {         return cc.computeTransferAmount(countryIndex, amount);     }          double computeTransferFee(int countryIndex, double amount) {         double transferAmount =  computeTransferAmount(countryIndex,amount);         double transferFee = transferAmount * 0.02;         return transferFee;     }          public static void main(String[] args) {         MoneyTransferService transferService = new MoneyTransferService();                  double transferAmount = transferService.computeTransferAmount(0, 1000);         double transferFee = transferService.computeTransferFee(0, 1000);         System.out.println(&quot;transferAmount: &quot; + transferAmount);         System.out.println(&quot;transferFee: &quot; + transferFee);     } }
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?
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
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;             }      }  }
56910
The function of this apex code is when Account has no Contacts the first contact created become the primary contact and when there is existing primary contact it cannot assign a other primary contact on account. Please help to optimized my code to easy understand.Thanks for the help.  public class CreatePrimaryContactHandler {     public static void createPrimary(List&lt;Contact&gt; contactList)     {        Set&lt;Id&gt; accountId = new Set&lt;Id&gt;();         for(Contact c : contactList)         {             accountId.add(c.AccountId);         }         List&lt;Contact&gt; allContact = [SELECT Id, Account.Id, Primary_Contact__c FROM Contact WHERE (Account.Id IN : accountId)];         Map&lt;Id, List&lt;Contact&gt;&gt; acctContactMap = new Map&lt;Id, List&lt;Contact&gt;&gt;();             for(Id aId : accountId)             {              List&lt;Contact&gt; conList = new List&lt;Contact&gt;();                 for(Contact allcont : allContact)                 {                     if(allcont.AccountId == aId)                     {                     conList.add(allcont);                     }                 }                 acctContactMap.put(aId, conList);             }             for(Id accId : acctContactMap.keySet())             {                 Integer count = 0;                 for(Contact c : contactList)                 {                     if(c.AccountId == accId &amp;&amp; c.Primary_Contact__c)                     {                         count++;                     }                 }                 if(count &lt;= 1)                 {                     List&lt;Contact&gt; cList = acctContactMap.get(accId);                     Contact primary;                     Boolean isPrimary = false;                     for(Contact cont : cList)                     {                         if(cont.Primary_Contact__c)                         {                             isPrimary = true;                         }                     }                     for(Contact cont : contactList)                     {                         if(cont.AccountId == accId)                         {                             if(cont.Primary_Contact__c)                             {                                 if(primary != null)                                 {                                     primary.Primary_Contact__c = false;                                      isPrimary = false;                                 }                                 else if(isPrimary)                                 {                                 cont.addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                                 }                                     else                                     {                                         cont.Primary_Contact__c = true;                                         isPrimary = true;                                     }                             }                                    else if(!isPrimary)                                 {                                     cont.Primary_Contact__c = true;                                     isPrimary = true;                                     primary = cont;                                 }                         }                     }                 }                 else                 {                     contactList.get(0).addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                 }         }       } }   This is the Trigger  trigger CheckPrimaryContact on Contact (before insert,after update,before update){     if(trigger.IsInsert &amp;&amp; trigger.IsBefore){         CreatePrimaryContactHandler.createPrimary(trigger.new);     }     if(trigger.IsBefore &amp;&amp; trigger.IsUpdate){         CreatePrimaryContactHandler.createPrimary(trigger.new);     } }
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
116296
Anytime I have to handle dates/times in java it makes me sad   I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.  "Exception in thread "main" java.lang.Error: Unresolved compilation problem:  The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"  Eh WTF?  Here is the offending code.  for(int i = 0; i &lt; flights.size(); i++){      String[] details = flight[i].toString().split(":");      DateFormat formatter ;      formatter = new SimpleDateFormat("ddMMyyyy");     Date date = formatter.parse(details[1]);       PreparedStatement pstmt = conn.prepareStatement(insertsql);     pstmt.setString(1, details[0]);     pstmt.setDate(2, date);     pstmt.setString(3, details[2] + "00");     pstmt.setString(4, details[3]);     pstmt.setString(5, details[4]);     pstmt.setString(6, details[5]);     pstmt.setString(7, details[6]);     pstmt.setString(8, details[7]);     pstmt.setString(9, details[8]);     pstmt.executeUpdate();  }
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
92088
public class WrapperTest {      public static void main(String[] args) {          Integer i = 100;         Integer j = 100;          if(i == j)             System.out.println("same");         else             System.out.println("not same");     }     }   The above code gives the output of same when run, however if we change the value of i and j to 1000 the output changes to not same. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.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
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
105546
When modelling classes, what is the preferred way of initializing:   Constructors, or Factory Methods   And what would be the considerations for using either of them?  In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)  Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.  In contrast to this I can have a static factory method on those classes which will return null if the record is not found.  Which approach is better in this case, constructor or factory method?
119160
This Trigger is on lead (Before Insert, Before Update) and it errors (System.NullPointerException: Attempt to de-reference a null object). I'm getting this error when i'm posting "Web to Lead". However i do have the right ORG iD and Record type id included on the xml file:   &lt;input type=hidden name="oid" value="xxxxxxxxxxxxx"&gt; &lt;input type=hidden name="recordType" id="recordType" value="zzzzzzzzzzzzzzzzzz"&gt;    trigger IAAILeadTrigger on Lead (before insert, before update){ //BEGIN: S-444340 T-561808 - Process only IAA Remarketing Recordtype data     Map&lt;ID,Schema.RecordTypeInfo&gt; rt_Map = Lead.sObjectType.getDescribe().getRecordTypeInfosById();      //Looks up the branches based on the Lead PostalCode     if(trigger.isBefore){          for(Lead ld : trigger.new){                      if (rt_map.get(ld.recordTypeID).getName().containsIgnoreCase('IAA Remarketing') )                if( trigger.isInsert ||                    (trigger.isUpdate &amp;&amp; ld.Branch__c == null) ||                   (trigger.isUpdate &amp;&amp; ld.PostalCode != trigger.oldMap.get(ld.id).PostalCode)               ){                   leads.add(ld);               }           }           }                 //Only check the leads that are in the lead list and NOT the full trigger.new list         if(!leads.isEmpty()){             LeadController.GetLeadBranches(leads);           }     }  }
24554
I have a lookup relationship.  If I just do the following query it works fine:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; system.debug('c:' + c);   However with the following I get an error:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; String c2 = (String) r.getSobject('field__r').get('fieldchild__c');   Error message:     FATAL_ERROR System.NullPointerException: Attempt to de-reference a   null object
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
101466
I have the following situation I think would be best to show in sample program code.  I have a Java class that extends JPanel.  In this class are two objects which are two more JPanels.  In one of the JPanel objects is a JTable object.  I added a listener to this JTable that detects a double click.  When it detects a double click, I want to fire a method in the top class.  How do I reference this method in Java?  public class TopPanel extends JPanel {    JPanel OnePanel;   JPanel TwoPanel;    public void MethodToFire;  }  public class OnePanel extends JPanel {    JTable TheTable;  }  public class TheTable extends JTable {    public TheTable {     this.addMouseListener(new MouseAdapter(){       public void mouseClicked(MouseEvent e){           if (e.getClickCount() == 2){ SYNTAX CALLING THE METHOD IN TopPanel  }       }     } );   } }
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
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?