This is the class where the error is shown.  I have commented the line number 245, where netbeans says: dereferencing possible null pointer. if i didn't initialize the endHours as null, it also gives an error. and when i print endHour, it clearly returns a value. but i get this error when i try to put the endHour to the array endHours  public List getRanges(String type) throws NullPointerException, FileNotFoundException, IOException{     List endHours = null;       String fileName="";     if(type.equals("tcp")){         fileName="tcprange";     }else if(type.equals("udp")){         fileName="udprange";     }      String line = null;      try {          FileReader fileReader=new FileReader("conf/"+fileName+".txt");         BufferedReader bufferedReader=new BufferedReader(fileReader);         int i=0;         HashMap tempEndHours=new HashMap();         while((line = bufferedReader.readLine()) != null) {             int endHour=0;             String[] split=line.split("\t");             endHour=Integer.parseInt(split[1]);             if(!tempEndHours.containsKey(endHour)){                 tempEndHours.put(tempEndHours,i);                 //System.out.println(endHour);                 endHours.add(i,endHour);// ** line 245             }             //System.out.println(endHour);              i++;          }     }catch(FileNotFoundException ex) {         System.out.println("Unable to open file '"+"conf/"+type+".txt"+ "'");                     }      //Collections.sort(endHours);     return endHours; }
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?
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
24404
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.  A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.  Update for clarification: The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
58461
Consider the code:  PreparedStatement ps = null; ResultSet rs = null; try {   ps = conn.createStatement(myQueryString);   rs = ps.executeQuery();   // process the results... } catch (java.sql.SQLException e) {   log.error("an error!", e);   throw new MyAppException("I'm sorry. Your query did not work."); } finally {   ps.close();   rs.close(); }   The above does not compile, because both PreparedStatement.close() and ResultSet.close() throw a java.sql.SQLException.  So do I add a try/catch block to the finally clause?  Or move the close statements into the try clause?  Or just not bother calling close?
62317
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers.  To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values:  if (p &amp;&amp; !q)   do_something();   then using zero makes more sense (as in if you use NULL, you cannot logically use p &amp;&amp; !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL).  Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?  Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
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...
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.
81002
When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts?  Edit: there is a native component, this is an SWT application on win32.
84853
Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate?  I also believe the question, detail, and response is much better than the referenced question.  I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse.  I want to use the  to visualize some data I'm working with.  This code is organized like this:  ./com ./com/touchgraph ./com/touchgraph/graphlayout ./com/touchgraph/graphlayout/Edge.java ./com/touchgraph/graphlayout/GLPanel.java ./com/touchgraph/graphlayout/graphelements ./com/touchgraph/graphlayout/graphelements/GESUtils.java ./com/touchgraph/graphlayout/graphelements/GraphEltSet.java ./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java ./com/touchgraph/graphlayout/graphelements/Locality.java ./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java ./com/touchgraph/graphlayout/graphelements/TGForEachNode.java ./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java ./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java ./com/touchgraph/graphlayout/graphelements/VisibleLocality.java ./com/touchgraph/graphlayout/GraphLayoutApplet.java ./com/touchgraph/graphlayout/GraphListener.java ./com/touchgraph/graphlayout/interaction ./com/touchgraph/graphlayout/interaction/DragAddUI.java ./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java ./com/touchgraph/graphlayout/interaction/DragNodeUI.java ./com/touchgraph/graphlayout/interaction/GLEditUI.java ./com/touchgraph/graphlayout/interaction/GLNavigateUI.java ./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java ./com/touchgraph/graphlayout/interaction/HVScroll.java ./com/touchgraph/graphlayout/interaction/HyperScroll.java ./com/touchgraph/graphlayout/interaction/LocalityScroll.java ./com/touchgraph/graphlayout/interaction/RotateScroll.java ./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java ./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java ./com/touchgraph/graphlayout/interaction/TGUIManager.java ./com/touchgraph/graphlayout/interaction/TGUserInterface.java ./com/touchgraph/graphlayout/interaction/ZoomScroll.java ./com/touchgraph/graphlayout/LocalityUtils.java ./com/touchgraph/graphlayout/Node.java ./com/touchgraph/graphlayout/TGAbstractLens.java ./com/touchgraph/graphlayout/TGException.java ./com/touchgraph/graphlayout/TGLayout.java ./com/touchgraph/graphlayout/TGLensSet.java ./com/touchgraph/graphlayout/TGPaintListener.java ./com/touchgraph/graphlayout/TGPanel.java ./com/touchgraph/graphlayout/TGPoint2D.java ./com/touchgraph/graphlayout/TGScrollPane.java ./TG-APACHE-LICENSE.txt ./TGGL ReleaseNotes.txt ./TGGraphLayout.html ./TGGraphLayout.jar   How do I add this project in Eclipse and get it compiling and running quickly?
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
80203
This error should be a simple one but I cant seem to make it work. The problem lies in the fact that this very same code works earlier in the program. I don's see any reason for it to be sending an error on this instance and not the four previous ones. Reference the code below, and feel free to provide any criticism you may have as it should make me better. If it matters, I am using Sharp Develop 2.2.  Here is an example of the code that works:  void calc2Click(object sender, EventArgs e) {     if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_fla.Text) &amp; String.IsNullOrEmpty(tb2_e.Text) | String.IsNullOrEmpty(tb2_e.Text))     {         MessageBox.Show("Enter either kVA and Voltage or FLA and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);     }                 if (!String.IsNullOrEmpty(tb2_kva.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_kva.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * 1000) / (1.732050808m * y); //the m at the end of the decimal allows for the multiplication of decimals                 tb2_fla.Text = z.ToString();             tb2_fla.Text = Math.Round(z,2).ToString();     }         else     {         if (!String.IsNullOrEmpty(tb2_fla.Text) &amp; !String.IsNullOrEmpty(tb2_e.Text))     {              decimal x, y, z;             x = decimal.Parse(tb2_fla.Text);                   y = decimal.Parse(tb2_e.Text);             z = (x * y * 1.732050808m) / 1000; //the m at the end of the decimal allows for the multiplication of decimals               tb2_kva.Text = Math.Round(z,2).ToString();      }   Here is the example of the code that sends the error in the subject line of this post:  void Calc4Click(object sender, EventArgs e) {         if (!String.IsNullOrEmpty(tb4_fla.Text) &amp;&amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_kw.Text) &amp; String.IsNullOrEmpty(tb4_e.Text) || String.IsNullOrEmpty(tb4_e.Text))         {   //If values are entered improperly, the following message box will appear         MessageBox.Show("Enter either FLA and Voltage or kW and Voltage", "Invalid Data Entry", MessageBoxButtons.OK);         }              if (!String.IsNullOrEmpty(tb4_fla.Text)&amp;&amp; !String.IsNullOrEmpty(tb4_e.Text)&amp;&amp; String.IsNullOrEmpty(tb4_kw.Text))         {//If the user eneters FLA and Voltage calculate for kW              decimal x, y, z;             x = decimal.Parse(tb4_fla.Text);             y = decimal.Parse(tb4_e.Text);             z = (x*y)*(.8 * 1.732050808m);             tb4_kw.Text = Math.Round(z,0).ToString();          }                         if (!String.IsNullOrEmpty(tb4_kw.Text) &amp;&amp; !String.IsNullOrEmpty(tb4_e.Text) &amp;&amp; String.IsNullOrEmpty(tb4_fla.Text))         {;//If the user enters kW and Voltage calculate for FLA             decimal x, y, z;             x = decimal.Parse(tb4_kw.Text);             y = decimal.Parse(tb4_e.Text);             z = (1000 * x)/(y * 1.732050808m)* .8;             tb4_fla.Text = Math.Round(z,0).ToString();         }      }   I appreciate any help that I can get.  Thank you.
40938
After I posted this question, I found a similar post that seemed to answer it: . I'll leave this in place for now, as I am not sure how to mark my own question as a duplicate  In attempting to debug a SOQL query error, I encountered a strange behavior with Database.query and bind variables. Specifically, when I run this code:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } Database.query(userQuery);   the Database.query statement executes with no errors, despite the fact that the variable firstNames does not exist in its context. However, when I add an else clause:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } else {     List&lt;String&gt; firstNames; } Database.query(userQuery);   I receive a null object reference exception. It seems like Salesforce is checking to see if the variable is only declared once beforehand and, if so, uses its value in the context it was declared. This seems strange to me, so I was wondering if anybody here has any insight into what is going on under the hood.
92456
Alright, I have been doing the following (variable names have been changed):   FileInputStream fis = null; try {     fis = new FileInputStream(file);      ... process ...  } catch (IOException e) {     ... handle error ... } finally {     if (fis != null)         fis.close(); }    Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.
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)
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?