Strange understanding of transient keyword

Hi,
I'm currently studying for the SCJP exam and came across the following question.
"What can be done so that a Portfolio object can be serialized while preserving the state of the Bond objects contained in Portfolio?"
class Bond
    String ticker; double coupon; java.util.Date maturity;
class Portfolio implements Serializable
    String accountName;
    Bond[] bonds;
public class TestClass {
    public static void main(String[] args) throws Exception{
     Portfolio portfolio = // get portfolio somehow.
     // serialize porfolio
}One of the proposed solutions is "Implement readObject and writeObject methods in Portfolio and read and write the state of Bond object explicitly."
But I find the solution quite strange
class Bond  // does not implement Serializable
    String ticker = "bac"; double coupon = 8.3; java.util.Date maturity = new Date();
class Portfolio implements Serializable
    String accountName;
    transient Bond bonds = new Bond[]{ }; // must be transient because it cannot be serialized
    private void writeObject(ObjectOutputStream os) throws Exception{
     os.defaultWriteObject();
     os.writeObject(bonds.length);
     //write the state of bond objects
     for(int i=0; i<bonds.length; i++) {
          os.writeObject(bonds.ticker);
          os.writeDouble(bonds[i].coupon);
          os.writeObject(bonds[i].maturity);
private void readObject(ObjectInputStream os) throws Exception{
     os.defaultReadObject();
     int n = os.readInt();
     this.bonds = new Bond[n];
     //read the state of bond objects.
     for(int i=0; i<bonds.length; i++) {
          bonds[i] = new Bond();
          bonds[i].ticker = (String) os.readObject();     
          bonds[i].coupon = os.readDouble();
          bonds[i].maturity = (java.util.Date) os.readObject();
What I'm slightly confused is if the variable bonds is defined as transient, how can one write out the state explicitly?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Even given that Bond isn't serializable and Portfolio has-an array of bonds, it would have made more sense to stick the serializing code in a BondSerializer class, rather than embedding it in Portfolio. That way you could test it separately and reuse it outside of Portfolio.
Oh, this is a test question. Never mind...

Similar Messages

  • Can we use transient keyword with methods of class?

    I just knew that the keyword transient is being used to ignore the Java serialization for variables.
    Could we use this for class methods??

    makpandian wrote:
    I dude i am preparing myself for SCJP6.
    Therefore i asked so.
    I apologize for my mistake.No need for an apology. Rather than simply memorizing the factoid of whether or not the transient keyword may be applied to methods, take the time to understand what transient means. If you remember the purpose of marking a member transient, you'll have no problem with answering correctly on the test.
    Good luck!
    ~

  • Transient Keyword

    what is the use of transient keyword ?any one can help me...

    http://www.google.com/search?q=Transient+keyword
    gurnah
    null

  • What is the use of transient keyword

    never read any java tutorial with the transient keyword explained

    the transient keyword means that the value of that variable will not be written to a file, or send across a stream (something like that). It has something to do with security issues. I've never used it myself, this is just what I remember reading somewhere.

  • Serialization & transient attributes

    Hello,
    I'm very new to Java programming and this site, so I apologize if this question has already been asked numerous times. I have to do a project for my intro to java class that is suppose to have binary file I/O in all of our classes we have to do. All of the classes are serializable, however, one of the classes extends another class which is not serializable. I thought that if I put the transient keyword in front of all the calls to the super class that that would allow for proper serialization but when I try to compile my code it tells me "illegal start of expression" if i do something like say :
    public Example(){
    transient super();
    this.attribute1=" ";
    this.attribute2=" ";}
    So does this mean that I can call on the super class constructor when it's not serializable in its subclass that is serializable and there won't be a problem?
    another question that is an extension of the first:
    This super class has two properties for example String title and int numTitles so would you ever need to have attributes in the subclass that account for these properties? If so is the representation below appropriate? When I compiled it I didn't receive any errors.
    transient MainExample title;
    transient MainExample numTitles;
    I understand the concept of serialization but I still don't seem to get how to work with it completely, especially with dealing with nonserializable properties as well. So if anyone can help me get this concept and how to take it and translate it into proper coding/tell me why what I have here is wrong, I would GREATLY appreciate it!

    Thanks for clearing up what exactly transient should be in front of, which makes sense because we also have to override the writeObject and readObject method calls and make appropriate changes to these now that the class extends a nonserializable class.
    In your #4 you said to serialize properties of a super class follow the example code, so does that mean even if the super class isn't serializable some of its properties can still be?
    We originally used text file I/O in the project before this and now we've been asked to change these reads and writes with the binary file I/O, like I stated before, so I've already done that with the method readObject() & writeObject(Object obj) already defined in for ObjectInputStream and ObjectOutputStream. So to override these calls I must pass in the properties defined in the current class and just omit the properties in the super class? or do i just place them in here and put them in as transient? or still define them as I have placed here?
    private void writeObject(java.io.ObjectOutputStream oos){
    oos.writeBoolean(this.someproperty);
    oos.writeDouble(this.someproperty);
    oos.wrtieInt(this.someproperty);
    oos.writeObject(this.someproperty) ; *this would be in place for the attribute of an array of objects. I'm not sure that this is allowed seeing as how it's inside of a writeObject
    oos.writeInt(super.getSomeProperty());
    oos.writeUTF(super.getSomeProperty());
    }

  • How to model parent child relationship with DPL? @Transient?

    Hello All,
    I want to model a parent entity object with a collection of child entities:
    @Entity
    public class Parent{
    @PrimaryKey
    String uuid;
    List&lt;Child&gt; children;
    @Entity
    public class Child{
    @PrimaryKey
    String id;
    I know that the DPL won't support automatic persistence where it'll recursively go through my parent bean and persist my children with one call. Is there a way of applying the equivalent to JPA's @Transient annotation on "children" so I can persist the children manually and have the engine ignore the collection?
    If not and I want to return to the user a Parent with a List named "children," do I have to create a new object which is identical to Parent, but doesn't have the BDB annotations and manually assemble everything? If possible, I'd like to avoid defining redundant objects.
    Thanks in advance,
    Steven
    Harvard Children's Hospital Informatics Program
    Edited by: JavaGeek_Boston on Oct 29, 2008 2:22 PM

    Hi Steven,
    The definition of persistence is here:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/Entity.html
    And includes this: "All non-transient instance fields of an entity class, as well as its superclasses and subclasses, are persistent. static and transient fields are not persistent."
    So you can use the Java transient keyword. If that isn't practical because you're using transient in a different way for Java serialization, see the JE @NotPersistent annotation.
    In general a parent-child relationship between entities is implemented almost as you've described, but with a parentId secondary key in the Child to index all children by their parent. This enables a fast lookup of children by their parent ID.
    I suggest looking at this javadoc:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/SecondaryIndex.html
    as it describes all types of entity relationships and the trade-offs involved. The department-employee relationship in these examples is a parent-child relationship.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to create email message filter that will AND multiple keywords in the message body

    Greetings,
    I am using BlackBerry Desktop Manager (version 4.3.0.17) and I need a filter that will match ALL keywords in the body of a note rather than ANY one of a list of keywords. I understand that separating keywords with a semicolon will match on any one of them, but I would like to match on ALL keywords that may be interspersed throughout the body of the email. In other words, I understand that the semicolon works like an OR connector. I need a connector that works like an AND.

    Hi bik,
    >> how to use the F keys to apply the tagging mentioned below and the direction of how to do the tagging and make the tag invisible in a text editor but not the text file. 
    It is unclear to me. Like you mentioned F keys, how does it work for?  And Could you show us some code with a simple sample or a capture? It could be better to help us understand more.
    In addition, I found a related thread
    Tag editing in a WPF TextBox. Not sure if it is useful for you. Thanks.
    Have a nice day!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Bug with Lightroom 4? - Big problem in the keyword list!!

    Hello guys,
    I am Rafael Rojas, a nature and landscape photographer. This is my first post, trigered by a quite bothering problem I am having with my LR...So hello everybody!
    I upgraded to LR 4 a week ago. Today I realized many of the keywords I have installed in Lightroom do not appear on the keyword list (basically all keywords after the letter S). Moreover, half of the keywords which appear on the list are not editable: that is, I cannot assign them to the selected image (by clicking on the left box), or I cannot double click them or right click them to get the Edit panel. All the rest of keywords (those which appear on the list on top), can be edited and there is no problem.
    When I export the keywords as a .txt file (in metadata, export keywords) I can see that all the keywords are there. When I try to write some of them on the box LR recognize them and adds them automatically. However, I just cannot see them on my keyword list or just cannot edit them.
    The reason I want to edit the keywords is because many of them got desactivated while upgrading (something more people have reported). Right now, I cannot send my images to my stock galleries, since many of my important keywords are not active, and I just cannot edit them...
    Can you help me please?
    thanks so much!!
    rafael

    Well, 64 bits.
    And yes, it seems when I erase one keyword, the list "shows" one more below...so it seems the problem is related to a certain limit in number.
    That would be still a problem I could live with, the big problem tough is that many of the keywords got "deactivated" alone by Lightroom (see problem here described http://www.backyardsilver.com/2012/02/strange-behavior-with-capitalized-keywords/) and that means I NEED to edit some keywords which are really important and which are not active. Otherwise, when I export the images those keywords are not embedded...
    Any thoughts?
    Rafa

  • Use of transient

    by learning i came to know that use of transient variable may increase the performance for a web application,
    But i am not very clear where exactly i have to use transient.
    suppose this is my class,
    public class ConServ extends HttpServlet {
         transient private  Vector allNodeVC;
         transient private  Vector allNodeVC1;
         //database acess class
                    transient private Connection conn;
         transient private DB2Pool db2Pool;
         //xml class
                    transient private  XmlClass map;
         transient private  XmlClass ws;
    }the HttpServlet class implements java.io.Serializable,
    now if i use "transient " for the upper vaiables will it effect in execution time?
    and what will be the diffrent using and without using transient in this case?

    debdutta wrote:
    jbish wrote:
    if you need that object as part of the state of the object you are serializing then transient would not be a very good choice. can you please explain this a more? i don't have much idea about object serialization,
    and in my upper example, so i can use transient keyword,
    those variables are not used to read or write in fileSerialization is used to store objects or "send" them from one place to another using streams.
    Transient variables, and hence the object they reference if not primitives, do not become part of that stream.
    public class Point {
        private int x;
        private int y;
    }Now, in the above example, x and y are part of a Point object's state (a rather important part :). If x and y are made transient then those variables would not become part of the stream. The Point object would not be of much use without those two variables.

  • Hierarchical Keywords in Filter

    Hello Everyone!
    I have just moved from Windwos PSE8 with Organizer to PSE8 on Mac with Adobe Bridge. I am trying find my way in the Bridge application. Have searched and watched many videos on it over the internet but I still have one thing that is driving me nuts.
    I realized that I could inport and understand my hierarchical keyword structure and have them showed up in the keywords panel (or whatever it is called) in an hierarchical way).
    But when I try to use filter and filter my photos based on the keywords I can only see the deppest level word. For example, if I hava a Category of WildLife/Animal/Cat I can only see the keyword "cat". I may have another keyword like Toys/Fabric/Cat and in this case if I only specify the "cat" keywork I will end up with photos from both real and toy cats....
    How can this be handled? One of the features that I loved from Organizer was the ability to seach based on differente hierarchical keywords.
    Thanks a lot.
    Paulo

    iPhoto doesn't support hierardhical keywords.  Only Aperture does. We don't know what Apple's plans are for updates to iPhoto as we're just users like yourself but you can put in a feature request to Apple via http://www.apple.com/feedback/iphoto.html.

  • [JPQL] Howto pass proprietary SQL keywords to the DB?

    Hi,
    Is there any way to pass proprietary SQL keywords to the database without the JPA implementation complaining?
    In my case I would like to use PostgreSQL's "OFFSET" and "LIMIT" keywords in a subquery, however Hibernate complains because it doesn't understand the OFFSET keyword.
    Thank you in advance, Clemens

    linuxhippy wrote:
    I would really try to avoid native queries if possible somehow :/Is it really such a big concern? I can think of two reasons that it would be:
    - you use something like HSQL as a drop-in database for unit testing purposes
    - you want to keep the option open to switch DBMS implementation
    The first I can understand but is easily circumvented with some mock code override magic, the second I would say is no issue as it is a very bad idea to switch DBMS anyway, even if you use an ORM layer that technically makes it possible.
    Just a thought, I really wouldn't spend ages trying to work around a problem just because maybe perhaps you never know somewhere in some unknown point in time you might just need to spend 5 minutes to locate and change a line of code.

  • Keyword compatability

    Sorry if this has been covered already but I can't find what I'm looking for by searching. Can someone please either explain or point me to an easy-to-understand explanation of keyword compatability across programs. I use iPhoto very little but I am seriously considering switching over to it. My concern is that the keywords won't show up outside of iPhoto. I use Photoshop CS2 a lot. I currently use iView Media Pro for organizing but I have also tried Lightroom Beta and Bridge and I am considering, but have not used, Aperture. If I am going to switch to iPhoto, I would like any keywording that I do in the program to be recognized in Adobe programs (especially if I stop using iPhoto in the future) Is that possible? I understand there are some standards issues going on with XMP and IPTC Core, none of which make sense to me. A beginners guide to metadata and what not would be appreciated.

    Chet:
    Welcome to the Apple Discussions. You're right in that iPhoto keywords stay in iPhoto. They are stored in the AlbumData.xml file and not written to the actual file. There is a way to get them written to the actual file. It involves using iView MediaPro in it's demo mode (good for 21 days). Check out Tutorial #1. It may be a one time thing as the demo is only good for 21 days. I use iView as my primary along with iPhoto on the same set of source files. I have iPhoto in it's alias mode so there's only one set of source files on my HD. Any edits made by iPhoto will not touch the original files and not be seen by iView. However, any edit by iView will be recognized by iPhoto when it uses the full sized image file in books, slideshows, etc. However, the thumbnail will remain the same.
    Do you Twango?

  • How to add keywords

    I'm having a problem getting my keywords into my homepage.
    I'm using Dreamweaver MX2004 with my Mac PowerBook G4 and used the
    insert command>HTML>Head Tags>keywords to enter my
    kewords. The codein my file looks like this:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
    Transitional//EN"
    http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <META NAME="keywords" CONTENT="Mount Tamborine, Mt.
    Tamborine,ceramics,gallery,art
    gallery,pottery,artists,nature,jewelry">
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    <title>mountain dreams atelier</title>
    but in both Foxfire and Safari, after loading my homepage and
    looking at the source code, I get this:
    <HTML><HEAD>
    <META NAME="description" CONTENT="mountain-dreams.net">
    <META NAME="keywords" CONTENT="">
    </HEAD>
    <FRAMESET border=0 rows="100%,*" frameborder="no"
    marginleft=0 margintop=0 marginright=0 marginbottom=0>
    <frame src="
    http://www.moon-song.net/mountain-dreams/"
    scrolling=auto frameborder="no" border=0 noresize>
    <frame topmargin="0" marginwidth=0 scrolling=no
    marginheight=0 frameborder="no" border=0 noresize>
    </FRAMESET>
    </HTML>
    I don't understand why the keywords don't appear in the
    source code in Foxfire or Safari . Can anyone help me to get my
    keywords listed properly and also give me some advice about how to
    get my homepage listed in Explorer and other browsers when they
    enter my keywords. Also, I've heard that some browsers limit the
    number of browsers limit the number of allowable keywords. Any
    information about that would be helpful, too.
    thanks very much, Hillel

    > I'm having a problem getting my keywords into my
    homepage.
    Keywords are for the content on the page, not for the keyword
    meta tag,
    which is ignored by the major search engines.
    Also -
    <FRAMESET border=0 rows="100%,*"
    You are looking at the FRAMESET code, not the code on the
    individual frames,
    which is likely where you have added your keywords. If you
    don't understand
    this distinction, then a) you probably shouldn't be using
    frames in the
    first place, and b) you should read up on frames and all the
    reasons why one
    wouldn't want to use them.
    The reason for using or not using frames should be based on
    a) your site's
    needs, and b) your willingness to accept the potential
    problems that frames
    can create for you as developer and maintainer of the site
    and for your
    visitors as casual users of the site.
    I am down on frames because I believe that they create many
    more problems
    than they solve.
    Judging from the posts here, and the kinds of problems that
    are described,
    the kind of person most likely to elect to use frames is also
    the kind of
    person most likely ill-prepared fo solve the ensuing problems
    when they
    arise. If you feel a) that you understand the problems and b)
    that you are
    prepared to handle them when they occur, and c) that you have
    a need to use
    frames, then by all means use them.
    As far as I know, the most comprehensive discussions of
    frames and their
    potential problems can be found on these two links -
    http://apptools.com/rants/framesevil.php
    http://www.tjkdesign.com/articles/frames/
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "hillel" <[email protected]> wrote in
    message
    news:[email protected]...
    > I'm having a problem getting my keywords into my
    homepage. I'm using
    > Dreamweaver MX2004 with my Mac PowerBook G4 and used the
    insert
    > command>HTML>Head Tags>keywords to enter my
    kewords. The codein my file
    > looks
    > like this:
    > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
    Transitional//EN"
    > "
    http://www.w3.org/TR/html4/loose.dtd">
    > <html>
    > <head>
    > <META NAME="keywords" CONTENT="Mount Tamborine, Mt.
    > Tamborine,ceramics,gallery,art
    gallery,pottery,artists,nature,jewelry">
    > <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    > <title>mountain dreams atelier</title>
    >
    > but in both Foxfire and Safari, after loading my
    homepage and looking at
    > the
    > source code, I get this:
    > <HTML><HEAD>
    > <META NAME="description"
    CONTENT="mountain-dreams.net">
    > <META NAME="keywords" CONTENT="">
    > </HEAD>
    > <FRAMESET border=0 rows="100%,*" frameborder="no"
    marginleft=0 margintop=0
    > marginright=0 marginbottom=0>
    > <frame src="
    http://www.moon-song.net/mountain-dreams/"
    scrolling=auto
    > frameborder="no" border=0 noresize>
    > <frame topmargin="0" marginwidth=0 scrolling=no
    marginheight=0
    > frameborder="no" border=0 noresize>
    > </FRAMESET>
    > </HTML>
    >
    > I don't understand why the keywords don't appear in the
    source code in
    > Foxfire
    > or Safari . Can anyone help me to get my keywords listed
    properly and
    > also
    > give me some advice about how to get my homepage listed
    in Explorer and
    > other
    > browsers when they enter my keywords. Also, I've heard
    that some browsers
    > limit the number of browsers limit the number of
    allowable keywords. Any
    > information about that would be helpful, too.
    >
    > thanks very much, Hillel
    >

  • Common Keywords for Multiple Libraries

    Hello,
    I have a number of iPhoto libraries, each of which has its own set of Keywords. I now want to use a single set of Keywords to all the libraries. Is there a way to do this without having to manually edit the Keyword preferences for each library?
    Thanks.
    Mike

    Hello Terence,
    I have no idea who Kevin is! Sorry about that. Now that I have the name straight, maybe I can get my message straight!
    I understand that the keywords are part of the iPhoto database. My goal is for all my libraries to share a common list of keywords. Specific pictures in a library would be assigned applicable keywords from the common list. Thus, keywords for particular pictures will be different in almost all cases. This difference is why I don't see how to avoid having to assign the specific keywords on a picture by picture basis.
    Thanks for the Keyword Manager link. It gets great reviews and I think it could be very helpful for what I am trying to do. However, KM 1.4.1 fails to install on my iBook G4, OS 10.4.11. I have posted this to Bullstorm and it looks like I need to install SIMBL in order for KM to install. From my web searches it looks like SIMBL could lead to headaches with future software upgrades. After I update my keywords, I plan to upgrade from iPhoto 6 to iPhoto 8 and then later this year I will move to OS 10.5. Assuming no other changes do you think this will lead to problems with SIMBL?
    Thanks for your help and patience!
    Mike

  • Timeline, keyword tween

    Sorry if this is a stupid question but I don't understand what the keyword tween does in the following code and would greatly appreciate it if someone could explain it to me!:
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.scene.shape.Circle;
    import javafx.scene.paint.Color;
    import javafx.animation.Timeline;
    import javafx.animation.KeyFrame;
    import javafx.animation.Interpolator;
    def circle: Circle = Circle {
                centerX: 40
                centerY: 70
                radius: 25
                fill: Color.GREEN
    Timeline {
        keyFrames: [
            KeyFrame {
                time: 4s
                values: circle.translateX => 0.0
            KeyFrame {
                time: 5s
                values: circle.translateX => 165.0 tween Interpolator.LINEAR
    }.play();
    Stage {
        height: 600
        width: 600
        scene: Scene {
            content: circle
    }

    It's required to indicate which interpolation is to be used for this variable. Here it's LINEAR so the whole "tween Interpolator.LINEAR" is actually useless as LINEAR is the default interpolation.
    As for the meaning related to animation, yhou may want to read here [http://en.wikipedia.org/wiki/Tweening] and here [http://en.wikipedia.org/wiki/Interpolation_(computer_programming)]

Maybe you are looking for

  • I cannot restore my iphoto library from Time Machine

    I have lost my iphoto library.  I am trying to restore it from a backup and it was located in the My Pictures folder.  When I try and restore it, there is a big red circle with a dash in it saying I don't have permission to open the folder it is in. 

  • Customer Account Group missing

    Hi Gurus, In our customer master record, the Account Group field is blank(though as I understand, it is a mandatory field). Can someone suggest a way in which we can populate this field in the customer master record.

  • Same dimensions in one application

    Hi experts; My question is about the same dimensions in one application. I have customer dimension and customer_z dimension.There is no problem when enter bpc for excel. If i want to open dynamic table screen or  evdre function in blank sheet , the s

  • How create a bucket in PPM 6.0?

    Hi! Opened link Portfolio management - Portfolio structure and i see buckets list but there is no button to create it. This is wrong place to create buckets or i need more rights to do it?

  • Using SXPG_CALL_SYSTEM  to execute Unix 'MV' command not working

    Here is the code (method - params begin with "p_").  This returns no error but yet the file is not moved (called in a test program).  Any ideas? DATA: lv_sourcepath TYPE rlgrap-filename,         lv_targetpath TYPE string,         lv_fname      TYPE r