I am trying to create a custom class Student, which contains 2 fields, Name and Marks. I read on the internet that I need Getters &amp; Setters to do so. So, I wrote the following code but it is giving me a NullPointerException. import java.util.*;  class Student {     public String name;     public int marks;     public int getMarks()     {         return this.marks;     }     public void setMarks(int marks)     {         this.marks = marks;     }     public String getName()     {         return this.name;     }     public void setName(String name)     {         this.name = name;     } } public class getterSetter {     public static void main(String[] ab)     {         Scanner s = new Scanner(System.in);         int n = s.nextInt();         int x;         Student[] student = new Student[n];         String[] inputs = new String[n];         s.nextLine();         for(int i = 0; i &lt; n; i++)         {             String xx = s.nextLine();             inputs[i] = xx;         }         for(int i = 0; i &lt; n; i++)         {             String[] words = inputs[i].split(&quot;\\s+&quot;);             student[i].setName(words[0]);             student[i].setMarks(Integer.parseInt(words[1]) + Integer.parseInt(words[2]) + Integer.parseInt(words[3]));         }         for(int i = 0; i &lt; n; i++)         {             System.out.println(student[i].getName());             System.out.println(student[i].getMarks());         }     } }  The console screen is : java getterSetter 3 abc 10 10 10 def 10 10 10 ghi 10 10 10 Exception in thread &quot;main&quot; java.lang.NullPointerException         at getterSetter.main(getterSetter.java:58)
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?
120271
With the new approach of having the get/set within the attribut of the class like that :  public string FirstName {         get; set;     }   Why simply not simply put the attribute FirstName public without accessor?
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;             }      }  }
121551
I have a function called:  void initializeJSP(string Experiment)   And in my MyJSP.h file I have:  2: void initializeJSP(string Experiment);   And when I compile I get this error:     MyJSP.h:2 error: variable or field initializeJSP declared void   Where is the problem?
106099
I'm working on developing a test class for my apex. I'm stuck with creation of Contract records contractnumber field. In test class, I use the following code:     Contract c = new Contract();     c.Name = 'Test Contract';     c.AccountId = acc.Id;     c.Status = 'Draft';     insert c;     //I'm creating a draft contract and then activating it.     c.status  = 'Activated';     update c;     system.debug('contract debug:'+c.contractnumber);  Contractnumber field on object is Autonumber, but in the log I get null for contractnumber. I see the whole contract record is created with null ContractNumber. What am I doing wrong?
108487
I have the code below (I've included what I believe are all relevant sections):  private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; }   When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
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
20599
I am receiving apex errors with the following code:   public with sharing class AddExistingSpecsExt {      public Specifications__c loadedSpec { get; private set; }  public AddExistingSpecsExt() {     String specId = ApexPages.currentPage().getParameters().get('id');     if (String.isBlank(specId)) return;      List&lt;Specifications__c&gt; candidates = [         SELECT Id, Name, Product__c FROM Specifications__c WHERE Id = :specId LIMIT 1     ];     if (!candidates.isEmpty()) loadedSpec = candidates[0]; }     public PageReference associate () {          Specifications__c candidates = new Specifications__c ( Id = Specifications__c.Product__c, Name = Specifications__c.Id);          try {             Database.update(candidates);         } catch (Exception error) {             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while associating.' + error.getMessage()));         }          PageReference page = new PageReference('/' + candidates);          return page.setRedirect(true);     }      public PageReference cancel () {         PageReference page = new PageReference('/' + Null);         return page.setRedirect(true);             }  }   Attempting to add records to a related list through a custom button and small vf page.   The Error is Line 16      Invalid initial expression type for field Specifications__c.Id, expecting: Id   Any help?
5648
Declared a string and assigned SOQL value as shown below. While running I am getting an error.   String country = 'United States'; String accountQuery = 'SELECT Id,BillingPostalCode,County_Name__c '+      'FROM Account WHERE zipCodeLen__c =9 AND AND BillingCountry = '+ Country;   System.QueryException: unexpected token: 'AND'  System.QueryException: expecting a colon, found 'United'
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
65745
I have created an Apex InterfaceFactory that the user can use to get an instance of a specified implementation of an interface. For this I use the System.Type class. The actual name of the class can be set in a custom setting. I wanted to be able to pass some parameters to the constructor of the dynamically instantiated class. In short; this is the code I'm talking about:  public static MyInterface GetMyInterfaceImplementationByClassName(String settingName){     String implementationClassName;     Type t;     MyInterface implementation = null;      //get the actual class name from the custom setting     Interface_Implementations__c settings = Interface_Implementations__c.getInstance(settingName);      //just make sure there actually is a className found     if (settings != null &amp;&amp; settings.Class__c != null) {         implementationClassName = settings.Class__c;         //get the type object for the class name retrieved from the custom setting         t = Type.forName(implementationClassName);         //this line is where my question comes in; how can I pass parameters here         implementation = (MyInterface)t.newInstance();     }      return implementation; }
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
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
109679
I have the following code:      public class OrderRequestCreationEmails {     public static void sendMail()     {          Messaging.reserveSingleEmailCapacity(2);         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();         String[] toAddresses = new String[] {'dgriff@varonis.com'};           mail.setToAddresses(toAddresses);          mail.setReplyTo('dgriff@varonis.com');          mail.setSenderDisplayName('Mail Test');          mail.setSubject('Success! Mail Sent');          mail.setBccSender(false);         mail.setPlainTextBody('BODY');          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     } }   I tried to call this function from a test as such: (I know its not an actual test, its just to see if I receive a mail).  @isTest private class CreationEmailsTest {     @isTest private static void sendMailTest() {         OrderRequestCreationEmails.sendMail();     } }   And I haven't received the mail, no idea why?  It's an example I took from the salesforce developer guide. couldn't find any answers online...  FYI - deliverability in the sandbox is turned on, and test deliverability works
58964
I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable.  I tried to use the property() function with these, but it results in an error.  I was able to reproduce the error with the following in the interpreter: class Foo(object):     _var = 5     @classmethod     def getvar(cls):         return cls._var     @classmethod     def setvar(cls, value):         cls._var = value     var = property(getvar, setvar)  I can demonstrate the class methods, but they don't work as properties: &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.getvar() 5 &gt;&gt;&gt; f.setvar(4) &gt;&gt;&gt; f.getvar() 4 &gt;&gt;&gt; f.var Traceback (most recent call last):   File &quot;&lt;stdin&gt;&quot;, line 1, in ? TypeError: 'classmethod' object is not callable &gt;&gt;&gt; f.var=5 Traceback (most recent call last):   File &quot;&lt;stdin&gt;&quot;, line 1, in ? TypeError: 'classmethod' object is not callable  Is it possible to use the property() function with @classmethod decorated functions?
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();  }