public static ArrayList&lt;Integer&gt; getStudentClasses(Student student, ArrayList&lt;Integer&gt;[] classesXstudents) {       ArrayList&lt;Integer&gt; classes = new ArrayList&lt;Integer&gt;();       for (int i = 0; i &lt; classesXstudents.length; i++) {         for (int j = 0; j &lt; classesXstudents[i].size(); j++) {           if (classesXstudents[i].get(j) == student.getID()) {             classes.add(i+1);           }         }       }       return classes;   }   throws NullPointerException at the line     for (int j = 0; j &lt; classesXstudents[i].size(); j++) {   which I'm assuming means classesXstudents[i].size() is null at some point. classesXstudents is an array of ArrayList objects. How should I debug this case?
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?
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
61737
I would like to use Class.newInstance() but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
118759
Question  I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?  If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.  Code  // Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i &lt; frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } }
6832
How does one go about and try to find all subclasses of a given class (or all implementors of a given interface) in Java? As of now, I have a method to do this, but I find it quite inefficient (to say the least). The method is:    Get a list of all class names that exist on the class path Load each class and test to see if it is a subclass or implementor of the desired class or interface   In Eclipse, there is a nice feature called the Type Hierarchy that manages to show this quite efficiently. How does one go about and do it programmatically?
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
50228
I have a Linq to objects statement   var confirm = from l in lines.Lines   where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)   select l;   The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()  If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?  EDIT When I said I know for a fact that there are no null objects it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'  LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool
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
30943
I think there must be something subtle going on here that I don't know about. Consider the following:  public class Foo&lt;T&gt; {   private T[] a = (T[]) new Object[5];    public Foo() {     // Add some elements to a   }    public T[] getA() {     return a;   } }   Suppose that your main method contains the following:  Foo&lt;Double&gt; f = new Foo&lt;Double&gt;(); Double[] d = f.getA();   You will get a CastClassException with the message java.lang.Object cannot be cast to java.lang.Double.  Can anyone tell me why? My understanding of ClassCastException is that it is thrown when you try to cast an object to a type that cannot be casted. That is, to a subclass of which it is not an instance (to quote the documentation). e.g.:  Object o = new Double(3.); Double d = (Double) o; // Working cast String s = (String) o; // ClassCastException   And it seems I can do this. If a was just a T instead of an array T[], we can get a and cast it without a problem. Why do arrays break this?  Thanks.
80627
I have a string variable that represents the name of a custom class. Example:   string s = "Customer";   I will need to create an arraylist of customers. So, the syntax needed is:  List&lt;Customer&gt; cust = new ..    How do I convert the string s to be able to create this arraylist on runtime?
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?
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
99846
I need to determine if a Class object representing an interface extends another interface, ie:   package a.b.c.d;     public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{     }   according to  Class.getSuperClass() will return null for an Interface.       If this Class represents either the   Object class, an interface, a   primitive type, or void, then null is   returned.   Therefore the following won't work.  Class interface = Class.ForName("a.b.c.d.IMyInterface") Class extendedInterface = interface.getSuperClass(); if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){     //do whatever here }   any ideas?
4455
I have an array that is initialized like:  Element[] array = {new Element(1), new Element(2), new Element(3)};   I would like to convert this array into an object of the  class.  ArrayList&lt;Element&gt; arraylist = ???;
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...