Final keyword and return type ...

static byte m1() {
final char c = 'b';
return c; // THIS IS FINE NO COMPILER ERROR
static byte m2() {
char c = 'b';
return c; // COMPILER ERROR
The first return type is LEGAL, but the secoond type is not because it is not final. Why is this the case? Going from a char to a byte is a down conversion. Why does the compiler allow it for a final variable and dis-allow it for the other variable?

i am curious... what is this one about ?See section 5.2 of the JLS, regarding assignment conversion:
Assignment conversion occurs when the value of an expression is assigned (�15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (�5.1.1), a widening primitive conversion (�5.1.2), or a widening reference conversion (�5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:
The expression is a constant expression of type byte, short, char or int.
The type of the variable is byte, short, or char.
The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

Similar Messages

  • Help needed understanding final keyword and  use 3

    Hi Everyone,
    I have been studying a book on multi-threading and have inadvertently come accross some code that I don't really understand. I am wondering if anybody can explain to me the following:
    1). What effect does using the final keyword have when instantiating objects, and
    2). How is it possible to instantiate an object from an interface?
    public class BothInMethod extends Object
         private String objID;
         public BothInMethod(String objID)
              this.objID = objID;
         public void doStuff(int val)
              print("entering doStuff()");
              int num = val * 2 + objID.length();
              print("in doStuff() - local variable num=" + num);
              // slow things down to make observations
              try{
                   Thread.sleep(2000);
              }catch(InterruptedException x){}
              print("leaving doStuff()");
         public void print(String msg)
              String threadName = Thread.currentThread().getName();
              System.out.println(threadName + ": " + msg);
         public static void main(String[] args)
              final BothInMethod bim = new BothInMethod("obj1");  //Use of final on objects?
              Runnable runA = new Runnable()      //Creating objects from an interface?
                   public void run()
                        bim.doStuff(3);
              Thread threadA = new Thread(runA, "threadA");
              threadA.start();
              try{
                   Thread.sleep(200);
              }catch(InterruptedException x){}
              Runnable runB = new Runnable()
                   public void run()
                        bim.doStuff(7);
              Thread threadB = new Thread(runB, "threadB");
              threadB.start();
    }If you know of any good tutorials that explain this (preferably URL's) then please let me know. Thanks heaps for your help.
    Regards
    Davo

    final BothInMethod bim = new BothInMethod("obj1");  //Use of final on objects?
    Runnable runA = new Runnable()      //Creating objects from an interface?          
         public void run()               
                                    bim.doStuff(3);               
    };Here final is the characteristics of bim reference variable and it is not the characteristics of class BothInMethod
    This means u cannot use bim to point to some other object of the same class
    i.e, u cannot do this
                       final BothInMethod bim = new BothInMethod("obj1"); 
                       bim  =  new   BothInMethod("obj2");  This bim is a constant reference variable which will point only to the object which it is initialized to
    and not to any other object of the same class later on.
    How is it possible to instantiate an object from an interface?Regarding this yes we cannot create an object from an interface but
    but here it is not an interface u are providing the implementation of the interface Runnable
    as
    new Runnable()
    }This now no longer stays an interface but now it is an object that implements the interface Runnable

  • About return type and parameter type in IDL

    I don't know how to define return type and parameter type in
    operations in a module which are not listed in predefined in
    IDL. can I define these types as java class?
    can someone help me where a tutorial about this in detail can
    be found?
    thanks a lot

    My understanding is that if something is not in the IDL definition, then as far as the CORBA system is concerned it doesn't exist.
    Therefore any methods you create in a class that implements an IDL defined interface, that are outside that interface, are completely free and outside the CORBA system.
    The parameters and return types of these 'local native' methods should be java classes. All methods and variables outside the IDL spec will only be visible to the local JVM.
    ciao
    Jim
    PS - there is a zip file containing a very long and fairly messy demo of this behaviour at http://clio.mit.csu.edu.au/subjects/itc327/Asg2Demo.zip
    it has an html file which describes using additional non-IDL 'local native' methods for implementing a save/load function

  • Stub generated in Jdev9i for webservice with 'Vector' return type

    Hi,
    In the OAF page that I am developing, I am trying to consume a web service generated in SAP PI using Jdeveloper. My Jdeveloper version is 9.0.3.5(I need to use this version since I need to deploy the OAF page in EBS11i). The stub generated based on the WSDL is given below.
    import oracle.soap.transport.http.OracleSOAPHTTPConnection;
    import org.apache.soap.encoding.soapenc.BeanSerializer;
    import org.apache.soap.encoding.SOAPMappingRegistry;
    import org.apache.soap.util.xml.QName;
    import java.util.Vector;
    import org.w3c.dom.Element;
    import java.net.URL;
    import org.apache.soap.Body;
    import org.apache.soap.Envelope;
    import org.apache.soap.messaging.Message;
    * Generated by the Oracle9i JDeveloper Web Services Stub/Skeleton Generator.
    * Date Created: Tue Jan 25 16:12:55 IST 2011
    * WSDL URL: file:/C://Working/XXXXXXX/RegConsComplaint_OB.wsdl
    public class RegConsComplaint_OBServiceStub
      public RegConsComplaint_OBServiceStub()
        m_httpConnection = new OracleSOAPHTTPConnection();
      public static void main(String[] args)
        try
          RegConsComplaint_OBServiceStub stub = new RegConsComplaint_OBServiceStub();
          // Add your own code here.
        catch(Exception ex)
          ex.printStackTrace();
      public String endpoint = "http://XXXXXX:8000/sap/xi/...../RegConsComplaint_OB";
      private OracleSOAPHTTPConnection m_httpConnection = null;
      private SOAPMappingRegistry m_smr = null;
      public Vector RegConsComplaint_OB(Element requestElem) throws Exception
        URL endpointURL = new URL(endpoint);
        Envelope requestEnv = new Envelope();
        Body requestBody = new Body();
        Vector requestBodyEntries = new Vector();
        requestBodyEntries.addElement(requestElem);
        requestBody.setBodyEntries(requestBodyEntries);
        requestEnv.setBody(requestBody);
        Message msg = new Message();
        msg.setSOAPTransport(m_httpConnection);
        msg.send(endpointURL, "http://sap.com/xi/WebService/soap1.1", requestEnv);
        Envelope responseEnv = msg.receiveEnvelope();
        Body responseBody = responseEnv.getBody();
        return responseBody.getBodyEntries();
    }I am wondering whether I will be able to use this stub generated by Jdeveloper since the input type is 'Element' and return type is 'Vector'; while in the Jdeveloper documentation the supported "primitive XML Schema types and arrays of primitive XML Schema types as parameters and return values for web services" do not include either of the two.
    Regards,
    Sujoy

    Hi Sujoy
    I have been having big problems consuming microsoft sharepoint webservices using jDeveloper 9i.
    Problems with jdk version compatability with jDev and NTLM authentication (Sharepoint).
    so switching to db connection using utl_http.
    Can you pls send me the code set for reference at [email protected]
    thanks.
    Regards
    Sachin

  • Column Function Return Type Number is forcing to cast to Decimal

    Hi - I am using Oracle 11g Release 11.2.0.2.0 and ODP.NET 4.112.3.0.
    Whenever I am trying to execute a package query with column function and return type is number, it is throwing cast exception whenever I am trying to cast it as GetInt32.
    The workaround we have for now is to get it decimal and cast to Int32, this is going to be painful moving forward because it means that we have to check each of our packages and need to know if each package has column function and do this special casting.
    Is this a known bug?

    Oracle Number is 6.
    Run the below script to your machine and the sample code below so you can see what I am talking about.
    --drop table aninalfarm;
    --drop table birdfarm;
    --drop public synonym animalfarm;
    --drop public synonym birdfarm;
    --drop public synonym birdfarm_Pkg;
    --drop public synonym animalfarm_Pkg;
    create table animalfarm
            (code                                 NUMBER(6),
            description                        varchar2(10));
    create table birdfarm
           (code                               number(6),
           description                         varchar2(10));
    create public synonym  animalfarm for db.animalfarm;
    create public synonym  birdfarm for db.birdfarm;
    grant select, delete, insert, update on  animalfarm to public;
    grant select, delete, insert, update on  birdfarm to public;
    delete from animalfarm;
    delete from birdfarm;
    commit;
    insert into animalfarm (code, description) values(111122, 'Horse');
    insert into animalfarm (code, description) values(111133, 'Chicken');
    insert into animalfarm (code, description) values(111144, 'Cow');
    insert into animalfarm (code, description) values(111155, 'Pig');
    insert into animalfarm (code, description) values(111166, 'Sheep');
    insert into birdfarm (code, description) values(222, 'Pigeon');
    insert into birdfarm (code, description) values(333, 'Sparrow');
    insert into birdfarm (code, description) values(444, 'Chickadee');
    insert into birdfarm (code, description) values(555, 'Blue Jay');
    insert into birdfarm (code, description) values(666, 'Loon');
    commit;
    create or replace package birdfarm_Pkg is
    function get_key_from_desc(bird_name_in in birdfarm.description%type) return number;
    end birdfarm_Pkg;
    create or replace package body birdfarm_Pkg is
    function get_key_from_desc(bird_name_in in birdfarm.description%type) return number is
    RETURN_VALUE birdfarm.code%TYPE;
    BEGIN
           select code into RETURN_VALUE from birdfarm where description = bird_name_in;
           return RETURN_VALUE;
    end get_key_from_desc;
    END birdfarm_Pkg;
    create or replace package animalfarm_Pkg is
    --region Define Record Type for Strong Type REF CURSOR
    TYPE AnimalFarmRecord is
      RECORD(
                      code animalfarm.code%type,
          description animalfarm.description%type,
                      birdfarm_code birdfarm.code%type
    --endregion
    TYPE animalfarmCur is REF CURSOR RETURN AnimalFarmRecord;
    procedure get_code_two_ways(cur_OUT OUT animalfarmCur);
    end animalfarm_Pkg;
    create or replace package body animalfarm_Pkg is
    procedure get_code_two_ways(cur_OUT OUT animalfarmCur) is
    BEGIN
      open cur_OUT for
           select animalfarm.code,
                  animalfarm.description,
                  birdfarm_pkg.get_key_from_desc('Pigeon') birdfarm_code
           from animalfarm
           order by code;
    end get_code_two_ways;
    END animalfarm_Pkg;
    create public synonym birdfarm_Pkg for db.birdfarm_Pkg;
    grant execute on birdfarm_Pkg to public;
    create public synonym animalfarm_Pkg for db.animalfarm_Pkg;
    grant execute on animalfarm_Pkg to public;
    See the sample code below:
                 var conn = new OracleConnection(OraDB);
                conn.Open();
                conn.ClientId = "Sample";
                var command = new OracleCommand
                                      Connection = conn,
                                      CommandText = "DB.animalfarm_Pkg.get_code_two_ways",
                                      CommandType = CommandType.StoredProcedure
                command.Parameters.Add(new OracleParameter
                                       ParameterName = "cur_OUT",
                                       OracleDbType = OracleDbType.RefCursor,
                                       Direction = ParameterDirection.Output
                OracleDataReader dr = command.ExecuteReader(); // C#
                dr.Read();
                var code =dr.GetInt32(dr.GetOrdinal("Code")); //This is ok
                var description = dr.GetString(dr.GetOrdinal("Description"));
                var codeError = dr.GetInt32(dr.GetOrdinal("birdfarm_code"));//Throw invalid cast exception
                                                                            //because it is column function
                conn.Close();
                conn.Dispose();

  • How does "Unflatten From String" take a type and return a value of that type?

    http://zone.ni.com/reference/en-XX/help/371361E-01/glang/unflatten_from_string/
    How exactly does the "type" argument for "Unflatten From String" work? I need to create a VI that takes a type, passes it as an argument to several calls of the "Unflatten From String" function, and returns an array containing elements of the type originally passed. The "Unflatten From String" function seems to do some magic though, because the type of the "value" that it outputs changes depending on the type it is passed as input. How do I do the same magic in my VI?
    Ultimately, what I need to accomplish is an unflatten-list operation. Given a type T and a byte string of length L (which contains a concatenation of T elements that are flattened to their bytes), create a VI that unflattens all the types in the string and return an array of length (L / sizeof(T)) that contains each type.
    Note: performing the unflatten-list operation is trivial, but I cannot for the life of me figure out how to do it in a VI that takes a type and returns an array of the appropriate type. By the way, my data is being given to me from another source, so please don't bother suggesting that I should be flattening an array using LabVIEW's "Flatten To String" function in the first place. My data is not given in LabVIEW's array format: http://zone.ni.com/reference/en-XX/help/371361B-01/lvconcepts/flattened_data/
    Thanks a ton!
    -Wakka

    Take a look at this example:  You can see that the flattened string contains several bytes.  The first four bytes contain the length of array (number of elements).  Since the data type is U32, the next 32 bits (4 bytes) contains the value of the first element, and so on.  Could you possibly use this scheme to do what you want to do?  Other data types present different outputs.  You would have to experiment with them.
    - tbob
    Inventor of the WORM Global

  • T-SQL and CLR types for return value do not match

    Hi I am trying to create a CLR function to call a webservice, the CLR function return data type is double, whether I try
    to create this as a table valued funcion or a scalar to return a distance travelled value I am receiving the error below. I've tried changing data types around in the CLR side and the SQL side but keep receiving the same error message, any help would be appreciated,
    Thank you,
    [Microsoft.SqlServer.Server.SqlFunction(Name = "DistanceCalc")]
    public static Double DistanceCalc(Double SrcLat, Double SrcLong,
    Double DestLat, Double DestLong)
    MileageWS ws = new MileageWS();
    ws.Url = "http://test.isp.ca/Distance.asmx";
    int intUom = 0; // 0 = Mile, 1 = KM
    RouteType RouteMethod = RouteType.Practical;
    Requester RequestedFrom = Requester.LinkRoute;
    Double distance;
    distance = ws.GetDistanceInfoForLonLat(SrcLat, SrcLong, DestLat, DestLong, intUom, RouteMethod, RequestedFrom);
    return distance;
    CREATE FUNCTION DistanceCalc
    @SrcLat as float, @SrcLong as float,
    @DestLat as float, @DestLong as float
    RETURNS TABLE (Distance float)
    External NAME CLRfunctions.RIFunctions.DistanceCalc
    GO
    Error received when try to Create function ...
    1, Level 16, State 2, Procedure pcMiler, Line 6
    CREATE FUNCTION for "pcMiler" failed because T-SQL and CLR types for return value do not match.

    You defined at table-valued CLR function, but I think you meant to define a scalar CLR function. That might be the cause of the error.
    RETURNS TABLE (Distance float)
    should be
    RETURNS (Distance float)

  • How comples return types and parameters are mapped

    Hi all!
    I want to know how complex return types and parameters in a java interface gets mapped to wsdl? for example how would the wsdl for the following interface shall look like:
    interface ComplexReturns{
       java.util.Date getLuckyDate(java.util.Date DoB);
       myPack.MyClass getMyClass();
    }

    Hi,
    - In your application module, make a public method that returns an arry, for example an arry of strings[]
        public String[] returnTwoVals(){
            String[] returnvals = {"1","2"};
            return returnvals;
        }- expose this method in the application module
    - in the user interface drag/drop the returnTwoVals method on a page and choose to create a button.
    - double click the button to generate the binding code
        public String commandButton_action() {
            BindingContainer bindings = getBindings();
            OperationBinding operationBinding =
                bindings.getOperationBinding("returnTwoVals");
            Object result = operationBinding.execute();
            if (!operationBinding.getErrors().isEmpty()) {
                return null;
            return null;
        }- you can access the values in the arry by adding this code after the Object result =...
       String[] vals = (String[])result;
       System.out.println(vals[0] + " - " + vals[1]);

  • Can you explain when using keywords and addding them to various clips pressing ctrl and a number eg. 1 or 2 it simply closes down FCPX.  Just to the dock as would th yellow -sign. As you gather I am new to this program having only used Final Cut Express 4

    Can you explain when using keywords and addding them to various clips pressing ctrl and a number eg. 1 or 2 it simply closes down FCPX.  Just to the dock as would the yellow -sign.  I am new to this program having only used Final Cut Express 4 previously.
    iMac (early 2009) 24in 2.93GHz 4GB 1066MHz DDR3 SDRAM (To be upgraded ot 8GB in the nextfew days) os x 10.7.2 Lion
    Re: Why don't my arrows on the time line operate and allow me to move to the start and end of the timeline. Iam using the trial version 

    Check System Preferences. I think Control-1 is used by something in the OS now. Switch it off. It's a major p[ain the way the OS is taking over more and more of the keyboard, allowing less options for application use.

  • Somewhere my "T" key is set as a keyword and everytime I type a t, I have a blank search open up with a tab. Impossible to use for email.

    Somewhere my "T" key is set as a keyword and everytime I type a t, I have a blank search open up with a tab. Impossible to use for email.

    Is it only T? Does pressing N open a new window, and does R reload the page?
    The most likely reason for this is that the CTRL key is held down - see [[Keyboard shortcuts]] for information on what should happen when keys are held down together.
    If a key isn't stuck or being held down, an extension could be the cause. See [[Troubleshooting extensions and themes]] to troubleshoot.

  • IS Retail - POS sales and return movement type issue

    Hi,
    We are facing issue whlile doing POS sales and return, when sales transaction data transfer to ECC from POS its create Idoc and material document.
    When I look the material document for sales its showing movment type 252 instead of 251, as same in return material document 251 instead of 252,
    When I look the cofiguration settings are perfect in SPRO.
    How to resolve this issue and what changes need to be done
    regards
    Satish

    Satish,
    Check following IMG settings;
    IMG - Sales and Distribution - POS interface - inbound - Aggregated Sales Control
    IMG - Sales and Distribution - POS interface - Inbound - Movement type-dependent control of sales as per receipt
    Bye - Muralidhara

  • POS sales and return movement type Issue

    Hi,
    We are facing issue whlile doing POS sales and return, when sales transaction data transfer to ECC from POS its create Idoc and material document.
    When I look the material document for sales its showing movment type 252 instead of 251, as same in return material document 251 instead of 252,
    When I look the cofiguration settings are perfect in SPRO.
    How to resolve this issue and what changes need to be done
    regards
    Satish

    Satish,
    are you sure that you applied the right logic regarding signs in the POS inbound?
    In WPUBON the Field E1WPU02-VORZMENGE must be negative so the POS inbound will consider this line item as sales and would put 251 als movement type if the sign is not minus it would put 252.
    With the WPUUMS it is the same.
    Are you using WPUBON01 or WPUUMS?
    Regards Carsten

  • Rmic and "contains an invalid return type."

    Hello,
    since two days, rmic does not compile anymore. rmic is called via an Ant job like this:
    <javac srcdir="${src}" destdir="${bin}" depend="true">
    </javac>
    <rmic base="${bin}" includes="../**/*.class" iiop="true" idl="true">
    </rmic>
    And I get errors like
    [rmic] error: Class Session contains an invalid return type.
    in the Eclipse output console. On the other hand, the Session interface looks like this:
    public interface Session extends Remote {
    public Enumeration enumerateLocks() throws RemoteException;
    [more Methods]
    (yes, all methods throw RemoteException)
    If I comment out all methods of Session, other messages appear, such as:
    [rmic] error: Class ....AccessService contains an invalid argument type in method findSession.
    [rmic] error: Class Loader contains an invalid return type.
    [rmic] error: Class ....Service contains an invalid argument type in method init.
    All classes compile fine with both Jikes and the Eclipse compiler.
    Thanks for any help,
    Johann

    Sorry, even if I comment out Enumeration, rmic will not compile the classes. To me it looks like something in the interface for Session is wrong, but I dont know what it is...
    public interface Session extends Remote {
    public Unique sessionID() throws RemoteException;
    public long sessionCreated() throws RemoteException;
    public long sessionDestroyed() throws RemoteException;
    public void destroySession() throws RemoteException;
    public int actionsPerformed() throws RemoteException;
    public Enumeration enumerateActions() throws RemoteException;
    public Lock createLock(Reference ref) throws RemoteException, LockedException;
    public Lock createLock(Reference ref, long milliseconds)
    throws RemoteException, LockedException;
    public void releaseAllLocks() throws RemoteException;
    public Enumeration enumerateLocks() throws RemoteException;
    public boolean isDestroyed() throws RemoteException;
    If I comment out all methods in Session, I can compile Session with rmic, but other errors appear:
    [rmic] error: Class ...AccessService contains an invalid argument type in method isValidSession.
    [rmic] error: Class Loader contains an invalid return type.
    [rmic] error: Class ...Service contains an invalid argument type in method init.

  • DLL return type and parmaters

    I must access a DLL developped by VC++ via LV6i with the 'Call Library function'. Everythimg is fine, but the DLL function return type is bool, and I don't find the bool data type in the 'Call library parameter'.
    Secondly, I must pass parameters to this DLL function. Parameters type are : std::vector and GUID. How can I pass this type of parameters ??
    Function is : bool MyFunction (const GUID &guidMyGuid, std::vector &MyVector).
    Thanks in advance.

    You can't, you have to create a CIN that reshapes this parameters to something LabView understand.

  • Trouble defining an interface return type and parameter

    This is what I have so far
    interface Display {
       //Excel
       public HSSFRow createRow(HSSFSheet sheet);
       public HSSFWorkbook createContainer();
       //Pdf
       public Document createContainer(Document document);
       public Document createRow(Document document);
    }Really what I want is one method declaration called createRow() that has an unknown return type and an unknown input parameter type. Is there a way to accomplish this? I will have two classes implement this interface. An Excel class and a PDF class. Those two classes will contain the correct implementations of createContainer() and createRow().
    For example my Excel class will contain this
    public HSSFRow createContainer(){
    return new HSSFWorkbook();
    }and my pdf class will look something like this
    public Document createContainer(Document document){
    return new Document();
    }My main class then can do something like this:
    Display display;
    if(input.equals("xls")){
    display = new Excel();
    }else if(input.equals("pdf")){
    display = new Pdf();
    //Here I can call the correct method to build the outer container
    display.createContainer();What I'm trying to do is have reuse all my algorithms and just have generic calls to create the main container, rows, etc.I had a previous post on this but have created a new one thats more specific to interfaces because ideally I'd like use interfaces here if possible, but not if it will get more complicated than its worth.

    What generic things do you wish to be able to do with all documents? Whatever those things are, they are what should be defined in either an interface or abstract class.
    Here is an example (without any error checking), though it's not the only approach you could take:
    public interface ForumKidDocument {
         public void nextRow();
         public void addTableCell(String cellContent);
         public void save(File file);
         // add whatever other methods you want all documents to be able to do
    public class ExcelForumKidDocument implements ForumKidDocument {
         private HSSFWorkbook workbook;
         private HSSFSheet worksheet;
         private HSSFRow currentRow;
         private int row;
         private int col;
         public XLSForumKidDocument() {
              this.workbook = new HSSFWorkbook();
              this.worksheet = workbook.createSheet();
         public void nextRow() {
              this.currentRow = this.worksheet.createRow(row++);     
              col = 0;
         public void addTableCell(String cellContent) {
              HSSFCell cell = currentRow.createCell(col++);
              cell.setCellValue(cellContent);
         public void save(File file) {
              //TODO:  save workbook to the given File
    public class PDFForumKidDocument implements ForumKidDocument {
    }Then in your outer method, you work with ForumKidDocument instances, calling only ForumKidDocument methods, without having to know anything about the inner workings of the document type.

Maybe you are looking for

  • [b]Can't not run the Oracle Universal Installer (Oracle8.1.7 for Linux) on

    I have a problem when try to install Oracle8i Release 8.1.7 Enterprise Edition on RedHat Linux 7.3. After I do the pre-installation tasks, i enter the command (runs as the oracle user): $ /tmp/Disk1/runInstaller I wait for the one minute and then not

  • Parallel processing in ODI

    Hi experts, I have 30+ files in text format, that hold partitions of the same table. These partitions can/must go through the same processing in parallel, and then must be appended back to a single large file. I'd have no problem designing the transf

  • Remembering passwords for certain sites

    I have an iPad with iOS 4.2.1, brand new (2 days old). I notice in Safari that passwords are saved for sites where the username/password are entered on the page. However, for sites that have you enter the username/password in a popup dialog box, they

  • Xp will not boot

    xp will not boot, last known configuration will not load? help please

  • HT4314 It will not let me open to log in

    When I click on the Game Center icon it will not open.