I have this method:  private ArrayList&lt;Image&gt; imageArray(File files[]) {      ArrayList&lt;Image&gt; images = null;      for(int x = 0; files.length &gt; x; x++) {          //I want to add each PNG-File to the Image-Array          try {             images.add(x, ImageIO.read(files[x])); //Demo.imageArray(Demo.java:23)         }catch(IOException | ArrayIndexOutOfBoundsException exception) {             exception.printStackTrace();         }          //Now I scale each Image, so it fits the screenSize          int newWidth = (int) screenSize.getWidth(),             newHeight = newWidth * images.get(x).getHeight(null) / images.get(x).getWidth(null);          if(newHeight &gt; screenSize.getHeight()) {              newHeight = (int) screenSize.getHeight();             newWidth = newHeight * images.get(x).getWidth(null) / images.get(x).getHeight(null);         }          images.set(x, images.get(x).getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH));     }      return images; }   which causes this Exception :  Exception in thread "main" java.lang.NullPointerException     at Demo.imageArray(Demo.java:23) //I've marked the position in the code!     at Demo.main(Demo.java:47) // Just, when I want to use the method anywhere   Why do I get that Error and how can I work around it? I have added a parameter, when I wanted to use the method, which looks like this :  imageArray(new File[] {new File("filePath to PNG-Image"),             new File("filePath to PNG-Image")})
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?
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?
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?
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();          } }
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");             }         }     } }
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));         }      }
75825
I have created a program which searches for files in a source folder. If it finds any file, it processes that file and moves it to a destination folder, then looks for a new file in the source folder. It has to keep on checking the source folder for a file.  I have used a thread to look for files in the source folder. The problem I am facing is whenever any exception is thrown during file processing, the thread gets stopped. I want the thread to be running even if an exception is thrown. It has to move the file that caused the error to some other folder and look for a new file in the source folder. How can I make the thread keep on running?  Eg:  public void run() {     try {         searchfile();     }     catch(Exception e) {         e.printStackTrace();     } }  public void searchfile(){   ... }     Update :   I should be more clear in my question. Actually there are 4 source folders and 4 destination folders. I have to perform the same operation in each source &amp; destination pair. So i have created 4 threads in one class and do the operation in separate class.  class MainClass {    public static void main(String[] args){       for(int i=0;i&lt;4;i++){          SearchClass search = new SearchClass();          Thread thread = new Thread(search);          thread.start();      }    }    }  class SearchClass {    public void run() {    try {       searchfile();    } catch(Exception e) {       e.printStackTrace();    } }  public void searchfile(){ ... } }   All the thread wont stop running eventhough it caught any exception in middle. How can i do that?
108125
I'd like to convert gif images to jpeg using Java. It works great for most images, but I have a simple transparent gif image:    [In case the image is missing: it's a blue circle with transparent pixels around it]  When I convert this image using the following code:  File file = new File("indexed_test.gif"); BufferedImage image = ImageIO.read(file); File f = new File("indexed_test.jpg"); ImageIO.write(image, "jpg", f);   This code works without throwing an Exception, but results an invalid jpeg image:     [In case the image is missing: IE cannot show the jpeg, Firefox shows the image with invalid colors.]  I'm using Java 1.5.   I also tried converting the sample gif to png with gimp and using the png as an input for the Java code. The result is the same.  Is it a bug in the JDK? How can I convert images correctly preferably without 3rd party libraries?  UPDATE:  Answers indicate that jpeg conversion cannot handle transparency correctly (I still think that this is a bug) and suggest a workaround for replacing transparent pixels with predefined color. Both of the suggested methods are quite complex, so I've implemented a simpler one (will post as an answer). I accept the first published answer with this workaround (by Markus). I don't know which implementation is the better. I go for the simplest one still I found a gif where it's not working.
13711
I am trying to install a Java application on my Linux machine (Slackware).   I have received the following error, and I do not understand it.   Could you advise me how to approach the problem? Thank you.  Here is what I get: (I see that some X11 DISPLAY variable needs to be set, but what value should I give it and how?)  ~$ java -jar gate-5.0-beta1-build3048-installer.jar - ERROR -  java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. at java.awt.GraphicsEnvironment.checkHeadless(Graphic sEnvironment.java:159) at java.awt.Window.&lt;init&gt;(Window.java:407) at java.awt.Frame.&lt;init&gt;(Frame.java:402) at net.sourceforge.mlf.metouia.borders.MetouiaDotsBuf fer.&lt;init&gt;(MetouiaDotsBuffer.java:105) at net.sourceforge.mlf.metouia.borders.MetouiaDots.&lt;i nit&gt;(MetouiaDots.java:66) at net.sourceforge.mlf.metouia.borders.MetouiaToolBar Border.&lt;init&gt;(MetouiaToolBarBorder.java:49) at net.sourceforge.mlf.metouia.MetouiaLookAndFeel.ini tComponentDefaults(MetouiaLookAndFeel.java:241) at javax.swing.plaf.basic.BasicLookAndFeel.getDefault s(BasicLookAndFeel.java:130) at javax.swing.plaf.metal.MetalLookAndFeel.getDefault s(MetalLookAndFeel.java:1591) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:537) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:581) at com.izforge.izpack.installer.GUIInstaller.loadLook AndFeel(GUIInstaller.java:373) at com.izforge.izpack.installer.GUIInstaller.&lt;init&gt;(G UIInstaller.java:116) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Construc tor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:30 at com.izforge.izpack.installer.Installer.main(Instal ler.java:62)
112802
i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.  this is the code:  [TestMethod] public void TestMethod1() {     // Grab the binary data.     byte[] data = File.ReadAllBytes("Chick.jpg");      // Read in the data but do not close, before using the stream.     Stream originalBinaryDataStream = new MemoryStream(data);     Bitmap image = new Bitmap(originalBinaryDataStream);     image.Save(@"c:\test.jpg");     originalBinaryDataStream.Dispose();      // Now lets use a nice dispose, etc...     Bitmap2 image2;     using (Stream originalBinaryDataStream2 = new MemoryStream(data))     {         image2 = new Bitmap(originalBinaryDataStream2);     }      image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception. }   Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).  I'm really confused :(
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 ?
37105
I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I:  return null throw an exception other  Which is the best practise or idiom?
113807
Why does the following code not work?  I want to instantiate prefabs in a list and then use  it as a GameObject like that :  public GameObject prefab;  void Start() {   ArrayList players = new ArrayList();    for(int i=0; i&lt;5; i++)   {         players.Add( (GameObject)Instantiate(prefab));   }    players[2].transform.position = new Vector3(1, 1, 1);  }   there is an error message
24520
I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript?  Using PHP's getimagesize() for each image causes an unnecessary performance hit since there will be many images.
8444
How can I use JUnit4 idiomatically to test that some code throws an exception?  While I can certainly do something like this:  @Test public void testFooThrowsIndexOutOfBoundsException() {   boolean thrown = false;    try {     foo.doStuff();   } catch (IndexOutOfBoundsException e) {     thrown = true;   }    assertTrue(thrown); }   I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
21911
I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application.  I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying "The file name, directory name, or volume label syntax is incorrect."  As a point of reference, I have no trouble reading image resources from the same jar, passing the URL to an ImageIcon constructor.  This seems to indicate that the method I'm using to get the URL is correct.  URL url = getClass().getResource("/xxx/xxx/xxx/services.xml"); ServicesLoader jsl = new ServicesLoader( url.toString() );   Inside the ServicesLoader class I have   XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler( this ); xr.setErrorHandler( this ); xr.parse( new InputSource( new FileReader( filename )));   What's wrong with using this technique to read the XML file?
114872
I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.  string filePath = "image.jpg"; Image newImage = Image.FromFile(filePath);   The problem occurs when image.jpg isn't really a jpg.  For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception  will be thrown when image.jpg is loaded.  I'm looking for a function that will validate an image given a stream or a file path of the image.  Example function prototype  bool IsValidImage(string fileName); bool IsValidImage(Stream imageStream);