Real easy question about defining objects in java

hey guys here is my problem. I am trying to implement an insert() method for my binary tree. i have my node class defined to contain
public T element() {
          return _data;
and then my actual tree class has an instance of this declared to be called runner.
BTreeNode runner;
runner = _root;
The problem occurs when i try to compare what i am inserting (obj) with what i have (runner.element) The actual line of code is
( obj.compareTo(runner.element) < 0 )
i get an error that says "runner.element cannot be resolved or is not a field".
I believe the error comes because i didnt adequately define runner but im not sure how to take care of that. Any suggestions would be most appreciated.
-peter

this is all of the code that has a relation to the error I am getting. The error is found in the BasicBTree class and says
"The method compareTo(T) in the type Comparable<T> is not applicable for the arguments
(Comparable)"
Basic Binary Tree Node class
public class BTreeNode<T extends Comparable<T>> implements Position<T> {
     private BTreeNode<T> _left;
     private BTreeNode<T> _right;
     private BTreeNode<T> _parent;
     private T            _data;
     public T element() {
          return _data;
     }Basic Binary Tree class
public class BasicBTree<T extends Comparable<T>> implements BinaryTree<T> {
public void insert(T obj) {
          BTreeNode runner;
          runner = _root;
          if (obj.compareTo (runner.element()) = null) { // ERROR OCCURS HERE
               _root = new BTreeNode(obj);
          return;   
}the interface posistion
public interface Position<T> {
     public T element();
}

Similar Messages

  • Hopefully an easy question about arrays

    hi there
    is there any way of creating an array of objects that is of unspecified size at the time of creating and then add objects as and when they are read from a file?
    longer explanation:
    i am creating molecule visualization software. the molecule's structure is stored in a text file, ie each line has info on one atom ie 3d coords etc. i'm storing the molecule structure in an object (Molecule.java) which has an array (Structure[]) of atoms (Atom.java). obviously molecules can have any number of atoms in it and you don't know how many until you've gone through the whole file and counted. The only way i can think of doing it is to go through the whole file, coun the atoms, close the file, create the Molecule object with the structure array size of NoOfAtoms and then open the file again and add the atoms as i go through them again. however, i refuse to believe this is the most efficient way of doing it as i have to go throguh the same file twice which brings me back to my original question.
    as i said i'm hopeing there is a simple answer
    cheers

    Use a Collection . Use a Vector, ArrayList or even a Hashtable. You do not need to define the size of these objects and can add and remove Objects from them whenever you want

  • Dispose a user-defined object in Java

    Hello,
    Suppose I have the following loop :
    while ( some_condition) {
    UserDefinedClass abc = new UserDefinedClass();
    // do some work and exit loop.
    Everytime, I enter this loop I instantiate a new object "abc". I am worrying that if I keep doing this, after a while, I will run out
    of memory. Is there a way to dispose a user-defined object? Or is this scenario taken care of by Java garbage collection process?
    Any advice is much appreciated.
    Akino.

    Akino wrote:
    Hello,
    Thank you for your reply.
    I wonder if you could tell me how often Java does its garbage collection?That's pretty unpredictable.
    I ran a test and observed that
    my program's memory usage kept going up and up.If you gave it it 64M, and the most it ever needs at one time is 10M, it can still ramp up to the full 64M, even if it's doing frequent GC. Running GC does NOT mean that the JVM gives the memory back to the OS. It can do that, and I think it does under some circumstances, but there's no guarantee if, when, or how much it will give back. GC only means that the JVM has reclaimed space that is no longer in use by objects. Whether it holds onto that memory for future use or gives it back to the OS is up to it.

  • Easy question about JScrollPane issue

    The problem is I do not understand why it is not possible, or what I am doing wrong to not be able to initialize a JScrollPane with a variable and call it later, real easy to see in the code below.
    NOTE! I CAN use scrollbars, but only without initializing first, am just trying to understand how to properly do this with initialization or if it is not possible.
    Thank you!!!!
    just look for the First 3 commented sections with stars ******
    import java.awt.Container;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SquareIntegers extends JApplet {
         // set up GUI and calculate squares of integers from 1 to 10
         public void init() ///all variables below are LOCAL, because used only in "init()" if needed elsewhere make above in the CLASS
                             //OR SAVE VALUES between calls to the class's methods
                // get applet's content pane (GUI component display area)
              Container container = getContentPane();
              container.setLayout(new FlowLayout());
              //creaing a layout because I wanted to add a scroll pane
              //container.setLayout(new BorderLayout());
              // JTextArea to display results
              JTextArea outputArea = new JTextArea(8, 8);
              // JScrollPane myscrollbar = new JScrollPane( outputArea ); //********************this is line 27 why does this along with line 33 NOT work????????
              // attach outputArea to container
              container.add( outputArea);
              //container.add( myscrollbar); ******************************this is Line 33 why does this along with line 277 NOT work????????
              container.add(new JScrollPane( outputArea ));//***********this is Line 34, if I comment out 27/33, and just use this, scrollbars
                                                                     // work correctly, but I have heard/seems better to "initialize variables first"
              int result; // store result of call to method square
              String output = ""; // String containing results
              // loop 10 times
                   for ( int counter = 1; counter <= 10; counter++ ) {
                   // calculate square of counter and store in result
                   result = square( counter );           //***********************uses the CUSTOM method from line 44
                   // append result to String output
                   output += "The square of " + counter +
                   " is " + result + "\n";
                   } // end for structure
         outputArea.setText( output ); // place results in JTextArea
    } // end method init
         // square method definition...***** This is a CUSTOM method creation..... if "Math.sqrt" was used, we would not have to do this
         public int square( int y )
         return y * y;      // return square of y this is RETURNED to the statement in "init()" that originally invoked the
                             // "square()" method - in this case line 32, where RESULT invoked the METHOD, so "result" gets the value of RETURN
                             // if it were "public int square()" that means the method does NOT return a value
    The general format of a method definition is
    return-value-type method-name( parameter-list )
    declarations and statements
    including "return;" or "return EXPRESSION;"
         } // end method square ALL METHODS must always be created inside the CLASS definition, as this one is... notice the closing
              // CLASS bracket below
    } // end class SquareIntegers

    Thank you!!!
    I think I understand...... since the JScrollPane already assigned itself to the JTextArea....
    when "adding" to the parent container, the only necessary component to call was in fact the JScrollPane with the container.add( myscrollbar); I do not know if this is correct, but I thank you for your help, because this definitely confused me, back to studying :)
    I have it 100% operational, just posting this to say thank you that it worked, and it will help further my and possibly others understanding of this.

  • Easy question about Reformatting

    Hello all,
    I am trying to reformat my HD after I have deleted Windows XP off of a partition. The reason for this is an upgrade to Vista and a larger allotment of HD space. My question is:
    I am using Backup v3.1.1. (v369) and I have FULL backup files of my Home folder, and my Music folder (as backup for my backup) for all my iTunes libraries. These are located on a portable HD. Are these the correct files to have backed up in order to have my MAC the way it was before I started the process? If so, then once the reformatting is complete, how do I get it all back onto my MAC permanently? Will all my apps and tweaks work as before?
    I am sure this is a simple question, however, I have never had to do this with a MAC, and I want to make sure I have all bases covered before I begin this. Any other comments or advice would be greatly appreciated.
    Thanks All!

    You call this an easy question ???
    Just messin with ya
    Your home folder is the most important folder containing your music, documents, preferences etc. but a lot is also stored in the system folder and library folder outside your home folder, if you want to be ensured of an exact copy of your current system the best way to go at this is to clone your system partition.
    The app i use for this is carbonCopyCloner
    http://www.bombich.com/software/ccc.html
    To add to this.. i've heard there is software for the mac that allows you to make adjustments to the size of your partitions without having to format the drive, i don't know the names of these products but i do know that it's very risky to use them, if you decide to use an app like that make sure you have proper backups of everything just in case it goes wrong.
    Message was edited by: Pr0digy V.

  • Easy question about objects

    why with this code;
    private Scanner x;
    public void openfile(){
    try {
    x = new Scanner(new File(chinese.txt));
    why do you say x is a variable at private scanner x and then make x an object? why do both variable and object? the code is from http://www.youtube.com/watch?v=3RNYUKxAgmw
    Edited by: 980099 on Jan 19, 2013 4:30 PM
    Edited by: 980099 on Jan 19, 2013 4:38 PM
    Edited by: 980099 on Jan 19, 2013 4:42 PM

    why do you say x is a variable at private scanner xThe code doesn't actually say it's a variable, but it is. It is a reference of type Scanner. As it isn't initialized in the declaration, its initial value is null.
    and then make x an object? It doesn't. it creates a new Scanner instance and then assigns the reference to 'x'.
    why do both variable and object?You should now be able to see that the question is meaningless.

  • Question about creating Forms in Java.

    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Thanks ....

    HeavenBoy wrote:
    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?Some Oracle Forms fans certainly do. But the truth is that Oracle Forms application tie down all the components in fixed pixels. The typical Swing form can be resized and can function at different screen resolutions. So, when designing a Java form, we don't tend to work on a fixed grid but define the sizes and positions relative to other components. What's more the interface between the form elements and the data is completely flexible, and flexibility means extra effort.
    >
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Most I've tried have been a bit of a straitjacket, but I've recently been using the latest Netbeans offering and it's pretty good. I think the breakthrough was the introduction of the GroupLayout layout manager. This is a layout manager really designed for WYSIWYG form designers (pretty challenging to use hand coded).
    The way these things work is that the class generated contains some methods which cannot be edited by hand, but you can add any amount of your own code without interfering with the generated code. You hook your own code snippets into the generated code, for example you can select a property of an object, say the model of a JTree, and select "user code", then type in an expression returning the TreeModel you want to use.
    With listeners the designer will generate the method signature etc. but you can edit the body of the listener method.
    However I would always recommend that you hand code a form or two before resorting to on of these editors because it's important you understand the code, even where a designer writes it.

  • Question about main difference between Java bean and Java class in JSP

    Hi All,
    I am new to Java Bean and wonder what is the main difference to use a Bean or an Object in the jsp. I have search on the forum and find some post also asking the question but still answer my doubt. Indeed, what is the real advantage of using bean in jsp.
    Let me give an example to illustrate my question:
    <code>
    <%@ page errorPage="errorpage.jsp" %>
    <%@ page import="ShoppingCart" %>
    <!-- Instantiate the Counter bean with an id of "counter" -->
    <jsp:useBean id="cart" scope="session" class="ShoppingCart" />
    <html>
    <head><title>Shopping Cart</title></head>
    <body bgcolor="#FFFFFF">
    Your cart's ID is: <%=cart.getId()%>.
    </body>
    <html>
    </code>
    In the above code, I can also create a object of ShoppingCart by new operator then get the id at the following way.
    <code>
    <%
    ShoppingCart cart = new ShoppingCart();
    out.println(cart.getId());
    %>
    </code>
    Now my question is what is the difference between the two method? As in my mind, a normal class can also have it setter and getter methods for its properties. But someone may say that, there is a scope="session", which can be declared in an normal object. It may be a point but it can be easily solved but putting the object in session by "session.setAttribute("cart", cart)".
    I have been searching on this issue on the internet for a long time and most of them just say someting like "persistance of state", "bean follow some conventions of naming", "bean must implement ser" and so on. All of above can be solved by other means, for example, a normal class can also follow the convention. I am really get confused with it, and really want to know what is the main point(s) of using the java bean.
    Any help will be highly apprecaited. Thanks!!!
    Best Regards,
    Alex

    Hi All,
    I am new to Java Bean and wonder what is the main
    difference to use a Bean or an Object in the jsp. The first thing to realize is that JavaBeans are just Plain Old Java Objects (POJOs) that follow a specific set of semantics (get/set methods, etc...). So what is the difference between a Bean and an Object? Nothing.
    <jsp:useBean id="cart" scope="session" class="ShoppingCart" />
    In the above code, I can also create a object of
    ShoppingCart by new operator then get the id at the
    following way.
    ShoppingCart cart = new ShoppingCart();
    out.println(cart.getId());
    ...Sure you could. And if the Cart was in a package (it has to be) you also need to put an import statement in. Oh, and to make sure the object is accessable in the same scope, you have to put it into the PageContext scope. And to totally equal, you first check to see if that object already exists in scope. So to get the equivalant of this:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart"/>Then your scriptlet looks like this:
    <%@ page import="my.pack.ShoppingCart %>
    <%
      ShoppingCart cart = pageContext.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        pageContext.setAttribute("cart", cart);
    %>So it is a lot more work.
    As in my mind, a normal class can also
    have it setter and getter methods for its properties.True ... See below.
    But someone may say that, there is a scope="session",
    which can be declared in an normal object.As long as the object is serializeable, yes.
    It may be
    a point but it can be easily solved but putting the
    object in session by "session.setAttribute("cart",
    cart)".Possible, but if the object isn't serializable it can be unsafe. As the point I mentioned above, the useBean tag allows you to check if the bean exists already, and use that, or make a new one if it does not yet exist in one line. A lot easier than the code you need to use otherwise.
    I have been searching on this issue on the internet
    for a long time and most of them just say someting
    like "persistance of state", "bean follow some
    conventions of naming", "bean must implement ser" and
    so on. Right, that would go along the lines of the definition of what a JavaBean is.
    All of above can be solved by other means, for
    example, a normal class can also follow the
    convention. And if it does - then it is a JavaBean! A JavaBean is any Object whose class definition would include all of the following:
    1) A public, no-argument constructor
    2) Implements Serializeable
    3) Properties are revealed through public mutator methods (void return type, start with 'set' have a single Object parameter list) and public accessor methods (Object return type, void parameter list, begin with 'get').
    4) Contain any necessary event handling methods. Depending on the purpose of the bean, you may include event handlers for when the properties change.
    I am really get confused with it, and
    really want to know what is the main point(s) of
    using the java bean.JavaBeans are normal objects that follow these conventions. Because they do, then you can access them through simplified means. For example, One way of having an object in session that contains data I want to print our might be:
    <%@ page import="my.pack.ShoppingCart %>
    <%
      ShoppingCart cart = session.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        session.setAttribute("cart", cart);
    %>Then later where I want to print a total:
    <% out.print(cart.getTotal() %>Or, if the cart is a JavaBean I could do this:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart" scope="session"/>
    Then later on:
    <jsp:getProperty name="cart" property="total"/>
    Or perhaps I want to set some properties on the object that I get off of the URL's parameter group. I could do this:
    <%
      ShoppingCart cart = session.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        cart.setCreditCard(request.getParameter("creditCard"));
        cart.setFirstName(request.getParameter("firstName"));
        cart.setLastName(request.getParameter("lastName"));
        cart.setBillingAddress1(request.getParameter("billingAddress1"));
        cart.setBillingAddress2(request.getParameter("billingAddress2"));
        cart.setZipCode(request.getParameter("zipCode"));
        cart.setRegion(request.getParameter("region"));
        cart.setCountry(request.getParameter("country"));
        pageContext.setAttribute("cart", cart);
        session.setAttribute("cart", cart);
      }Or you could use:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart" scope="session">
      <jsp:setProperty name="cart" property="*"/>
    </jsp:useBean>The second seems easier to me.
    It also allows you to use your objects in more varied cases - for example, JSTL (the standard tag libraries) and EL (expression language) only work with JavaBeans (objects that follow the JavaBeans conventions) because they expect objects to have the no-arg constuctor, and properties accessed/changed via getXXX and setXXX methods.
    >
    Any help will be highly apprecaited. Thanks!!!
    Best Regards,
    Alex

  • Theorical question about declaration/definition in java

    Hi, we know the difference between declaration and definition:
    -declaration: no memory is allocated.
    -definition: memory is allocated.
    In C/C++ if we want to define a variable we can make
    int x;or
    int x = 5; (we assign a value too)
    while, if we just want to declare we can make
    extern int x;Is there a way in java to simply declare a variable? According to me just arrays can be declared with
    String[] arrayString;while istructions like
    String myString;are definition as they allocate at least a String reference on the stack...am I wrong?

    Squall867 wrote:
    Hi, we know the difference between declaration and definition:
    -declaration: no memory is allocated.
    -definition: memory is allocated.That's not the definition I learned, back when dinosaurs roamed the earth, men lived in caves and used pterodactyls for airplanes, and computers were made of rocks.
    Is there a way in java to simply declare a variable? According to me just arrays can be declared withThis is a pretty meaningless question.
    In Java, whenever you declare/define a variable (there is no distinction), space is allocated for that variable. It's at least 1 byte for a byte or boolean, at least 2 bytes for a char or a short, at least 4 bytes for an int, float, or reference, and at least 8 bytes for a double or long. A given JVM implementation may actually use more bytes for any given type for word-alignment performance optimization.
    Is there a way in java to simply declare a variable? According to me just arrays can be declared with
    String[] arrayString;
    This declares a reference variable of type reference to array of String. It will occupy at least 4 bytes.
    while istructions like
    String myString;are definition as they allocate at least a String reference on the stack...am I wrong?This declares a reference variable of type reference to String. It will occupy at least 4 bytes.
    Note that an array reference variable is no different than any other reference variable.
    Also note that for any variable, whether it lives on the stack or on the heap depends only on whether it's a member variable or a local variable. If objects are allowed to be created on the stack in future versions of Java, that distinction will get slightly more complex.

  • Question about using objects in SQL query.

    I had posted this question in the SQL/PLSQL forum but I guess nobody took the time to understand exactly what I am asking so I decided to try here hoping to get the answer. So here is the thing:
    I have created generic object type "tree" - the constructor takes as a parameter sql query which returns "node_id" and "parent_node_id" - this is all we need to have a tree. The object has all related to a tree structure member functions and one of them is "oldest_relative" (the tree may not be fully connected - it may be more like a set of many trees, so it's not necessary all nodes to have the same root).
    I also have departments table with the following fields: department_id, parent_department_id, department_name,...
    all records in the table w/out parent_departments (parent_department_id is null) are considered divisions.
    Now if I run the following query:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT_NAME", tree('select department_id "node_id", parent_department_id "parent_node_id" from departments').oldest_relative("DEPARTMENT_ID") "DIVISION_ID" FROM departments
    my question is: Is the tree object created for every row or does Oracle somehow caches the object since the object itself is not changing but only the parameter for the oldest_relative member function.
    The table only has a few hunderd records and I can't see much of a difference in the execution time btw the query above and query like this:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT_NAME", b.t.oldest_relative("DEPARTMENT_ID") "DIVISION_ID"
    FROM departments left join (select tree('select department_id "node_id", parent_department_id "parent_node_id" from departments') t from dual) b on 1 = 1
    where the object is clearly created just ones. (there is probably a better way to do it instead of this join)
    Pls elaborate
    George

    Not exactly sure what the question is...
    As I understand, you are comparing the following two constructor calls:
    +select..  tree('select department_id "node_id", parent_department_id "parent_node_id" from departments').oldest_relative("DEPARTMENT_ID") ... FROM ...+
    +select tree('select department_id "node_id", parent_department_id "parent_node_id" from departments') ... FROM dual+
    These calls are the same (besides the 1st one doing an immediate implicit call to a method of the object being constructed). The number of times these are being called depends on the number of times this SQL projection is applied - and that is determined by the number of rows being projected by the SELECT.
    The latter one is against DUAL which only has a single row. So that constructor is only called once. The former can be against multiple rows. Obviously a single pass through a data set is desirable - which means that the sub-select (use by the constructor) should ideally only be executed once and makes the 2nd method more desirable.
    However, I'm having a hard time understanding why the class and constructor are at all needed. Why pull data from a SQL table into PL memory? As that is where the class will need to cache and store the results of that construction parameter SQL SELECT. And once in PL memory, how does the object effectively access, search and use this cached data?
    PL memory is expensive. It is not sharable.
    PL data structures are primitive - these cannot be compared to SQL structures in the form of tables and columns that can be stored in a number of physical ways (index tables, hash tables, partitioned tables, clustered tables, etc). Cannot be indexed like SQL structures using B+tree, bitmap, function and other indexing methods. Cannot be sorted, grouped, analysed, filtered, etc like SQL structured data.
    It makes very little sense to read SQL data into a class and then deal with that data, cached in expensive PL memory, using primitive PL structures.
    And the same would be true if Java or C# was used. The best place for data is inside the SQL engine. That is the most superior environment for data. It can processes more data, scale better, perform better and offer more flexibility, than pulling data from it and then crunch that data using PL or Java or C#.

  • A question about immutable object: Integer

    import java.lang.Integer;
    public class ImmutableObject {
         public void changeImmutable(Integer x){
              x = x+1;
              System.out.print(x );          
    public static void main(String[] args){
         Integer x = new Integer(1);
         ImmutableObject i= new ImmutableObject();
         i.changeImmutable( x);
         System.out.print( x);     
    Hello everyone,
    Why the output of the program above is 21 rather than 22?
    Is it because of +? Can anyone tell me about this?
    Thanks a lot.
    Kolapig

    Isn't it call-by-reference? All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments. If you pass a double to a method, its parameter is a copy of whatever value was being passed as an argument, and the method can change its parameter's value without affecting values in the code that invoked the method. For example:
    class PassByValue {
        public static void main(String[] args) {
            double one = 1.0;
            System.out.println("before: one = " + one);
            halveIt(one);
            System.out.println("after: one = " + one);
        public static void halveIt(double arg) {
            arg /= 2.0;     // divide arg by two
            System.out.println("halved: arg = " + arg);
    }The following output illustrates that the value of arg inside halveIt is divided by two without affecting the value of the variable one in main:before: one = 1.0
    halved: arg = 0.5
    after: one = 1.0You should note that when the parameter is an object reference, the object reference -- not the object itself -- is what is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. Here is an example to show the distinction:
    class PassRef {
        public static void main(String[] args) {
            Body sirius = new Body("Sirius", null);
            System.out.println("before: " + sirius);
            commonName(sirius);
            System.out.println("after:  " + sirius);
        public static void commonName(Body bodyRef) {
            bodyRef.name = "Dog Star";
            bodyRef = null;
    }This program produces the following output: before: 0 (Sirius)
    after:  0 (Dog Star)Notice that the contents of the object have been modified with a name change, while the variable sirius still refers to the Body object even though the method commonName changed the value of its bodyRef parameter variable to null. This requires some explanation.
    The following diagram shows the state of the variables just after main invokes commonName:
    main()            |              |
        sirius------->| idNum: 0     |
                      | name --------+------>"Sirius"       
    commonName()----->| orbits: null |
        bodyRef       |______________|At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same underlying object. When commonName changes the field bodyRef.name, the name is changed in the underlying object that the two variables share. When commonName changes the value of bodyRef to null, only the value of the bodyRef variable is changed; the value of sirius remains unchanged because the parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line would say "null". However, the variable bodyRef in commonName and the variable sirius in main both refer to the same underlying object, so the change made inside commonName is visible through the reference sirius.
    Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. If the Java programming language actually had pass-by-reference parameters, there would be a way to declare halveIt so that the preceding code would modify the value of one, or so that commonName could change the variable sirius to null. This is not possible. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
    -- Arnold, K., Gosling J., Holmes D. (2006). The Java� Programming Language Fourth Edition. Boston: Addison-Wesley.
    ~

  • Question about Using Objects

    Hi Guys,
    Need some help here with understanding the basics. Basically i'm getting a bit confused on how objects are instantiated and used in java. Firstly an object of a class is instantiated with the following piece of code;
    ClassA obj = new ClassA();This would allow you to use the variable and method of ClassA. Say ClassA has the method set(). You could call it via the obj object with the code;
    obj.set();that I understand. You can also declare an annonymous object which is an object that is only really going to be used once for the purposes of the statement. For example, something like;
    System.out.println(new Date());That I understand too. However what is confusing me is this type of object instantiation;
    public static ClassA obj; You cannot not call the set() method of the ClassA in the same way so why use this? Also this code is confusing me;
    obj = new ClassA();Are you saying that a precreated object is now equal to ClassA. Meaning that you can call its set() method in the same way?
    What do they mean? Why are they used? Can anyone give me an example of how they would be used?
    Any help would be appreciated.

    public static ClassA obj;This is a declaration, basically you are telling the
    computer that you intend to make a "ClassA" object
    and the program will allocate enough memory to hold a
    "ClassA" object, although the object "obj" does not
    actually "exist" at this time. This is why you can't
    use the set() method, because obj doesn't have any
    methods at all since it hasn't fully been created
    yet.
    obj = new ClassA();This is what actually creates the object, according
    to the instructions in the object's "ClassA()"
    method, which is known as a constructor.
    ClassA obj = new ClassA();This statement simply combines the two previous ones
    into one line. You are declaring "obj" to be a
    "ClassA" which allocates memory to store it, and then
    immediately executing the "ClassA()" constructor to
    build a new ClassA and store it in the memory space
    referenced by "obj". Does any of that make sense?
    I'm not exactly a teacher, but I think I understand
    your problem enough to explain it.Yes that does make sense. However i have some more questions now if you dont mind answering.
    If the code
        public static ClassA obj;simply allocates the memory (instantiate) and does not name (declare) the object then why cant you do something like this afterwards;
    obj = new ClassC();or this;
    obj1 = new ClassA();The object doesn't yet exist you only putting memory aside for it. Its only at this point that your naming the object and setting the parameters for it.
    Why bother even allocating memory for the object without actually declaring the object? Surely combing the two statements is more efficient and makes more sense than separating them. Why do you need to allocate the memory and then give it a name?
    Also the following piece of code;
    ClassA objA = obj;Since obj is already intialized as being a new ClassA object, then is this simply declaring and instantiating a new object of type ClassA? And what is the difference between this and;
    ClassA objA = new ClassA();Thank You

  • Where is the best place to ask questions about NetBeans 6 for Java?

    When it comes to Java discussions, all I can think is this forum, but what about Java Desktop Applications using NetBeans IDE 6?
    Question/Query 1:
    I just like to ask how I can make the Database Application Template under the Java> Java Desktop Application> Database Application:
    Well, the the nice Frame with prebuilt components are good, but how can we customize the Window Icon? Has anybody in this forum and particularly Netbeans 6 users encountered the same scenario?
    Question/Query 2:
    How can I make a splash page with such a Database Application template too?

    Hello Andy,
    we talk about Photoshop, or? In this case you should use Photoshop General Discussion
    You will find all the (other) communities by clicking "Adobe Communities" on the top of the window. Please have a look at
    https://forums.adobe.com/welcome (see screenshot) and/or open "All communities"
    Hans-Günter

  • Questions about smart objects in CS3-CS5.

    Hi.
    Two questions.
    When I replace content of smart object in CS2 the content takes the size of previous state of smart object in pixels.
    It was very useful when need to replace some background to another and it autoresized to the new size and proportion.
    For example, when I replace content of smart object with external size 100x90px and 100x90% proportion (can see with Ctrl-T) with file with 200x300px size, i have new smart object with old size 100x90px and new proportion 50x30%.
    When I try to do the same in CS3-CS5 I get smart object with size 160x216px and proportion 100x90%.
    Haw can I return the old behaviour?
    Second.
    In CS2 I use files with a lot of smart objects each of them may consists with some others smart objects and so on.
    But i can`t use this scheme in CS3-CS5 because of very high consumption of scratch memory.
    Very-very simple example. In CS2 create file 4000x3000px, create new layer and draw there black square 300x300px.
    Convert the "square" layer to smart object. Then duplicate it with Ctlt-J 30 times. Save the file and reopen.
    The scratch size is about 280 MB and practically not changing when moving layers with movetool.
    Open this file in CS5. The scratch size is about 2.5 GB and quickly increase to 5 GB and above when i try to move layers. And this is a very simple file.
    If i will try to open several such files in CS5 the amount of useing memory will be fantastic.
    Why there is such behaviour whis memory in cs3-cs5 photoshops?
    PS. sorry for my english. hope you understand me.

    Hi,
    What version of Ps and AI are you using?
    1. In Ps, there's no controls for the AI layer visibilty, but the visibility attributes should be respected.
    2. The placed file is an embedded copy, not a link to an external file. However, there is a script that you might find useful for your purposes. I'm not sure if the Win support improved with CS5.
    http://ps-scripts.com/bb/viewtopic.php?t=3045%20Brilliant%21%21
    regards,
    steve

  • Very easy question about variables

    Can I convert float-variable to String-variable?

    Hi, a very easy way to convert almost anything is
    called "typecasting". It might sound difficult, but
    it isn't.
    You use it like this example
    > String outcome;
    Double input;
    input = 3.54789654587;
    Output = ""+input;
    That's not casting. It's implicit formatting.
    What it does is making an empty string and pasting
    your number behind it. VERY easy! You can do this
    with allmost every type of variables.What it's doing is creating a StringBuffer, appending an empty string to it, then appending the result of calling toString on the Double, which is itself a String. (Though things change a bit in jdk1.5.) It works because StringBuffer.append has versions for each primitive type, and toString exists for all Objects.
    One problem is that it's not efficient -- you're doing a lot of work behind the scenes to do something that can be done much more simply. But the bigger problem is that it's using operators in a roundabout way and with implicit results. So it's sort of a hack. "+" is the append operator for Strings (well it actually comes down to an implicit method call, or several). Putting the double on the right side of that also causes an implicit format. So you're implicitly formatting a value, and then appending it to nothing, to get a result. You're not actually meaning to append, you're meaning to format, but you're using an append operator.
    The more straightforward way to do it is simply to explicitly format it, using the methods already shown on this thread, or using java.text.DecimalFormat.

Maybe you are looking for

  • What is the significance of LOCK INDICATOR in IT0006?

    Hi all, has anyone used lock indicator in IT0006? for what requirement is it used? what is its significance? what r the implications? does it used for any specific HR process? Where else do we find lock indicators in HR master data? thanks in advance

  • ACROBAT 6 DISTILLER - TRUETYPE FONTS

    Okay so here goes.... We use quark to save our quark files as .ps (postscript) files and drag those postscript files to the distiller to create pdf's. The problem is when i send these pdf's created from this mac to a pc and open it up and go under fi

  • Program to maintain table

    Hi Experts, I need a program which is used to maitain the table same as SM30, and i need  to give the select options for this table even.

  • How to view Financial Year details in Scorecard

    Hello all , We are using SSM 7.5 SP 04. We have built a scorecard with monthly KPIs. The financial year for my client is April to March. So , he wants to see the monthly data and the FY data in the scorecard. But , the timeperiod drop down box shows

  • Unable to open LiveCycle-protected pdf document with Reader 9 (ok with Reader 8)

    Hello, I installed a LiveCycle server for the Right management module. But I have the following problem : - I can protect and save pdf documents with Acrobat Pro 8 (connecting with the server LiveCycle Update 1) - I can open the document using a RSA