I'm trying to make a matrix using two dimensional arrays, but when I try to print it to the screen I get a null pointer exception  import java.util.concurrent.ThreadLocalRandom;  public class GridWorld {   // data    int [][] grid; // a "r by c" grid will all entries of type int   int r; // no. of rows    int c; // no. of cols    final static int ROW = 4;  // Default row size    final static int COL = 4;  // Default col size    // constructors    // 1. default constructor: construct a 4x4 Grid of int   //    the entry at row i and col j is  4*i+j+1    public GridWorld() {     r=4;     c=4;     for(int i =0;i&lt;r;i++){       for(int j=0; j&lt;c; j++){         grid[i][j] = 4*i+j+1;}}    }    * -----------------------------      |    1 |    2 |    3 |    4 |      -----------------------------      |    5 |    6 |    7 |    8 |      -----------------------------      |    9 |   10 |   11 |   12 |      -----------------------------      |   13 |   14 |   15 |   16 |      -----------------------------   */  public void display() {    System.out.println("-----------------------------");    for(int i=0;i&lt;this.r;i++){      for(int j =0;j&lt;this.c;j++){        System.out.print("|    "+this.getVal(i,j)+" ");}      System.out.println(" |");      System.out.println("-----------------------------");}   }      GridWorld grid1 = new GridWorld();      grid1.display(); }     I was hoping this would print something similar to the commented picture, but instead it is giving me java.lang.NullPointerException  I'm pretty new to java and couldn't find how to fix this anywhere, any help would be greatly appreciated.
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?
46764
I may be teaching a "Java crash-course" soon.  While it is probably safe to assume that the audience members will know Big-O notation, it is probably not safe to assume that they will know what the order of the various operations on various collection implementations is.  I could take time to generate a summary matrix myself, but if it's already out there in the public domain somewhere, I'd sure like to reuse it (with proper credit, of course.)  Anyone have any pointers?
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
50259
I need to illustrate a 2D array data structure in my document. This is a picture I found on the internet. I want something similar.    I also want to show the memory layout in the illustration. Something like this:   Can someone help me with drawing them in Tikz? Thanks in advance.  MWE  \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{tikz} \usetikzlibrary{matrix,backgrounds}  \begin{document} \begin{tikzpicture}[font=\ttfamily, array/.style={matrix of nodes,nodes={draw, minimum size=7mm, fill=green!30},column sep=-\pgflinewidth, row sep=0.5mm, nodes in empty cells, row 1/.style={nodes={draw=none, fill=none, minimum size=5mm}}, row 1 column 1/.style={nodes={draw}}}]  \matrix[array] (array) { 0 &amp; 1 &amp; 2 &amp; 3 &amp; 4 &amp; 5 &amp; 6 &amp; 7 &amp; 8 &amp; 9\\   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;  \\}; \node[draw, fill=gray, minimum size=4mm] at (array-2-9) (box) {};  \begin{scope}[on background layer] \fill[green!10] (array-1-1.north west) rectangle (array-1-10.south east); \end{scope}  \draw (array-1-1.north)--++(90:3mm) node [above] (first) {First index}; \draw (array-1-10.east)--++(0:3mm) node [right]{Indices}; \node [align=center, anchor=south] at (array-2-9.north west|-first.south) (8) {Element\\ (at index 8)}; \draw (8)--(box); % \end{tikzpicture} \\ \begin{tikzpicture}[font=\ttfamily, array/.style={matrix of nodes,nodes={draw, minimum size=7mm, fill=red!30},column sep=-\pgflinewidth, row sep=0.5mm, nodes in empty cells, row 1/.style={nodes={draw=none, fill=none, minimum size=5mm}}, row 1 column 1/.style={nodes={draw}}}]  \matrix[array] (array) {  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp; \\  &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;  \\}; % \end{tikzpicture} \\ \begin{tikzpicture}[font=\ttfamily, array/.style={matrix of nodes,nodes={draw, minimum size=7mm, fill=blue!30},column sep=-\pgflinewidth, row sep=0.5mm, nodes in empty cells, row 1/.style={nodes={draw=none, fill=none, minimum size=5mm}}, row 1 column 1/.style={nodes={draw}}}]  \matrix[array] (array) {  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp;  &amp; \\  &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;   &amp;  \\}; % \end{tikzpicture} \end{document}
80355
I have this struct:  struct Map {     public int Size;      public Map ( int size )     {         this.Size = size;     }      public override string ToString ( )     {         return String.Format ( "Size: {0}", this.Size );     } }   When using array, it works:  Map [ ] arr = new Map [ 4 ] {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  arr [ 2 ].Size = 0;   But when using List, it doesn't compile:  List&lt;Map&gt; list = new List&lt;Map&gt; ( ) {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  list [ 2 ].Size = 0;   Why?
106050
Hi I'm pretty new to Stack Overflow so I hope that I'm doing this correctly and that someone out there has the answer I need.  I'm currently coding a program in Java with Eclipse IDE an my question is this:  I need a snippet of code that does the following  It's supposed to get a .TXT file containing text and from that .TXT file  count the number of rows and print it,  count the number of words and print it,  count the number of characters and print it. And finally make a list of the top 10 words used and print that.  Allt the printing is done to system outprintln  I'm pretty new to Java and am having some difficulties.  Anyone out there who can provide me with these lines of code or that knows where i can find them? I want to study the code provided that's how I learn best=)  Thanks to all   Didnt find the edit button sorry...  I Added this to my question:  Hehe it´s an assignment but not a homework assignment ok i see well i could provide what i've done so far, i think im pretty close but it´s not working for me. Is there anything i have missed?  // Class    Tip   import java.io.*; import java.util.*;  class Tip {     public static void main(String [] args) throws Exception     {          String root = System.getProperty("user.dir");            InputStream is = new FileInputStream( root + "\\tip.txt" );         Scanner scan = new Scanner( is );          String tempString = "";         int lines = 0;         int words = 0;         Vector&lt;Integer&gt; wordLength = new Vector&lt;Integer&gt;();         int avarageWordLength = 0;          while(scan.hasNextLine() == true)         {                 tempString = scan.nextLine();                 lines++;         }          is.close();          is = new FileInputStream( root );         scan = new Scanner( is );          while(scan.hasNext() == true)         {                 tempString = scan.next();                 wordLength.add(tempString.length());                 words++;         }          for(Integer i : wordLength)         {                 avarageWordLength += i;         }         avarageWordLength /= wordLength.size();           System.out.println("Lines : " + lines);         System.out.println("Words : " + words);         System.out.println("Words Avarage Length : " + avarageWordLength);          is.close();          } }
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?
59355
DataGridView, for example, lets you do this:  DataGridView dgv = ...; DataGridViewCell cell = dgv[1,5];   but for the life of me I can't find the documentation on the index/square-bracket operator.  What do they call it?  Where is it implemented?  Can it throw?  How can I do the same thing in my own classes?  ETA: Thanks for all the quick answers.  Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation.  It doesn't mention what happens if you supply invalid coordinates.  ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates.  Fair warning.
37897
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
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?
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.
3276
I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to the x and the y axis, that is all of their edges will have slopes of 0 or infinity.  I've tried to implement what is mentioned in  question but I am not having very much luck.  My current implementation does the following:  // Gets all the vertices for Rectangle 1 and stores them in an array -&gt; arrRect1 // point 1 x: arrRect1[0], point 1 y: arrRect1[1] and so on... // Gets all the vertices for Rectangle 2 and stores them in an array -&gt; arrRect2  // rotated edge of point a, rect 1 int rot_x, rot_y; rot_x = -arrRect1[3]; rot_y = arrRect1[2]; // point on rotated edge int pnt_x, pnt_y; pnt_x = arrRect1[2];  pnt_y = arrRect1[3]; // test point, a from rect 2 int tst_x, tst_y; tst_x = arrRect2[0]; tst_y = arrRect2[1];  int value; value = (rot_x * (tst_x - pnt_x)) + (rot_y * (tst_y - pnt_y)); cout &lt;&lt; "Value: " &lt;&lt; value;     However I'm not quite sure if (a) I've implemented the algorithm I linked to correctly, or if I did exactly how to interpret this?  Any suggestions?
6108
Why do I get compiler errors with this Java code?  1  public List&lt;? extends Foo&gt; getFoos() 2  { 3    List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4    foos.add(new SubFoo()); 5    return foos; 6  }  Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.  Errors I get with this code:   On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;" On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"   Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();".  But I'm still having the issue with Line 4.
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?
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)?
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!