Java InstanceOf operator

I am writing a program that runs on a simulated network, that exposes my data to potential corruption. So, if I send an object across the network and some of the bytes in that object get corrupted will the instanceof operator still recognize that object as a member of a particular class even though some of the data is corrupted, or does it depend on which actual bytes are corrupted?

When an object is serialized part of what's sent is the name of the class, and that's all that determines what class of object it will attempt to reconstruct..
If you're using an unreliable connection stream then you should probably add a CRC check of some kind. Most of the channels you migh use have that built in.

Similar Messages

  • Java or operator statement and expressions

    So I tried to simplify some code this morning using the java or operator and it doesn't seem to work. It went something like this:
    if ((time < 4) || (time > 10))}
    val = aVariable}
    else val=0;
    What I end up with is zero until 4 but after 10 the val does not return to 0.
    I hope this makes sense to somebody out there. I just went back to a stack of if else statements to solve the problem.
    Thanks

    I'm not sure what the problem is (except that your curly brackets are wrong), but this opacity expression works:
    if ((time < 4) || (time > 10)){
    0
    }else{
    100
    Dan

  • Is the 'instanceof' operator discouraged ?

    Hi,
    I have heard that the instanceof operator is not recommended and should be used only as a last resort. Can someone throw some light into it ? is there an alternative ?
    thanx and regards

    hi,
    thanx for the response.
    well, the BaseException and its subclasses belong to a different applicaiton, and my application calls this application thru remote interface.
    For each of the 5 sub-exceptions, we need to log a different message, and then propogate the same to our client.
    There is too much code repetetion-- My session bean has 10 methods, each of these catch the 5 sub-classes, log a message and throw a new exception.
    To avoid code repetetion, i ll catch the BaseException in each of the 10 methods of session bean, and then in the catch block, i ll call a method say -- handleExeption, which will identify the type of exception and take the action that were taken earlier by the multiple catch blocks.
    Now, I need to use the instanceof operator to identify the specific type of exception. Will it be recommended practice ?
    thanx and regards

  • Avoiding using instanceof operator

    I've heard that using the instanceof operator isn't such a great code technique, and since I'm in the design phase, I feel like I should be able to avoid this. Right now, part of my design requires use of the instanceof operator as well as casting.
    Let's say you have a common notifier interface and two abstract classes which extend from this interface:
    com.example.Notifier Interface:
    public void doNotify(Notification notif, List notifiables);
    public boolean canSend(Notification notif, Notifiable person);
    com.example.SerialNotifier (abstract)
    public void doNotify(Notification notif, List people)
        for (Iterator itList = people.iterator(); itList.hasNext();)
             Notifiable person = (Notifiable)itList.next();
             doNotify(person, notif);
    public abstract doNotify(Notification notif, Notifiable person);
    com.example.MulticastNotifier (abstract)
    public abstract void doNotify(Notification notif, List notifiables);MulticastNotifier purposefully doesn't define a way to send a message to a single person, so that developers don't implement a non-multicast solution for a multicast protocol.
    Here's the part that seems to require an "instanceof" clause. Now let's say you have a list of Notifiers. The list of notifiers is mixed, containing both Serial and Multicast Notifiers. Before you send out the notification, you need to filter the list (because for example, someone doesn't want to be notified at all):
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           if (notifier instanceof MulticastNotifier)
                                  buildPeopleList.add(person);
                           } else
                                   SerialNotifier serialNotif = (SerialNotifier)notifier;
                                   serialNotif.doNotify(notification, person);
             if (notifier instanceof MulticastNotifier)
                      notifier.doNotify(notification, buildPeopleList)
        }Is this bad design? Another option is to just iterate through the list essentially twice, but this is of course, less efficient for the serial notifier case:
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           buildPeopleList.add(person);
             notifier.doNotify(notification, buildPeopleList);
        }Any suggestions?

    I'm not sure what you mean. I moved a loop from your
    code to a different class. AFAICT, it's a
    one-for-one. My solution has the same number of
    iterations as yours.Yeah, your code is actually missing a loop, because, as I explained earlier, the design supports filtering at both a parent notifier and a child notifier. To filter, it needs to loop through the list of people
    So, your code actually will look like: (forgive me, doing code in a textarea is kinda a pain)
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      List intermediateList= new ArrayList();
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 intermediateList.add(person);
       for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                    Notifier notif = (Notifier)itNotifiers.next();
                    notif.doNotify(n, intermediateList); // 2nd loop is in here where additional filtering takes place
    }If you assume a serial notifier, you don't need this additional iteration:
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                         Notifier notif = (Notifier)itNotifiers.next();
                         // PROBLEM HERE: assumes serial notifier
                         notif.doNotify(n, person); // child will do own filtering
    }Edit: Corrected logic error in code

  • Instanceof operator, please help!

    I am reading the codes written by others. I am confused on instanceof operator here.
    (A instanceof B) where A and B are interfaces. I found a definition in a book such that the
    instanceof operator returns true or false based on whether the object is an instance of the named
    class or any of that class's subclass. However, I didn't find the relationship between A and B is
    established in the codes. In this case, I wonder if instanceof operator can still be used because I am thinking that it will always evaluate to be false.
    Thank you for your help!
    Cathy

    The instanceof operator can always be used - a return value of false is still a valid return value!
    However, when it comes to interfaces it is possible for a class to implement both interfaces even though there may be no direct relationship between those interfaces.
    Have a look at this:
    public interface MyInterface
    public interface YourInterface
    public class MyClass implements MyInterface, YourInterface
    }There is no relationship between the two interfaces but I can still do this:
    public void check(MyInterface myObj)
      if(obj instanceof YourInterface)
        YourInterface yourObj = (YourInterface)myObj;
        System.out.println("Woo hoo - an instance of MyInterface that's also an instance of YourInterface!");
    }Essentially the instanceof operator is asking if the value passed can be cast to something else for the method to use it more specifically.
    There could be classes other than MyClass that implement both interfaces, particularly if a system is designed to be flexible.
    I hope this makes sense!

  • JCVM are the java card operating system?

    in some articles I read teh following:
    JCVM acts like an operating system. the implementation of JCVM =java card operating system?
    in some articles I read: the Java Card Operating system are JCVM, APIs,JCRE, native Methos, and another classes.
    help me please. thanks.

    The problem can be explained this way.OS and natvie function is the lowest level of the articture,which play the role of os like Windows,JCVM
    is higher,its function is platform indepent,JCRE,or javacard Framework,is the platform for the application,Industry Add-on Classes is the interface supplied by others,for instance,the javacard is used as SIM card,the class is the Sim interface,javacard applet is the applet user developed.
    Apis play the role of package,for example,Throwable � class,it is the parent class of all the exceptions.

  • Efficiency of Java String operations

    Hi,
    for an Information Retrieval project, I need to make extensive use of String operations on a vast number of documents, and in particular involving lots of substring() operations.
    I'd like to get a feeling how efficient the substring() method of java.lang.String is implemented just to understand whether trying to optimize it would be a reasonable option (I was thinking of an algorithm for efficient string pattern matching such as the Knuth-Morris-Pratt algorithm, but if java.lang.String already applies similarly efficient algorithms I would not bother).
    Can someone help?
    J

    Thanks for your comment. Yes of course you're right, I
    mean indexOf(). If so (thanks DrClap), let me enter the discussion.
    The indexOf() implements a so called "brute force algorithm".
    The performance is O(n*m), where n is the length of the text, and
    m is the length of the pattern, but is close to n on the average.
    The KMP is O(n), so the performance gain should be hardly noticeable.
    To get a real performance gain you should look at the BM (Boyer-Moore,
    O(n/m)) algorithm or some of its descendants.
    As for java.util.regex package, as far as i understand it should be
    several times slower than indexOf(), because it reads EACH character through an interface method (as opposed to direct array access in indexOf()).
    Though it's still to be proved experimentally.

  • JAVA (SHIFT OPERATOR)

    Hi,
    I really want to know SHIFT operator in Java like >> , << , >>>
    Could anybody kindly help to explain??
    And
    byte a =-1;
    a = (byte)(a>>>2);
    why the output become -1??
    thanks.

    umm i did get them mixed up. preserved sign bit right shift is >>, pulling-zeros is >>>. so keep that in mind. (ie, 18>>2 == 10010>>2 == 11100 which is -4)
    To calculate the resulting number from >>> right shifts, check this: http://www.janeg.ca/scjp/oper/shift.html
    In response to your original question, it seems it's far more complicated than I at first thought. The -1 that you're getting is an odd (and rather interesting, imo) byproduct of modular arithmetic. what you wrote is exactly similar to this code (ie, my code mimics the castings that happen in your code):
            byte a = -1;
            int b = (int) a;
            int c = b>>>2;
            byte d = (byte) c;
            System.out.print(d);So what happens is A, which is a string of ones (ie 11111111) is casted to an int, B. In general, casting a byte to an int returns an int with exactly the same bits at the end with the sign bit repeated 24 times at the start (ie, 01101011-->(int)0000...00001101011). So B is 11111111111111...1111 (32 ones). Then we right shift B by 2 (we'd get the same answer right shifting it by 0, 1, 2, etc, all the way up to (and including) 24). Then we recast the int C to a byte. This is where the interesting thing happens: Depending how much we right shifted B to get C, C will be a certain number of zeros (call this Z) followed by (32-Z) ones. Apparently, in (mod 2^8) in two's complement all of these numbers are congruent to -1, so the cast gives negative one.
    (remember that the int 127 cast to byte is 127, while the int 128 cast to byte is -128. conversions to a lower-bit type always happen mod 2^N, where N is the number of bits in the type we're casting to.)
    BTW, thanks for this problem. i had a fun half hour figuring it out. hopefully it made some sense to you...
    (EDIT: Flounder is right--you can just view the cast from int to byte as keeping the last 8 bits. much easier to think of it that way, though my definition does give some intuitions about WHY all this works.)
    Edited by: a_weasel on Oct 13, 2008 8:00 PM

  • About instanceof operator

    Example1:Suppose class SubComp extends Component. There has an instance of SubComp calls subCompInstance.When I wrote:subCompInstance instanceof String will compile fail�Bwhy?
    Example2:java.sql.Connection fobjConn; fobjConn instanceof String will compile success.
    Could you tell me what restrice of the second operand?
    Thank you very much!

    from JLS 15.20.2
    "If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true. .."
    basically what it says is, if the type of the reference you arre using can never be an instance of the type you mentioned, the compiler should generate error. so this will not compile
    Component c = create a component
    boolean b =(c instanceof String)
    but this will
    Object c = create a component
    boolean b = (c instanceof String)
    since, in the second case c has the type Object which, depending on the actual class, may be casted to String at runtime.
    Hope it clarifies.

  • Instanceof operator treatment

    Hi I am new bie in java,
    Following is my code.
    public class Test {
        public static void main(String[] args) {
            Test test = new Test();
            System.out.println(test instanceof T);
            System.out.println(test instanceof I);
    interface I {
    class T {
    }Compiler shows error at line System.out.println(test instanceof I);. but not at System.out.println(test instanceof T);.
    If compiler can check that there is no IS A relationship between class Test & T then why it can't chek same for interface reference type.
    Can you please explain the rationale?

    Hi I am new bie in java,
    Following is my code.
    public class Test {
    public static void main(String[] args) {
    Test test = new Test();
    System.out.println(test instanceof T);
    System.out.println(test instanceof I);
    interface I {
    class T {
    }Compiler shows error at line
    System.out.println(test instanceof I);.
    but not at System.out.println(test instanceof
    T);.
    If compiler can check that there is no IS A
    relationship between class Test & T then why it can't
    chek same for interface reference type.
    Can you please explain the rationale?I guess, since all the classes are derived from "Object" base class, thats y the classes (Test & T) are being compared. But the interface does not extend from the Object class..

  • What is the Java exponent operator??

    In Visual Basic, the exponent operator is signified by a hat "^". How can I denote an exponent in Java?

    There is none. Use Math.pow(base, exponent)

  • Java Post-Operation Plugin

    We are running Sun One Directory Server 5.2.
    I have the distinct honor of inheriting a number of Post-Operation plug-ins written by a person who just left the company. Unfortunately, this person was also the only person that knew how they worked.
    These plug-ins were written with Java. The only documentation I have found thus far have been for c programs. Is there a manual available with how to build/deploy post-operation plug-ins written in Java?

    Sun Directory Server 5 (and 6.0) only exports a C API for its plug-in interfaces.
    I've never heard of any customer having written DS post-operation plug-ins in Java. I'm surprised and curious to hear that it actually happened.
    Regards,
    Ludovic.

  • Large Java 2D operations...

    Hi all,
    Im relativly new to drawing graphics with Java 2D so bare with me, I have created a basic CAD type program and thrilled with what I have so far but the problem is I have come across a problem which is that with hundreds of points (with lines drawn between them) drawn up on a 800 x 600 JPanel (with a black painted background) and I have worked out a system where although your not actually panning across real coordinates (6 digit coordinates) but the program is calculating where they should be in relation to the current view onscreen including changing the scale. The problem is as you may already have guessed is speed, everytime you pan, scale or do anything its not too quick and this also slows down the reaction speed of the general GUI too (buttons etc.).
    I have read around and so but I was wondering if there was any efficient or a 'proper' way to handle such an operation, I know about hardware accelarated graphics but they are for images only I understand?
    Also if the program is told to draw lines that are outside the extents of the JPanel does this have a significant effect too?
    There may be no solution to this problem but I know and accept there is alot I dont know or understand about Java 2D so before trying to come up with a different system I would like any feedback from some of the smart people on here.

    MarksmanKen wrote:
    Thanks for the information, I shall look into this and see what I can do.
    I found one way to help which is to cut out using the BigDecimal class for drawing calculations and stick to doubles (accuracy doesnt have to be procise for drawing the display really), the problem is that I require the user/program to retrieve accurate coordinates from the display (JPanel) using the location of the cursor position, in my mind I cant see how this is possible but they seem to have achieved it in commercial CAD programs some how, does anyone have any ideas?
    I have managed to retrieve the X and Y using a custom class that implements both MouseListener and MouseMotionListener (for drag, movements and mouse presses) but this returns an int which isnt accurate enough and I was aiming for a 3 decimal place double, this may be stupid but is it possible to split a pixel into fractions?It's been a while since I've looked at anything like AutoCad or any of the other packages, but I seem to recall that they give you points of interest--intersecting points or beginnings of curves or transitions. They do that with a point to click--that way they are precalculated.

  • ARGENT:error in java.exe operating server (after updating remote dbase)

    Hello,
    I am getting big trouble in java.exe which is running server program.
    interface : swings
    windows: NT 4.0
    database: MS access97
    jdk 1.3 (jsdk2)
    Dr. watson of NT reporting the error in java.exe(of server) that application error has occured and this is happening every time after i update or write something into the database. Currently i am doing it on localhost m/c.Error: "the instruction at "0x77b3cd19"
    referenced memory at 0x77b3cd19".The memory could be read/"
    //server code
    import java.rmi.*;
    import java.rmi.server.*;
    public class LoginServer {
    public LoginServer() {
    try {
    Login c = new LoginImpl();
    Naming.rebind("login", c);
    } catch (Exception e) {
    System.out.println("Trouble: " + e);
    public static void main(String args[]) {
    new LoginServer();
    //Remote functions implementation
    import java.rmi.*;
    import java.rmi.server.*;
    import java.sql.*;
    public class LoginImpl extends UnicastRemoteObject implements Login
    public LoginImpl() throws RemoteException
    super();
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    } catch(Exception e) { System.err.print("Exception: ");
    System.err.println(e.getMessage());}
    //register new user take name and password as arguement and creates
    // new user and set status OFF (ie user not logged in)
    public int NewUser(String n,String p) throws RemoteException
    String url = "jdbc:odbc:Authentic";
    int i=2;
    Connection con;
    Statement stmt;
    ResultSet rs;
    try {
    con = DriverManager.getConnection(url, "anything", "anything");
    stmt=con.createStatement();
    rs = stmt.executeQuery("SELECT NAME FROM TAUTHENTIC");
    while (rs.next()) {
    String nam = rs.getString("NAME");
    if((n.equalsIgnoreCase(nam)))
    i=1;
    rs.close();
    stmt.close();
    con.close();
    break;
    f (i==2) {
    stmt.executeUpdate("INSERT INTO TAUTHENTIC "+"VALUES'"+n+"','"+p+"','OFF')");
    i=3;
    rs.close();
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    return i;
    //verifying usre and password and then checking status if off turns on else cant verify.
    public int VerifyUser(String s,String p) throws RemoteException
    { int i=0;
    String url="jdbc:odbc:Authentic";
    String status="OFF";
    Connection con;
    Statement stmt;
    ResultSet rs;
    try {
    con = DriverManager.getConnection(url, "anything", "anything");
    stmt=con.createStatement();
    rs = stmt.executeQuery("SELECT NAME, PASSWORD, STATUS FROM AUTHENTIC");
    while (rs.next()) {
    String nam = rs.getString("NAME");
    String pas = rs.getString("PASSWORD");
    String sta=rs.getString("STATUS");
    if((s.equalsIgnoreCase(nam))&&(p.compareTo(pas)==0))
    if(status.compareTo(sta)!=0)
    {i=5; break;}
    if((s.equalsIgnoreCase(nam))&&(p.compareTo(pas)==0)&&(status.compareTo(sta)==0))
    System.out.println("Hi " +nam + " you are in our stock program now");
    i=1;
    break;
    if(i==0)
    System.out.println("Sorry either user dont exist or invalid user name or password");
    rs.close();
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    return i;
    //changes status each time user logged in or logged off
    public void cstatus(String name,String status) throws RemoteException
    String url="jdbc:odbc:Authentic";
    Connection con;
    Statement stmt;
    try {
    con = DriverManager.getConnection(url, "anything", "anything");
    stmt=con.createStatement();
    stmt.executeUpdate("UPDATE TAUTHENTIC SET STATUS ='" + status + "' WHERE NAME LIKE '" + name + "'");
    stmt.close();
    con.close();
    catch(Exception ex){ System.out.println("Exception: "+ex.getMessage());}
    i have used swings to call these functions. Updation is happwning but also bringing runtime server application halt.
    //if u need i can mail u my GUI client file from where i am making my RMI connections. my email is [email protected]. Please reply back as soon as possible as i am working on a java project of software agents and have to complete it by this month.
    thanx and bye for now

    Format this mess.
    http://forum.java.sun.com/faq.jsp#format

  • Java bytecode operation 'invokevirtual' does not keep consistency

    I have following codes.
    public class Parent {
    @Override
    public int hashCode() {
    return 0;
    public class Child extends Parent {
    public void test() {
    this.toString();
    this.hashCode();
    As you see in the above codes, Child inherits toString() from Object and hashCode() from Parent. Bytecode operation of Child#test is as following.
    ALOAD 0: this
    INVOKEVIRTUAL Object.toString() : String
    ALOAD 0: this
    INVOKEVIRTUAL Child.hashCode() : int
    RETURN
    I think if invokevirtual calls Object.toString(), it should call Parent.hashCode() for consistency. or, Child.hashCode() called, then Child.toString() should be called.
    However, invokevirtual does not keep its consistency if and only if target method is inherited by Object.
    Only that case, invokevirtual calls method in the Object. For other cases, invokevirtual calls method in current class.
    I want to know why this happens.

    I think if invokevirtual calls Object.toString(), it should call Parent.hashCode() for consistencyExcept that it doesn't exist.
    You can't seriously be suggesting that this doesn't work correctly.

Maybe you are looking for