Is this a bug in Java!

int i=0;
i=i++;
System.out.println(i);
What should this code print.
I guess 1.
But it prints 0.
Can anyone explain the logic behind this, or is this a bug in Java.
Thanks for your time in advance.

What did the mackerel do to deserve that?it wrote Sun's search function !!!!!! :pPlease, a mackerel would of done a better job.
All I can say is "JTable project", smiles.
(Gah, Please kill me)mlk BANG BANG*
*Post decease operator.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Is this a bug in Java for number format ?

    Hi,
    I found somethings strange when I trying to use NumberFormat.
    Here are the sample code:
    --- Sample Code start ---
    import java.text.*;
    public class TestNF {
    public static void main(String[] args) {
    double num1 = 10.5;
    double num2 = 10.55;
    NumberFormat nf1 = NumberFormat.getInstance();
    NumberFormat nf2 = NumberFormat.getInstance();
    nf1.setMinimumFractionDigits(0);
    nf1.setMaximumFractionDigits(0);
    nf2.setMinimumFractionDigits(1);
    nf2.setMaximumFractionDigits(1);
    System.out.println(nf1.format(num1));
    System.out.println(nf2.format(num2));
    -- Result start --
    10
    10.6
    -- Result End --
    --- Sample Code end ----
    Since 10.55 is rounded up to 10.6, therefore it should be the same behavior that 10.5 is rounded up to 11.
    Please correct me if I m wrong.
    Version:
    java version "1.6.0_21"
    Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
    Java HotSpot(TM) 64-Bit Server VM (build 17.0-b17, mixed mode)
    ** Added result from my sample code & java version
    Thanks and Regards,
    Jin Keat, Saw
    Edited by: 903151 on Dec 19, 2011 4:55 PM

    jverd wrote:
    903151 wrote:
    Since 10.55 is rounded up to 10.6, therefore it should be the same behavior that 10.5 is rounded up to 11.
    Please correct me if I m wrong.And this is exactly what I get when I run your code under Java 1.6 on Windows 7.
    :; java -version
    java version "1.6.0_29"
    Java(TM) SE Runtime Environment (build 1.6.0_29-b11)
    Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02, mixed mode)
    Also, this has nothing to do with Generics.
    Hi,
    Sorry for my poor English.
    Do u mean by running my sample code, you got 11 instead of 10 ?
    Please advise which is the correct forum/thread.
    Many thanks.
    Regards,
    SawJK

  • Is this a bug of Java? Or my mind?

    Thank you all of you!
    I wrote a Filter like this:
    public class FilterDispatcherExample implements Filter{
         public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws java.io.IOException,ServletException{
              HttpServletRequest req=(HttpServletRequest)request;
              HttpServletResponse res=(HttpServletResponse)response;
              PrintWriter out=res.getWriter();
              String str=(String)req.getAttribute("attr");
              res.setContentType("text/html");
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Filter Redirection</title>");
              out.println("</head>");
              out.println("<body>");
              out.println("FilterRedirection<br>Str: "+str);
              out.println("</body>");
              out.println("</html>");
              chain.doFilter(req,res);
    The problem is: what the str I want to display is not the String I use request.setAttribute() to set in a JSP. I have config web.xml properly. It's puzzled! Thank you!

    I think you should use, request.getParameter();

  • Is this a bug in Java, or am I doing something wrong?

    I have a Vector which I want to convert to an array, so I wrote my code something like this:
    MyObject a = new MyObject("A");
    MyObject b = new MyObject("B");
    MyObject c = new MyObject("C");
    MyObject d = new MyObject("D");
    Vector v = new Vector();
    v.add(a);
    v.add(b);
    v.add(c);
    v.add(d);
    MyObject[] list = new MyObject[v.size()];
    list = (MyObject[]) v.toArray();This should work, however it gives me a ClassCastException at runtime. Of course, I found ways around it, like using
    v.toArray(list);But using the method this way does not make any sense because according to the API it is not void, but supposedly returns another array of Objects in addition to filling up the array which you pass to it.
    Does anyone know the correct way to use the toArray() method, or it's even more mysterious overloaded companion, toArray(Object[] a)?

    With regards to the Vector.toArray() method that takes an Object[] as an argument, you would normally use it this way:
    Vector vector = <whatever>; // contains only instances of MyClass
    MyClass[] array = (MyClass[])vector.toArray(new MyClass[vector.size]);While you're right that if you declare the array first and then simply pass it to the toArray() method that the array will get filled with the appropriate values. However, the array that is returned is not necessarily the array that was passed in. If the array that is passed in is shorter than the number of elements in the Vector, a new array of the same type as the one passed in is allocated and it is that array which is returned. The API only says that an array is returned, not the original one. Here is the source code for the toArray() method for you to look at:
        public synchronized Object[] toArray(Object a[]) {
            if (a.length < elementCount)
                a = (Object[])java.lang.reflect.Array.newInstance(
                                    a.getClass().getComponentType(), elementCount);
         System.arraycopy(elementData, 0, a, 0, elementCount);
            if (a.length > elementCount)
                a[elementCount] = null;
            return a;
        }Shaun

  • Couldn't read from socket error: Is this a bug in Java?

    I have been facing this grave problem for a long time now. After establishing a socket connection with some server:port say 207.123.17.20:1865, I get this error "Couldn't read from socket" as an IOException. I can neither read or send any packets to the server after receiving this error. On checking whether the socket connection is alive or not, I print socket.getAddress() and it returns me the ip of the server to which it is connected. The specification says that receiving this error means the socket was closed by the server. If it so then how I am able to print the server address after receiving this error? How can I get around this problem? Plz. help...

    watertownjordan said:
    If your computer (client) killed the connection, it should throw an error >pointing to the OS closing the connection. but what if my client app cntrl alt del while the server is waiting to here from the client.
    my client may sit idle for hours and then contact again. i want to keep their socket connected but if they cntrl alt del then i want to close the socket so the thread on the server side can be exited.
    the way i solved this was to send an "i'm still here" message to the serv in a timer every 10 seconds and set the time out on the server side to 30 seconds.
    i used a syncronized boolean variable like so:
        volatile private boolean out1busy = false;
        private synchronized boolean getOut1busy(){
         return out1busy;
        private synchronized void setOut1busy(boolean on){
         out1busy = on;
        }then in the timer i do this
            while (getOut1busy()) try { Thread.sleep(40); } catch (InterruptedException ex) {}
            setOut1busy(true);
            lobbyOut.println("-1");
            setOut1busy(false);it seems to work fine but the loop using the thread.sleep does not seem right and i know very little about this all.
    i'm basically asking the same thing as Chintan.Kanal
    Is there any way I can test whether the socket connection is alive from the server side?
    does my approach above have flaws.
    again it seems to work but i am not very Java savy lol.

  • Bug in java arrays?

    Hi, just found this in a toy program and thought it might be a bug in the way java handles arrays... I'm working on Suse 8.0 & jdk 1.4, Red Hat 7.x/8.x with jdk 1.4 and Solaris 4 jdk 1.4:
    If you have a method like this:
        public static void resize(int[] arr, int size) {
            int[] tmp = arr;
            int iterate;
            arr = new int[size];  // disassociate tmp from arr
            iterate = size > tmp.length ? tmp.length : size;
            for(int x = 0; x < iterate; x++) {
                arr[x] = tmp[x];
        }and try to call it from another class like this:
            /* could this possibly be a bug in java??? */
            Arrays.resize(state, state.length + 1);  // make array bigger
            state[state.length - 1] = start;  // store current room in arrayI get an ArrayIndexOutOfBoundsException on the call to assign start to the last index of state, which means that the new array knows its new length, but can't assign to it.
    The solution to my problem was to return arr in the resize() method and assign the returned value to state.
    This seems to go against what its supposed to happen (that the array is rezized and the pointer just updated)
    Is this a bug in java or is it te desired behaviour?
    dave.

    But when I create the 'new' array I'm assigning the
    pointer to the place where the previous array pointer
    was... This should be completely legal. Yes, it's completely legal, but it doesn't do what you want :)
    The variable in method to which you assign a new and longer array is a different one than the pointer you have in another method.
    If you just call a function to assign values to an
    array like this:> public void update(int[]arr){
    arr[0] = 2;
    } > and then use some code to look at the array you
    passed: > int[]x = {1,2,3,4};
    update(x);
    system.out.println(x[0]);> you would expect to get 2 in the
    output. Whay should this operation be different?Because in this case you wrap the reference you change (slot 0 in the array) into another object (the array). Therefore the reference you actually change is the same as the reference you expect to change.
    If you let your resize method return the new and longer array, and assign the returned value to yor old variable, you might get a better result.
    (And System.arraycopy may be more efficient than your for loop.)

  • [ASK]Bugs of Java or Wrong Code?

    Dear All,
    What this is bugs of Java or me not to understand java programming, this my piece code :
    String kode = txtKode.getText();
            String nama = inputNama.getText();
            String keterangan = inputKeterangan.getText();
            try {
                Connection c = KoneksiMySql.getKoneksi();
                String sql = "UPDATE UNIT SET NAMA=?, KETERANGAN=?, WKT_INPUT=now() WHERE KODE=?";
                PreparedStatement p = c.prepareStatement(sql);
                p.setString(1, nama);
                p.setString(2, keterangan);
                p.setString(3, kode);
                p.executeUpdate();
                p.close();
                JOptionPane.showMessageDialog(null, "Data Berubah",
                        "Pemberitahuan", JOptionPane.INFORMATION_MESSAGE);
            } catch(SQLException e) {
                System.out.println("Error : " + e);
                JOptionPane.showMessageDialog(null, "Proses Rubah Unit Gagal",
                        "Pesan Error", JOptionPane.ERROR_MESSAGE);      
            }finally {
            inputNama.setText(null);
            inputKeterangan.setText(null);
                btnTambah.setEnable(true);
                btnHapus.setEnabled(false);
                btnRubah.setEnabled(false);
                inputNama.requestFocus();
    JOptionPane is Show and no error appears but data in database does not change, and code in block finally not executed.
    i'm use jInternalFrame, first run Only 'Add Button, Search Button' enable and other button are disable, then when 'Search Button' is clicked and open other jInternalFrame and get data form database, 'Add button' Disable and 'Delete Button, Change Button' are Enable. that my piece code on Change Button ActionPerformed.
    Please it's support.
    Thanks,
    Best & Regrads.

    Cross posted
    [ASK]Bugs of Java or Wrong Code?
    [HELP]Bugs of Java or Wrong Code?
    db

  • Bug in java.awt.geom.Line2D?

    The method,
    public static double ptLineDistSq(double X1,
                                      double Y1,
                                      double X2,
                                      double Y2,
                                      double PX,
                                      double PY)calculates the squared distance between a line segment and a point.
    If however you pass in a line segment of zero length (X1=X2, Y1=Y2), the method performs a div by zero, which causes NaN to be returned.
    I believe this is a bug, as the method makes no exceptions to valid input, also mathmatically the distance from a point to a line segment still has a value even if the line segment has a zero length.
    A simple sanity check at the start of the method would fix it,
    if(X1==X2 && Y1==Y2) return (X1-PX)*(X1-PX)+(Y1-PY)*(Y1-PY);

    Yeah, im already working around it (i've actually just stolen their code, and switched it all from doubles to floats :D - it isn't a serious app. just a problem I encountered when answering a question in this Thread http://forum.java.sun.com/thread.jsp?forum=406&thread=420363&start=30&range=15&tstart=0&trange=15)
    I was realy just posting here for confirmation that it is a bug, before I reported it.

  • Is this a bug in JVM?

    Hello all.
    Whenever I try to make JNI calls to Ms Word in multiclient environment on server, the JVM closes with the following message.
    Another exception has been detected while we were handling last error.
    Dumping information about last error:
    ERROR REPORT FILE = (N/A)
    PC = 0x19BFC46D
    SIGNAL = -1073741819
    FUNCTION NAME = (N/A)
    OFFSET = 0xFFFFFFFF
    I am using JRE1.4.0 .
    The heap size of JVM I have set is 256 MB.
    Is this a bug in JVM?
    Please guide me in this problem if possible because it is urgent for me.
    Thanks in advance.

    Hallo,
    if I understand your problem correctly, you are trying to call MS Word on your server from Java code in your server. This is not to be recommended!
    I have seen references to this problem elsewhere in the Sun forums but cannot at the moment find them. There is also something in MSDN. As far as I remember, the story goes like this:
    1. Word is a program for client PCs.
    2. Word expects to have a GUI available for it to display messages and so on.
    3. Although you can control Word over OLE, 1 and 2 above still apply.
    4. If you still want to use Word in your server, then on your own head be it.

  • Is this a bug of NIO???

    I am using nio to write a network server.
    I use following code to close a SocketChannel:
    Socket s = sc.socket();
              if (s != null) {
                   try {
                        s.close();
                   } catch (IOException e) {     
                        e.printStackTrace();
              sc.close();
    It works fine. But sometimes s.close() will throw a java.lang.Error, this will lead my server to crash!
    StackTrace:
    java.lang.Error: Untranslated exception
         at sun.nio.ch.Net.translateToSocketException(Net.java:65)
         at sun.nio.ch.SocketAdaptor.close(SocketAdaptor.java:354)
    Caused by: java.io.IOException: Unable to finish a non-blocking socket action (This error message is translated by me, I am not in USA)&#12290;
         at sun.nio.ch.SocketDispatcher.close0(Native Method)
         at sun.nio.ch.SocketDispatcher.preClose(SocketDispatcher.java:44)
         at sun.nio.ch.SocketChannelImpl.implCloseSelectableChannel(SocketChannelImpl.java:684)
         at java.nio.channels.spi.AbstractSelectableChannel.implCloseChannel(AbstractSelectableChannel.java:201)
         at java.nio.channels.spi.AbstractInterruptibleChannel.close(AbstractInterruptibleChannel.java:97)
         at sun.nio.ch.SocketAdaptor.close(SocketAdaptor.java:352)
         ... 18 more
    The error will be throwed if I called it N times, N < 2000.
    Runing env:
    WindowsXp, Amd dual core, 1G ram, JDK1.6.02
    The Logic of my test case:
    Server S listen to port 8080 with one select thread,
    Client A, Client B
    A connect to S, and send a package to get some resource, and A wait
    B connect to S, and send a package to get the same resource, This cause S cause Client A,
    A finds it disconnected, it reconnect and do the same as B
    B finds it disconnected, it reconnect too ....
    now, there is a loop.
    (all these are doing in the select thread)
    I think A and B will do these forever, but after some time( serveral seconds ), the Error will be thrown and
    server crashed.
    I google it, and I found nothing useful. Is this a bug??

    B connect to S, and send a package to get the same resource, This cause S cause Client A, A finds it disconnected, it reconnect and do the same as BI don't understand this. Why does anything done by B have anything to do with A? let alone making it reconnect? There is something seriously wrong with the application logic here if that's the result.
    NIO isn't that matureWell, it wasn't that mature in 1.4.0 or 1.4.1, but that's five years ago. Haven't found anything major in it for years.
    @OP: does it work better if you close the channel directly rather than its socket?

  • A bug in Java

    I would like to report a bug in Java.
    It began with the rmi tutorial on computing pi.
    I had no problem with this on a single computer but could never get it to work over the network. I posted messages on this forum and got lots of generous help, especially from Genady, but eventually I left it as an unsolved problem.
    Yesterday I came back to my local network with my current problem and had problems similar to pi. Now at least I have more experience and I could track it down. It looks like a Java bug to me.
    The hardware is: 1 router, behind which sit 2 computers: home-ilan at 192.168.2.100 and home-yona at 192.168.2.103. I have a client-server setup via rmi. If the server is on home-yona, all works OK. If the server is on home-ilan it fails. What could be the difference?
    It turns out that home-ilan (my main computer) also has the possibility to run VPN to the hospital. The VPN uses a given IP. If I need to get to the hospital, I use the VPN. If not, I don't use it.
    Yesterday I put Eclipse on home-yona and looked for the problem. It turns out to be in
    Query q1 = (Query) Naming.lookup(rmi1);I was running the query from home-yona to home-ilan. I got a valid q1 back, and I drilled down into it. One of the elements is
    ep=TCPEndpoint which has a host value.
    The host value should have been 192.168.2.100, but instead it was the value of the VPN. The packet was sent from 192.168.2.100 to 192.168.2.103 and home-yona picked up the packet correctly, but it had the wrong value of the host. When I actually made the query to rmi, it expected the result from the VPN IP, which it never got, so it timed out.
    The bug is that Naming.lookup, even though it got the packet through the LAN, gave VPN address. This would have been fine had I been querying from the hospital, but I was in fact doing a local query. The Naming.lookup doesn't differentiate, which is a bug.
    The bug is 100% reproducible. If I start the server while VPN is running, from home-yona I will always get the VPN IP. If I start the server while VPN is turned off, I will get the correct address.
    Any suggestions?
    Ilan

    If that were the only thing which was wrong, we'd be in great shape. It is then a bug of Cisco Systems who supplied the VPN. I just took the default conditions and used them. I had no idea there was any problem until I ran the RMI protocol.
    In fairness to Cisco Systems, I must say that it is unusal to say that I want a VPN connection into the hospital and at the same time make a connection over my local LAN. In fact it works for everything I happened to try up until now, but it fails for RMI (because of the static assignment).
    The amazing thing is that with all these incompatible programs is not that sometimes it fails, but that it works at all. When I look at the Control Panel, I see 2 LAN connections, my local LAN and the VPN. I suspect I would have a very similar problem if I had 2 physical LAN cards.
    The home-ilan identifies the computer and it doesn't identify the computer-lan combination.
    What the RMI wants is not the computer identification, but rather the lan card identification. At least in the Control Panel, such a thing doesn't exist.

  • Is this a bug in ArrayList or is it intended?

    Hi all,
    During past weekend, I was participating in a programming contest, where I found a bug in Java ArrayList class.
    When I added a string to the ArrayList (I used ArrayList<String>, of course), the added string's first letter was automatically capitalized.
    I was doing simple searching if a string (case sensitive) exists in the list and add if it doesn't exist. However, it was keep adding 'qwerty' when there was 'Qwerty' already exists in the list.
    Is this something intended for ArrayList or is it a bug?
    Or... am I missing something??
    Thanks in advance :)
    bLee

    Nothing is automatically capitalized when I do it.
    import java.util.ArrayList;
    public class ArrayListTest {
        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<String>();
            list.add("one");
            list.add("One");
            list.add("two");
            list.add("Two");
            list.add("three");
            list.add("Three");
            System.out.println(list);
    }Can you post code?

  • Is this a bug in ImageIO?  It gives inconsistent and nasty results

    Hi everyone
    Here's a stumper that I have been having trouble with and finally have a test case to illustrate it. First of all, the code:
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class PicTest
        public static void main(String[] args) throws Exception
            BufferedImage buf1 = ImageIO.read(new URL("http://www.bestfoto.com/ArchivedPOTD/021606S.jpg"));
            BufferedImage buf2 = ImageIO.read(new URL("http://www.bestfoto.com/ArchivedPOTD/021606O.jpg"));
            ImageIO.write(buf1, "jpg", new File("C:/test1.jpg"));
            ImageIO.write(buf2, "jpg",  new File("C:/test2.jpg"));
    }It's all very simple - we are pulling 2 jpgs from the net and writing them to 2 files. When you run it, test2.jpg is looking very nice. However, test1 is looking horrible and the color is completely off. Anyone know what's going on here? I've seen this on quite a few jpgs now and I'm thinking that there is either a bug in java's JPG codec or the incoming image is somehow corrupted. But, any web browser I try makes the image look fine.
    What gives? Thanks!

    Yes, I think this is a bug in java5 - it cannot write jpegs out because of a missing file in $JAVA_HOME/jre/lib/ccm. The file is called PYCC.pf.
    I forgot that I copied this file from a previous version of the JDK, 1.4x. Maybe this is my problem? But if this file is causing the problem, then taking it out would break the jpeg writer completely.
    Anyone have an idea about this?
    Thanks
    I tried you app in j2se 1.5 and came up with this
    stack trace for both images:
    C:\jexp>java PicTest
    Exception in thread "main"
    java.lang.IllegalArgumentException: Can't load
    standa
    rd profile: PYCC.pf
    at java.awt.color.ICC_Profile$2.run(Unknown
    (Unknown Source)
    at
    at
    at
    at java.security.AccessController.doPrivileged(Native
    Method)
    at
    at
    at
    at
    java.awt.color.ICC_Profile.getStandardProfile(Unknown
    Source)
    at
    at
    at java.awt.color.ICC_Profile.getInstance(Unknown
    wn Source)
    at
    at java.awt.color.ColorSpace.getInstance(Unknown
    known Source)
    at
    at
    at
    at
    com.sun.imageio.plugins.jpeg.JPEG.isNonStandardICC(Unk
    nown Source)
    at
    at
    at
    at
    com.sun.imageio.plugins.jpeg.JPEGMetadata.<init>(Unkno
    wn Source)
    at
    at
    at
    at
    com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(Unk
    nown Source)
    at javax.imageio.ImageWriter.write(Unknown
    (Unknown Source)
    at javax.imageio.ImageIO.write(Unknown
    (Unknown Source)
    at javax.imageio.ImageIO.write(Unknown
    (Unknown Source)
    at PicTest.main(pictest.java:13)It seems to work okay with a "png" extension
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class PicTest
    public static void main(String[] args) throws
    rows Exception
    BufferedImage buf1 = ImageIO.read(new URL(
    "http://www.bestfoto.com/ArchivedPOTD/021606S.jpg"));
    BufferedImage buf2 = ImageIO.read(new URL(
    "http://www.bestfoto.com/ArchivedPOTD/021606O.jpg"));
    //System.out.println("buf1 type = " +
    pe = " + buf1.getType() + "\n" +
    //                   "buf2 type = " +
    pe = " + buf2.getType());
    // buf1 type = 5
    // buf2 type = 5
    // 5 -> TYPE_3BYTE_BGR
    ImageIO.write(buf1, "png", new
    ng", new File("C:/test1.png"));
    ImageIO.write(buf2, "png", new
    ng", new File("C:/test2.png"));

  • Bug in Java

    Hi Guys ,
    i found a bug in java when doing this calculation..
    double a = 1741;
           double b = 81.1;
           double c = 0;
           double temp = (a-b-c);
           System.out.println("temp = "+temp);  //1659.9
           double total = (double)temp/1000;   //BUG HERE
           System.out.println("Res = "+total);  //1.6599000000000002I wonder if u guys get the same value as mine using above calculation.
    if i change the double b = 81.2 i works fine..

    I have good news and bad news for you. To end on a high note we'll leave the good news for last.
    The bad news is that you are the 6,137,215th person to report this "bug" yet Sun will not be fixing it.
    The good news is that the bad news doesn't matter because... <drumroll please/>.....
    It is NOT a bug. The only bug here is your lack of understanding floating point arithmetic. I refer you to the following article http://docs.sun.com/source/806-3568/ncg_goldberg.html

  • A possible *bug* in java jcombobox

    Hi all,
    I think i found a possible bug in java jcombobox .. i am sure some of you must have already experienced it..
    supposedly you put a jcombobox in a jpanel
    returned the panel from a method to a calling method..
    and that method adds it to another panel that it had created to a frame..
    and if this happens dynamicaly at runtime, as only after u click a button..
    meaning : without adding the combobox or the immediate parent panelto the contentpane .. directly..
    Then,
    your combox's keylistener may not catch events fired.
    .. this has happened to me many times.. and always i could only find a way out
    .. by adding the combobox to panel that is loaded during startup itself and is
    .. not returned through a method call.
    Your opinions please ?
    'Harish.

    All components in a UI are created at run-time.
    When you create your JFrame you call pack() to align and resize the UI. This validates all the components, and sets the default focus on what ever component should have the focus at start up.
    When you create components and add them as children of another component you have to validate the child and parent. This can be done by calling JComponent.validate()
    As for keylisteners not getting called, this might be fixed if you call grabFocus on the new combobox. I can't see a reason why any listener would stop working.
    For me to really understand what your talking about. I'd need to see source code reproducing this problem.

Maybe you are looking for