Final Method Parameters

I've discovered I don't understand final method parameters as I thought I did. The language spec says you can declare a parameter as final, which I would have thought meant the method can't change it. But it turns out the called method can change it. In the following code, the change() method modifies the Test parameter quite easily.
What am I misunderstanding here? If final doesn't keep the parameter from being modified, what does it do?
public class Test
private int privateValue = 0;
* Stores the private value.
* @param privateValue The value to store.
public void setPrivateValue(int value)
   privateValue = value;
public static void change(final Test test)
   test.setPrivateValue(3);
   test.setPrivateValue(4);
* Program entry point
* @param args Command line arguments
public static void main(String[] args)
   Test test = new Test();
   Test.change(test);
   System.out.println("Done");
}

"Ahh, I see," said the blind carpenter, as he picked up his hammer and
saw. I was indeed misunderstanding the use of final. It doesn't protect the
reference object from changes, only the reference variable itself. Sigh...Just to be sure, is this your way of saying "I don't understand those explanations"?
Look closely now :-)
public class Test
private int privateValue = 0;
public void setPrivateValue(int value)
   privateValue = value;
public static void change(final Test test)
   test.setPrivateValue(3); //this line does not even attempt to change the variable's value
   test.setPrivateValue(4); //neither does this one
  //incidentally and irrelevantly, they do ultimately change the value of another variable; a private field of the object pointed to by "test"
   //the next line DOES attempt to change the variable's value
   test = new Test(); //this does not compile because test is declared final
   test = null; //and again!
public static void main(String[] args)
   Test test = new Test();
   Test.change(test);
   System.out.println("Done");
}Variables (and parameters) hold primitives or references (they do not hold objects). For reference variables, they are either null or they point to an object. "final" applies to variables, not to the objects they may point to.
If final
doesn't keep the parameter from being modified, what
does it do?So (I hope) you see, it does just that, generate a compile time error when the parameter is being modified.
What am I misunderstanding here?I don't know. That's exactly what everyone else said.

Similar Messages

  • Actual Benefits of final methods and final parameters

    I know that a lot of this depends on the JVM and the actual code, but I was wondering what the actual real world advantage was of using final methods and final parameters.
    I use a business and data layer for my program to interact with the database. So all of the methods in these classes are public and static. I was just wondering if it would be benefical to make all of these methods final and all of the parameters final also. I won't ever be making subclasses of these classes, so is this worth doing?
    Thanks,
    Dave Johansen

    On the point of final, this should always be a design decision. That is, does it make sense to allow your class to be overridden? Making classes and/or methods final is a big barrier to future enhancements and extendability - so only make soemthing final if you haver a specific reason for doing so.
    Any performance issues should not take a high precedence in this decision - and in any case the difference in making something final will be non-existant for all practical purposes.
    How about volatile?
    I get the meaning of synchronized but
    volatile?Volatile is a keyword that tells the JVM it can't optimize / inline serctions of code that use certain variables. You may not realise it, but the JVM takes your bytecode and chops them up and re-arranges them at runtime, to boost performance. This can sometimes have dangerous consequences in a mutlithreaded environment, so by adding the volatile keyword you are saying to the JVM (or specifically HotSpot) not to perform any "code magic".
    Here's a simple example:
    public class TestClass {
        private boolean check = false;
        public void setTrue(){
            check = true;
        public void check(){
            check = false;
            if(check){
                System.out.println("Will this ever print?");
    }Obviously the string will never print in a single threaded environment. However, in a multithreaded environment, is is possible that a thread could call setTrue() between another thread setting the value to false and performing the if() check. The point is that due to runtime optimization, Hotspot may realise that check is always false, so completely remove the code section with the if block. so regardless of the value of the boolean, the code may never be entered.
    One solution is to declare the boolean check as volatile. This tells the JVM that such optimizations are not allowed and then it is entirely possible for the string to be printed.
    One curiousity, off-topic:
    is there a way for jvms instantiations to see each
    other?Have you looked into RMI?

  • Access fo Method parameters to Anonymous Class ?

    Can somebody please provide some more information on the statement below? I am also searching for some sample code implementations of it. It would help the cause better.
    +"Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined. "+
    Thanks in Advance

    We're concerned here with "local" classes, i.e. classes defined inside methods (not all anonymous classes are local, and not all local classes are anonymous).
    The thing about local classes is that, unlike local variables etc., instances of a local class may survive the method returning. For example a local class might be a listener which gets added to a swing component, it could be a Runnable that get's launched as a thread.
    Local classes get to access local variables and parameters of the method in which they are declared but the variables or parameters have to be declared final because, since the class needs to be able to access the value of the local variable even after the method exits, and the variable ceases to exist, what actually happens it that the value of the variable is copied into a special field of the anonymous class, and if the variable could be changed after the class was defined, the two copies would then disagree.

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • Final methods in abstract classes?

    Hi, why is it possible to define a final method in an abstract class? The theory behind a final method doesn't say that a final method couldn't be overridden?
    Marco

    So it's formally correct but it doesn't have any
    sense, does it?You sound very confused. A final method in an
    abstract class has just the same semantics and
    makes just as much sense as in a non-abstract
    class.
    The semantics of a final method is simply that
    it cannot be overridden in subclassed. Both
    abstract and non-abstract classes can be
    subclasses. So why do you think there should be any
    difference?Actually i was confused now it's clear. I was too binded to the concept that the extending class SHOULD(not for a formal reason, but for a 'design' one) write the implementation of the methods defined in the abstract class. Now i see that, actually, by defining a final method in an abstract class we are defining our design as implemented and clients(i.e. subclasses) can only use it.
    Thank you,
    Marco

  • Automatic output of method parameters

    Hi,
    Sometimes I find myself System.out'ing all parameters of a method. Is there a one-step way to do this? A one-liner that will output all method parameters (using reflection I guess) of the method the code is running in.
    for e.g
    public Car makeCar(Color carColor, int noOfWheels){
    System.out.println(outputAllParametersOfThisMethod();
    }Console:
    carColor=Blue
    noOfWheels=4
    Appreciate any help that I can get!

    Hi,
    You can map these all parameters in Process instruction sheets and operator can view the PI sheet to view the process or qc parameter.
    Find below the link
    [http://help.sap.com/saphelp_47x200/helpdata/en/05/603bc6462311d182b50000e829fbfe/frameset.htm]
    http://help.sap.com/saphelp_47x200/helpdata/en/05/603bc6462311d182b50000e829fbfe/frameset.htm
    Sanjay

  • Urgent pls-AdapterActivatorPOA overrides final method Error

    I am getting the following error when trying to access our reports .jsp files.
    java.lang.VerifyError: class org.omg.PortableServer.AdapterActivatorPOA overrides final method .
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.evermind.util.OC4JSecureClassLoader.defineClassEntry(OC4JSecureClassLoader.java:172)
    etc. . .
    No solutions forthcomming on the web and we have tried everything we can think of. Is this perhaps a java version problem. Seems that 9.0.4 is running java version 1.4.2. We have a staging area with a 9i server. It runs fine (java version 1.3).
    Also of note is that reports test implementation works fine. If we move our files to this location the reports come up. No graphs are displayed but the data is there and no error comes up.
    As a note we have replaced the reports_tld.jar in the ear with the one from the test area and redeployed with no changes (error returns).
    Any explination would be appreciated.
    Rhys Parry

    Hi,
    You need to check the Sampling procedure in QDV2 T-code
    In assignments check for which sampling type and valuation mode you had selected.Becuase you might choosed a valuation type which does not support control chart type.But for MIC you might ticked the chart type in control indicator.
    Manoj.N

  • Final method and final class

    What is final method and final class in abap objects.

    ejp wrote:
    Since that doesn't work--or would overyy complex to implement... would be impossible to implement. Once the method-local copy goes out of existence, ipso facto it can never be changed. This is the whole point.I consider it impossible too, but I'm not a language/compiler/runtime expert, so I allowed for the possibility that there could be some way to do it--e.g. local variables that are references in inner classes live on the heap instead of the stack, or something. My point isn't that it's possible, just that if it were somehow to be done, it would by ugly, so we may as well consider it impossible--it just ain't gonna happen.
    we go with the logic, "Okay, we need to copies, but keeping them in sync is a nightmareNo, it is +meaningless.+No, it's not meaningless. If we have the two copies, and they're not final, then after the inner object is created, the method can continue running, and either the method or the inner object could modify its copy. As far as our code knows, it's the same variable, so there'd have to be some way to keep them in sync. That's either impossible or undesirably complex--like the above, it doesn't matter which--so it's final in order to get past the issue of keeping the copies in sync.

  • Netbeans 6.0 - code completion of method parameters

    I just updated to NetBeans 6.0 and I find the code completion of method parameters very annoying and counter productive.
    It inserts the parameters as keywords when choosing a method from the list after pressing CTRL+SPACE.
    How can I switch this off?
    I searched the options and also the forum but didn't find a solution.

    I know that pressing space or whatever replaces the selected parameter. For a method with a single parameter is not a big problem but this is a poor workaround if a method has more parameters, like eg
    public static String formatDate(Date myDate, String myFormat)
    When typing
    Str.form<CTRL+SPACE,choose method, ENTER>
    it looks like
    Str.formatDate(myDate, errorMessage)
    Although myDate is selected and I can overwrite it, I have to proceed to the next parameter with CTRL+M instead of simply typing a comma. This is very annoying if a method has more parameters and as this annoyance occurs approx. every 5 lines that accumulates.

  • Get method parameters at runtime?

    Hey guys,
    is there a way to get the parameters of a methods parameters at runtime? I have a reference to an object and would like to know which paranmeter does a method have.?
       thx

    Hello
    You can use class CL_OO_CLASS (instance attribute METHOD_PARAMETERS ).
    Regards
      Uwe

  • What is the use of finalized method ..even though

    we know that java has inbuild garbage collector. then what is the need of finalized method.
    can any one give me the answer please

    The original idea was that you could use finalize() to clean up class-variable resources. For example, you might be (shudder) holding on to a database connection in a given object. The idea would be that you could close the connection within finalize().
    However, and I am not totally sure on this, but there seems to be a few issues around finalize() getting called by the garbage collector. There are also a few posts I remember admonishing programmers not to call finalize() explicitly. So, for me at least, I do not use the method and ensure I clean up any resources I have references to manually.
    - Saish

  • Method parameters

    Hello
    I'm usimg this code to get the local variables in case of a method entry:
                error = jvmti->GetLocalVariableTable(method, &entryCount, &localVariableEntry);
                if(error == JVMTI_ERROR_NONE) {
                    jvmtiLocalVariableEntry* entry = localVariableEntry;
                    for(int i = 0; i < entryCount; i++, entry++) {
                        cout << entry->signature << ":" << entry->name << endl;
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->signature));
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->name));
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->generic_signature));
                    } // for
                    jvmti->Deallocate(reinterpret_cast<unsigned char*>(localVariableEntry));
                } else if(error = JVMTI_ERROR_ABSENT_INFORMATION) {
                    cout << "<NO LOCAL VARIABLE INFORMATION AVAILABLE>" << endl;
                } else {
                    cout << "<ERROR>" << endl;
                } // if...else if...elseNow I'm wondering how to find the method parameters in all this local variables...
    Is there a way to get obly the method parameters?
    Thank you very much and with kind regards
    Alexander Schell
    Edited by: EJP on 3/10/2011 20:24: added {noformat}{noformat} tags: please use them.
    Edit: Moved the first code-tag
    Edited by: user3948319 on 03.10.2011 08:02                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Hello and thanks for the answer...
    That was my first assumption...but after running the code I got some puzzling results...here's an example:
    callbackMethodEntry: methodName=reverse methodSignature=(Ljava/util/List;)V methodGenerigPtr=(Ljava/util/List<*>;)V classSignature=Ljava/util/Collections; thread=DestroyJavaVM
    I:i
    I:mid
    I:j
    Ljava/lang/Object;:tmp
    I:i
    I:mid
    Ljava/util/ListIterator;:fwd
    Ljava/util/ListIterator;:rev
    Ljava/util/List;:list
    I:size
    The method entered takes surely one argument - a list...but the list is not the first entry in the array which is created by calling getLocalVariableTable...so I'm a wee bit confused right now...
    I also don't understand under which circumstances the JVMTI_ERROR_ABSENT_INFORMATION error is raised...
    before I forget: Thanks for the tip with the code tags...I looked for something to mark the code but could not find it...
    With kind regards
    Alexander Schell

  • How to get names of method parameters ?

    How to get names of method parameters (Not only their type and value) is it only possible during debugging ??
    for example void myFunction(int a,int b)
    I need the "a" , and the "b" The issiue is about the java.lang.reflect.InvocationHandler ,
    and its method invoke(Object proxy,
    Method method,
    Object[] args)
    throws Throwable
    I Have the parameter objects themself and their types using method.getParameters() , this is fine ,, but i need the names of the parameters !!!

    If the class file was compiled without debug information included then it is impossible to get the original parameter names, as used in the source code.
    However, If the class file does include debug information, then the method names are hidden deep within the class file. You'd need to parse the class file yourself. Check out a copy of the Java VM Specification for a detailed format of the java class file format.
    It's not a trivial task to parse the java class file, and the VM spec isn't easy reading. You'd nearly be writing a class file disassembler.

  • Can WLW display the real names of method parameters, not arg0, arg1...

    Hello
    I am new to Java development and as I used to work with MS.NET usually rely on parameter names, so that I don't have to read documentations each time I use a method. However I noticed that WLW replaces the names of method parameters with arg0, arg1, arg2 etc. Is there a way to somehow make WLW display the real argument names and not those argX strings?
    Thanks in advance.
    Best regards,
    Vasil Svetoslavov

    In wlw select...
    Tools
    +-- IDE Properties
    --Editor
    Ensure that the following are Checked
    Use Method Completion
    Use Parameter Completion

  • Does final method works like a inline function???

    Hi,
    in c and c++ we have macro and inline functions.
    In java u can not override final methods but My query is
    Does in java final methods wroks like inline methods ?
    Inline means the method call is replaced by method body at compile time so logically it improves the performance.
    I would like to know if final method works like an inkine method up to what extend it really improves the performance.
    Thanks in advance

    It depends.
    In Java it's mostly the VM (the JIT compiler, to be more exact) that handles the optimization. It may or may not inline methods, depending on which gives better performance.

Maybe you are looking for

  • USING LONG ETHERNET CABLE FROM HUB TO VISION BOX

    Hi, just ordered bt vision and wondered if anyone could tell me if it is ok to connect the hub to the vision box with a long Ethernet cable, 20m long. From the video clips on setting the system up they say if over 2 meters you must use power adaptors

  • Cannot get Hostgator email with IMAP to work with Thunderbird

    I have cpanel for VPS hostig with Hostgator.com One of my domains, www.fasttractionmarketing.com has webmail with hostgator wihich is working properly. I have been trying for hours to get email set up with Thuderbird client. I have dlownloaded Thunde

  • Macbook multi-touch functionality with LION OSX

    I know that some of the older MacBooks (2006-07) have multi-touch trackpad. Are some of those models only one or two finger touch? I am wanting to upgrade to Lion OSX and want to make sure the trackpad will support three and four finger gestures. And

  • ADF Line Graph

    Hello, I have a graph which i bind to backing bean private List<Object[]> graphTabularData. I am able to get the points from the adf line graph on clickListener only for the data that exist in the private List<Object[]> graphTabularData. Is it possib

  • Problems installing Designer 6.0 on Oracle 8.1.7

    I'm trying to install Designer 6.0 for NT on an Oracle 8.1.7 database running on Win2K. When compiling the package cioue_element_type the server "hangs". I have to shutdown the database to get rid of the process.