So I am working on a lab dealing with cards and decks. The code I have written in the deck.java is supposed to initialize a deck. However, I get a nullPointException and I don't know why. Here is a snippet of the code (I get the error on the line where it says "cards.add(thisCard);":  import java.util.List; import java.util.ArrayList; import java.lang.Math;  /**  * The Deck class represents a shuffled deck of cards.  * It provides several operations including  *      initialize, shuffle, deal, and check if empty.  */ public class Deck {      /**      * cards contains all the cards in the deck.      */     private List&lt;Card&gt; cards;      /**      * size is the number of not-yet-dealt cards.      * Cards are dealt from the top (highest index) down.      * The next card to be dealt is at size - 1.      */     private int size;       /**      * Creates a new &lt;code&gt;Deck&lt;/code&gt; instance.&lt;BR&gt;      * It pairs each element of ranks with each element of suits,      * and produces one of the corresponding card.      * @param ranks is an array containing all of the card ranks.      * @param suits is an array containing all of the card suits.      * @param values is an array containing all of the card point values.      */     public Deck(String[] ranks, String[] suits, int[] values) {         for (int i = 0; i &lt; ranks.length; i++){                     Card thisCard = new Card(ranks[i], suits[i], values[i]);                     cards.add(thisCard);                 }                 size = cards.size();                 shuffle();     } }
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?
44999
I am trying to write a test class for the Apex Class with try - catch block and this is my first time coding test classes. The Apex Class is like below which has trycatch   public class updateCaseRecord {          @AuraEnabled     public static void updateCheck(String caseId){         String msg = '';         try         {         List&lt;Case&gt; records = [select id,Status from Case WHERE Id = :caseId];         for (Case record : records)         {             record.Status = 'Closed';         }         update records;          }         catch(DmlException e)              {                for (Integer i = 0; i &lt; e.getNumDml(); i++) {                     msg =+ e.getDmlMessage(i) +  '\n' ;                     System.debug('getDmlFieldNames=' + e.getDmlFieldNames(i));                    System.debug('getDmlMessage=' + e.getDmlMessage(i));                   }                 throw new AuraHandledException(msg);             }             catch(Exception e)             {             throw new AuraHandledException(e.getMessage());             }             finally { }           }}   And I wrote my test class like   @IsTest public class updateCaseRecordTest { @IsTest static void testIsUpdateCheck() {      ID parentRecType = '012U0000000PqA9IAK';     ID csRecType     = '012U0000000QGv4IAG';       Account pa = new Account(Name='Test Parent Account', recordTypeId=parentRecType);     insert pa;      Account testAccount = new Account(Name='test', Industry='Biotech',Territory__c='EUR',BillingCity='Test',BillingCountry='Germany',ParentId=pa.id);     insert testAccount;       Contact c = new Contact(LastName='Test',LeadSource='Customer Service',AccountId=testAccount.Id);     insert c;      Case newCase1 = new Case();     newCase1.Subject = 'testStatusClosed';     newCase1.Status = 'New';     newCase1.Category__c = 'Inquiry';     newCase1.Sub_Category__c = 'Other';     newCase1.AccountId = testAccount.Id;     newCase1.ContactId = c.id;     newCase1.recordTypeId=csRecType;     insert newCase1;       Test.startTest(); try     {     updateCaseRecord.updateCheck(newCase1.Id);     List&lt;Case&gt; lCases = [SELECT Id,Status,OwnerId FROM Case WHERE Id =: newCase1.Id];     System.assertEquals('Closed', lCases[0].Status);      System.assertEquals(UserInfo.getUserId(), lCases[0].OwnerId);     }      catch(DMLException e) {         System.assertEquals(e.getMessage(), e.getMessage());     }      Test.stopTest();    }}   I thought I captured the try catch but when I run the test class it has only 57% code coverage and shows like below    Following one of the answers here
29674
Why do we need an init() method in servlet? Can't we use the constructor to initialization?
111890
I am a complete JSP beginner.  I am trying to use a java.util.List in a JSP page.  What do I need to do to use classes other than ones in java.lang?
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
31102
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code.   var urls = new List&lt;string&gt;(); urls.Add("http://www.google.com");  foreach (string url in urls) {     // Get all links from the url     List&lt;string&gt; newUrls = GetLinks(url);      urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping }   How can I rewrite this in a better way? I'm guessing a recursive solution?
4667
Getting error with this code but I can't figure it out  trigger LeadConvert on Lead (after insert) {     list leadsToConvert = new list();      Database.LeadConvert lc;     string convertedStatus = '';     list convertStatusList = new list();     convertStatusList = [Select Id, MasterLabel                          from LeadStatus where IsConverted=true limit 1];     if(convertStatusList.size() &gt; 0){         convertedStatus = convertStatusList[0].MasterLabel;         }     else{              convertedStatus = 'Closed - Converted';          }      for(Lead l : trigger.New){         if(l.AutoConvert__c == true){             lc = new database.LeadConvert();             lc.setLeadId(l.ID);             lc.setDoNotCreateOpportunity(true);              lc.setConvertedStatus(convertedStatus);             leadsToConvert.add(lc);         }     }      list lcrList = new list();     lcrList = Database.convertLead(leadsToConvert); }
45967
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.  #include &lt;iostream&gt; #include &lt;vector&gt;  using namespace std;  int main() {     vector&lt;char&gt; deck;     char suit[] = {'h','d','c','s'};     char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};     for (int j=0; j&lt;13; j++) {         for (int i=0; i&lt;4; i++) {             deck.push_back(card[j] suit[i]);         }            }      return 0; }   I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
91805
Short prestory. Typical problem: you have a lot of small string and you want to concatenate them all in one big string. The code like for(Integer i = 0; i &lt; smallStringsSize; i++){     bigString += smallStrings[i]; }  will solve this problem, but it has to produce a lot of unnecessary string objects that consume your heap. That is why Java has classes like StringBuilder and StringBuffer that allow you to solve this problem wihtout consuming too many memory. Thus, I decided to try to do my own StringBuilder in apex. String class has two methods that looked suitable for it:   and  . Here is the code that i used to test these methods against &quot;+=&quot; concatenantion (ready to execute in anonymous): List&lt;String&gt; chars = new List&lt;String&gt;(); List&lt;Integer&gt; charsCode = new List&lt;Integer&gt;(); Integer size = 10000; String chartToAdd = 'Ω'; for(Integer i = 0; i &lt; size; i++){     chars.add(chartToAdd);     charsCode.add(String.valueOf(chartToAdd).charAt(0)); } String joinS = '', forS = '', fromS = ''; Integer initialHeapSize = Limits.getHeapSize(); Integer initialCPUtime = Limits.getCpuTime(); System.debug('initialHeapSize ' + initialHeapSize); System.debug('initialCPUtime ' + initialCPUtime); joinS = String.join(chars, ''); Integer joinHeapSize = Limits.getHeapSize() - initialHeapSize; Integer joinCPUtime = Limits.getCpuTime() - initialCPUtime; System.debug('-------- String.join ---------'); System.debug('joinHeapSize ' + joinHeapSize); System.debug('joinCPUtime ' + joinCPUtime); for(Integer i = 0; i &lt; size; i++){     forS += chars[i]; } Integer forHeapSize = Limits.getHeapSize() - joinHeapSize - initialHeapSize; Integer forCPUtime = Limits.getCpuTime() - joinCPUtime - initialCPUtime; System.debug('-------- for each += ---------'); System.debug('forHeapSize ' + forHeapSize); System.debug('forCPUtime ' + forCPUtime); fromS = String.fromCharArray(charsCode); Integer fromHeapSize = Limits.getHeapSize() - forHeapSize - joinHeapSize - initialHeapSize; Integer fromCPUtime = Limits.getCpuTime() - forCPUtime - joinCPUtime - initialCPUtime; System.debug('-------- String.fromCharArray ---------'); System.debug('fromHeapSize ' + fromHeapSize); System.debug('fromCPUtime ' + fromCPUtime); System.debug(''); System.debug('-------- strings ----------'); System.debug('joins ' + joins); System.debug('fors ' + fors); System.debug('fromS ' + fromS);  The result of this code execution:  initialHeapSize 161166 initialCPUtime 242 -------- String.join --------- joinHeapSize 10016 joinCPUtime 17 -------- for each += --------- forHeapSize 10024 forCPUtime 48 -------- String.fromCharArray --------- fromHeapSize 10016 fromCPUtime 5  As you can see, the heap size for each approach is so close to 10 kilobytes, what is a size of the string of 10 000 characters (size) if each character takes only one byte. In case of creating 10 000 additional string objects, the heap size would be a bit more than 50 megabytes (10 000 * (1 + 10 000)/2). Taking into consideration the above,  Does not the '+=' concatenation create any additional string objects that devour your heap? Did not I miss anything? I am so amazed.  As you see, I use Omega 'Ω' as a chartToAdd. It has  the high-surrogate code point equals to 937, that needs at least 2 bytes to be encoded. How can 10 000 Omegas consume only 10 000 bytes of the heap size?  What weightful reasons Salesforce has that they do not to add the character data type? Any ideas?
57448
So, I've been spending considerable more time on SO recently than I normally have, and one thing that I've noticed is quite a few people saying stuff like "There's a Null Pointer Error in this block of code, please help me fix it", with a huge amount of code posted, and no real clue as to where the NPE is. So my question is, what can we do to accomplish 2 goals?   Help the person asking the question become a better programmer. Help them to solve their problems.
1064
I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?  Calling Code  c.firstName = "a";   Property Code    public String firstName; {     get     {         return firstName;     }     set     {         firstName = value;     } }
109761
I have getting the below JSON on using JSON.serialize  [ {   "lname" : "Singh",   "hcpZipCode" : null,   "hcpState" : null,   "hcpEmail" : "test@test.com",   "hcpCity" : null,   "hcpAddLine1" : null,   "fname" : "Abhey",   "countryCode" : "AUS" } ]   I don't know why this '[' is coming at the begining.I don't need this '[' at the begining due to which I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object  code     public PageReference step2() {         string JSONstr='';        List&lt;HCPRequest&gt; conWrapList = new List&lt;HCPRequest&gt;();        HCPRequest tempcontactWrapper = new HCPRequest();        tempcontactWrapper.fname='Abhey';        tempcontactWrapper.lname='Singh';        tempcontactWrapper.countryCode='AUS';        tempcontactWrapper.hcpEmail=contact.Email;         conWrapList.add(tempcontactWrapper);          JSONstr = JSON.serializePretty(conWrapList);         System.debug('\n******'+JSONstr +'\n******');          String clientId = 'xy';         String clientSecret = 'x';          //We can also store our username password in custom setting.         String username='x';//salesforce username          String password='x';//password+securitytoken         // Generating the Access Token         HttpRequest req = new HttpRequest();         req.setMethod('POST');         req.setEndpoint('https://test.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit         req.setBody('grant_type=password&amp;client_id='+clientId+'&amp;client_secret='+clientSecret+'&amp;username='+username+'&amp;password='+password);          Http http = new Http();         HTTPResponse res = http.send(req);         String str = res.getBody();         wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);         accessToken = wrapObj.access_token;         instanceUrl = wrapObj.instance_url;          HttpRequest req1 = new HttpRequest();         string response='';         req1.setMethod('POST');         //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');         string EndPt = 'y';         string email='test@test.com';         req1.setEndpoint(EndPt);         req1.setHeader('Authorization', 'OAuth '+wrapObj.access_token);          req1.setHeader('Content-Type', 'application/json');          //req1.setBody('{"request":{"lname" : "Singh","hcpZipCode" : null,"hcpState" : null,"hcpEmail" : "test@test.com","hcpCity" : null,"hcpAddLine1" : null,"fname" : "Abhey","countryCode" : "AUS"}}');          req1.setBody('{"request":'+JSON.Serialize(conWrapList)+'}');          //req.setBody('{"request": {"countryCode": "AUS","hcpEmail" : ""+email}}');          //req.setTimeout(60000);             //req.setHeader('Content-Length', '0');         Http http1 = new Http();         HTTPResponse res1 = http1.send(req1);          System.debug('***Response***** ' + res1.getBody());         if(res1.getBody()!=null)         {             response=res1.getBody();             HCPResponse saj=(HCPResponse)JSON.deserialize(response,HCPResponse.class);           System.debug('***Response came full***** ' + saj);            System.debug('***Response came***** ' + saj.accList);             for(HCPResponseDetail s :saj.accList)            {            System.debug('***Response email***** ' + s.hcpEmail);            System.debug('***Response add2***** ' + s.hcpAddrLine2);            contact.Address1_Line2__c=s.hcpAddrLine2;            }           //return response;         //string methodcall=methodGet(JSONstr);               return Page.opptyStep2CustomReg;         }
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.
34071
Consider this:  public class TestClass {      private String a;     private String b;      public TestClass()     {     a = "initialized";     }      public void doSomething()     {     String c;          a.notify(); // This is fine     b.notify(); // This is fine - but will end in an exception     c.notify(); // "Local variable c may not have been initialised"     }  }   I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?  Edit: making the members private was my initial intention, and the question still stands...
101821
while making a call from php i am getting the error      Attempt to de-reference a null object Class.Demo.Insert:   What is problem in my webservice?  global class Ctest{     global class RequestClass{         webservice String accName;     }      webservice static void   cInsert(RequestClass req){         Account a1 = new Account();         a1.Name = req.accName;         insert a1;     } }   And Our Php Code Is  require_once('salesforceAPI/soapclient/SforceEnterpriseClient.php'); require_once('salesforceAPI/soapclient/SforceHeaderOptions.php');  $sfdc = new SforceEnterpriseClient(); $SoapClient = $sfdc-&gt;createConnection('enterprise.wsdl.xml');  $loginResult = false;  $loginResult = $sfdc-&gt;login(USER, PASSWORD . SECURITY_KEY);  $parsedURL = parse_url($sfdc-&gt;getLocation()); define("_SFDC_SERVER_", substr($parsedURL['host'], 0, strpos($parsedURL['host'], '.'))); define("_WS_NAME_", 'salesforceAPI/Ctest'); define("_WS_WSDL_", _WS_NAME_ . '.xml'); define("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_); define("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);  $client = new SoapClient(_WS_WSDL_); $sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" =&gt; $sfdc-&gt;getSessionId())); $client-&gt;__setSoapHeaders(array($sforce_header));  $method = $client-&gt;__getFunctions();  $wsParams = array('accName' =&gt; 'XXXXXXX');  $client-&gt;cInsert($wsParams)
11494
App version 1.0.27  If you the notification pane and click on the loading icon while it's spinning, the app will cause the app to crash.  03-26 22:51:08.331 E/AndroidRuntime(5927): FATAL EXCEPTION: main 03-26 22:51:08.331 E/AndroidRuntime(5927): java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.util.ArrayList.get(ArrayList.java:310) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.stackexchange.marvin.ui.BaseActivity$3.onItemClick(BaseActivity.java:266) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView.performItemClick(AbsListView.java:1100) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$1.run(AbsListView.java:3463) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.handleCallback(Handler.java:730) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.dispatchMessage(Handler.java:92) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Looper.loop(Looper.java:137) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.app.ActivityThread.main(ActivityThread.java:5103) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invokeNative(Native Method) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invoke(Method.java:525) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-26 22:51:08.331 E/AndroidRuntime(5927): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126) 03-26 22:51:08.331 E/AndroidRuntime(5927): at dalvik.system.NativeStart.main(Native Method)   (Think I should calm down on finding bugs for a little while? :P)
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;             }      }  }