when I run it display this error  Exception in thread "main" java.lang.NullPointerException at Abstract2.main(Abstract2.java:70) pleae tell me how to resolve it  my code is given below  import java.util.*; abstract class plan { public double rate,bill; public abstract void getrate(); public void cbill(int unit) { double bill=rate*unit; System.out.println("bill is="+bill); } } class domestic extends plan { public void getrate() { rate=2.5; } } class commercial extends plan { public void getrate() { rate=5.5; } } class industrial extends plan { public void getrate() { rate=7.5; } } class bill { public plan getplan(String plantype) { if(plantype==("domestic")) { return new domestic(); } if(plantype==("commercial")) { return new commercial(); } if (plantype==("industrial")) { return new industrial(); } return null; } } class Abstract2 { public static void main(String aa[]) { plan p;//instance of class plan String plantype; int unit; double rate; bill b=new bill(); Scanner sc=new Scanner(System.in); System.out.println("enter the plan type="); System.out.println("     domestic"); System.out.println("     commercial"); System.out.println("     industrial"); plantype=sc.next(); System.out.println("enter the units"); unit=sc.nextInt(); p=b.getplan(plantype); p.getrate();//line 70 p.cbill(unit); }  }   please tell me how to resolve it
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?
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); }
5085
I´m having problems with url parameters (req.requestURI) in my test class.  This is my code.  REST CLASS:  @RestResource(urlMapping='/Accounts/*') global class StoreController {       @HttpGet     global static String getAccounts() {           integer pageNumber=integer.valueof(RestContext.request.params.get('page'));         string  ptime=RestContext.request.params.get('time');         string  hash=RestContext.request.params.get('hash');      }   REST TEST CLASS:  @isTest private class StoreControllerTest {      static testMethod void testGet() {       //do request     RestRequest req = new RestRequest();      RestResponse res = new RestResponse();      req.requestURI = 'https://dev-my-my.cs14.force.com/mine/services/apexrest/Accounts?page=0&amp;time=1390296387&amp;hash=1wer2547';         req.httpMethod = 'GET';     RestContext.request = req;     RestContext.response = res;          String results = StoreController.getAccounts();      } }   When i run test class i get the error:  System.NullPointerException: Argument 1 cannot be null    for line :  integer pageNumber=integer.valueof(RestContext.request.params.get('page'));   Looks like parameters are not taken from url ''  when i run the test class.Please can you help me with this?
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)
57036
When I used to create the record in Event object it is showing error like:     Error: Invalid Data.   Apex trigger General_Event_Trigger caused an unexpected exception, contact your administrator: General_Event_Trigger: execution of BeforeINsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.EventClass.updateNewCustomFieldsEvent: line 369, column 1   Trigger code:  trigger General_Event_Trigger on Event (...) {     if (trigger.isBefore)     {         if (trigger.isInsert)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }         else if (trigger.isUpdate)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }     } }   Apex class:  public static void updateNewCustomFieldsEvent(List&lt;Event&gt; eventList) {     for (Event eve : eventList)     {         if (Administrators__c.getInstance().Update_field_Last_Modified_End_User__c)         {             String userIdString = eve.LastModifiedById;             eve.Last_Modified_By_End_User__c = userIdString.subString(0, 15);             eve.Last_Modified_Date_End_User__c = eve.LastModifiedDate;         }     } }
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?
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 ?
105415
This is the test method i have writtenfor batch apex ProductUpdate  .Even if i have a single callout to Database.Executebatch()  I am getting the following error.  Please help !  @isTest (seeAllData=true) global class testbatchProductUpdate  {     public static testMethod  void  pBatchUpdate()     {          /** Product to meet the Criteria in test class **/          Product2 p = new Product2();         p.Name = 'Test Product';         p.Effective_Date__c = Date.Today();         //p.CurrencyIsoCode= 'USD';         p.Material_status__c='status';         insert p;          /** Product to meet the Criteria in test class **/           test.startTest();         batchProductUpdate bpu = new batchProductUpdate();         database.Executebatch(bpu);         test.stopTest();     }  }      Error :  System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable   returned from your start method matches the batch size, resulting in   one executeBatch invocation.", Failure Stack Trace: "External entry   point"
79268
Here is my code `  global with sharing class ReportsListController {     public String dcarr { get; set; }    public static ReportsColumnMap__c repcols { get; set; }    public ReportsListController() { } // empty constructor    @RemoteAction   global static List&lt;ReportsColumnMap__c&gt; getRepCols(String dcarr) {             List&lt;ReportsColumnMap__c&gt; repcols =          [SELECT ColumnName__c,SObject__c ,COUNT(ID) FROM ReportsColumnMap__c WHERE ColumnName__c IN ('OWNER','FIRST_NAME','LAST_NAME','TITLE','COMPANY','LEAD_SOURCE','RATING','STREET','EMAIL') AND SObject__c !='null' GROUP BY SObject__c ,ColumnName__c];     return repcols;   } }   `
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
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
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
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  }       }     } );   } }
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?
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.
120763
I have to serialize around a million items and I get the following exception when I run my code:  Exception in thread "main" java.lang.OutOfMemoryError: Java heap space     at java.util.Arrays.copyOfRange(Unknown Source)     at java.lang.String.&lt;init&gt;(Unknown Source)     at java.io.BufferedReader.readLine(Unknown Source)     at java.io.BufferedReader.readLine(Unknown Source)     at org.girs.TopicParser.dump(TopicParser.java:23)     at org.girs.TopicParser.main(TopicParser.java:59)   How do I handle this?
2097
I'm getting a NoSuchMethodError error when running my Java program.  What's wrong and how do I fix it?