Primitive Variable Type Casting

Dear all, as I was studying the SCJP Certification book, I notice the following:
This case shows compilation error:
byte a = 3;
byte b = 8;
byte c = a + b;
This case shows no problem:
byte c = 3 + 8;
According to the book, 3 and 8 will be converted to int type. However, the lower one can be implicitly converted to byte, but the upper one cannot be.
Thank you very much.

3 and 8 are compile-time constants (meaning the compiler knows their exact values). Thus the compiler can also figure out 3+8 is 11 and see that it's well within the range of a byte and therefore allow the assignment.
When you add a and b, then the compiler no longer knows for sure what the values are and treats it as if you added any two bytes. For [various reasons|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.2] this will produce an int value, which can't be assigned to a byte without casting it.
The compiler could theoretically notice that a and b have the values 3 and 8, but it generally doesn't do that kind of analysis.

Similar Messages

  • Primitive data type casting

    Hi..
    when I run the following prg, It is throwing exception at line 6.But it is compiling well with line 5. what make difference here.Why cant we do same with long.
    public class Tester {
         public static void main(String[] args) {
    final int i=10;
    final long l= 10;
    short s= i; // line 5
    short s1=l; // line 6
    Can any one clarify the reason.
    Thanks
    Mur

    Oh, but the reason of why the compiler doesn't choke on this:int i = 10;
    short s = i; is because the JVM handles integer values from -127 to 127 differently from larger values. Because you have said int i was final, the compiler knows the JVM will handles the (int)10 as one of these special immutable constant values, and as such it will easily fit in a short.
    A long does not get the same -127 to 127 treatment. A final long will not be associated with an immutable constant at runtime, so the compiler does not assume "final long 10" will fit into a short, and thus gives you a loss-of-precision error.
    Yeah, to you and me we know a (long)10 will fit, but the compiler and JVM can't see the 10 through the long.

  • Type casting of primitive types

    Hi,
    I have two pieces of code. The type casting between them is strange.
    1st snippet
    int i =100;
    byte b = i;This gives an precision error. where as this is allowed
    final int i =100;
    byte b = i;Pls explain as to why is this happening.
    Regards,
    Anand

    The compiler sees that the value is a constant, and that it can't change. And it can therefore validate that the value is within the valid range for a byte.
    /Kaj

  • Could not type cast in java embedding

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    org.xml.sax.InputSource in = (org.xml.sax.InputSource) getVariableData("Invoke_1_getRoutingAndFrameJumpers_OutputVariable","getRoutingAndFrameJumpersResponse");
    Document doc = db.parse(in);
    In the above code I am trying to type cast the variable getRoutingAndFrameJumpersResponse into org.xml.sax.InputSource so that i can parse.
    I am not getting any error during compilation
    but I am unable to type cast some run time error is coming in the line were I am type casting but I am not able to see the runtime error.
    How can I see the runtime error in java embedding, how to type cast a variable into xml so that I can parse it.

    Hi Arun,
    Could you try using the bpelx:rename extension in an assign activity enables a BPEL process to rename an element through use of XSD type casting.
    <bpel:assign>
    <bpelx:rename elementTo="QName1"? typeCastTo="QName2"?>
    <bpelx:target variable="ncname" part="ncname"? query="xpath_str" />
    </bpelx:rename>
    </bpel:assign>
    Cheers
    A

  • Is it possible to make a type cast in TestStand?

    I've got the following problem.
    I use a receive function which waits for an undefined package. (struct package).
    The problem is i can't specify the module with the exaxt package.
    Generally in C i define a Pointer and create enough buffer for it. Is it the same in TestStand?
    Is it possible to make a type cast?
    for example:
    i've got these packages
    struct packet;
    struct  data;
    the function does not know which structure to receive.
    err = receive(buffer,maxlen);
    how do i specify the buffer variable?
    can i create a type "void" with a String to have enough buffer.
    and then to make a type cast, for example "Locals.dataobject = ((data)Locals.buffer)"
    any ideas?
    thx for help

    Unfortunately there is no way to do type-casts in TestStand. What you could do is write a wrapper-dll in C, that has for example two parameters for both possible structs. The dll then takes one of the parameters, does the typecast and passes it on to your original dll.
    From TestStand you can pass the struct(or better container in the "TestStand language") you want to use to the accoridng parameter of the wrapper-dll, leaving the other parameter empty or with some default-value.
    Hope this helps!
    André

  • Runtime conversion of a string value to a primitive data type in java

    can anyone of you give me an idea to convert a string value to a primitive data type during run time...i have the value and the type to which it has to be converted as String values...do you have any idea ,...pls share

    String recvalvalue = inputval;
                    String recvartype = inputtype;
                   if (recvartype.equals("int")){
                   value0 = Integer.parseInt(recvalvalue);
             else
             if (recvartype.equals("double")){
                    value1  = Double.parseDouble(recvalvalue);
             else
             if(recvartype.equals("float")){
              value2 = Float.parseFloat(recvalvalue);
             else
             if(recvartype.equals("Boolean")){
              value3 = Boolean.parseBoolean(recvalvalue);
             else
             if(recvartype.equals("char")){
               value4 = (char)recvalvalue.charAt(0);
            else
            if(recvartype.equals("String")){
              value5 = recvalvalue;
             else
             if(recvartype.equals("byte")){
               value6 = Byte.parseByte(recvalvalue);
                  //listA.add(6, value6);
                  //     listA.g = value6;
             else
              if(recvartype.equals("long")){
               value7 = Long.parseLong(recvalvalue);
             else
              if(recvartype.equals("short")){
              value8 = Short.parseShort(recvalvalue);
             } yes i can do this but the resultant value has to be assigned to a variable of a specific type which is here recvartype .....it has to be done dynamically automatically..if we know what type of data is that we can convert and assign to the type but we donot know when we run the program as the program will be supllied by someone and has to be executed

  • Creation of new primitive data types

    Is it possible to create primitive data types? Or perhaps there's another solution...
    I have a need to work with signed integers represented by more than 128 bits, and would prefer to define such variables as primitive types and be able to use them as such. I have no problem creating "toString()" and friends for convert binary to decimal.
    Thanks in advance.
    Randolf Richardson - [email protected]
    Inter-Corporate Computer & Network Services, Inc.
    Vancouver, British Columbia, Canada
    http://www.8x.ca/

    What about using "BigIntegers"?
    http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html

  • Help needed in data type casting

    I have a java program which will receive data and its type in the String format. During program execution, the data in the String data has to be converted into the respective data type and assigned to a variable of that data type so that it could be used in the program. Programmer may not know the type of data that the value has to be converted into.
    I really got struck up with this. This is a RMI application and one process node is sending the data to another node in the String format and the type of data it should get converted into so that it can be converted into the respective type and used for computation.
    Can you understand what I am asking for ....if you can pls help and it is highly appreciated

    I dont know whether i ahve expressed it correctly
    look at this code
    dataPacket sendtoNode = send.senDatatoNode(inputReq);
    String recnodnum = sendtoNode.nodeNum;
    String recvarnum = sendtoNode.varNum;
    String recvartype = sendtoNode.dataType;
    String recvalvalue     = sendtoNode.dataVal;
    int num;     int type;
    double result;
    // here in this case the result variable type is double
    if (recvartype.equals("int")){
              type = 1;
         result = Integer.parseInt(recvalvalue); will pose problem
         else
         if (recvartype.equals("double")){
              type = 2;
              result = Double.parseDouble(recvalvalue);
         else
         if(recvartype.equals("float")){
              type =3;
              result = Float.parseFloat(recvalvalue); will pose problem
         else
         if(recvartype.equals("Boolean")){
              if ((recvalvalue.equals("true")) || (recvalvalue.equals("TRUE")))
              type = 4;
              result = Boolean.parseBoolean(recvalvalue); will pose problem
         else
         if(recvartype.equals("char")){
              type = 5;
              result = (char)recvalvalue; will pose problem
    else
    if(recvartype.equals("String")){
         type = 6;
              result = recvalvalue; will pose problem
         else
         if(recvartype.equals("byte")){
              type = 7;
              result = Byte.parseByte(recvalvalue); will pose problem
         else
         if(recvartype.equals("long")){
              type = 8;
              result = Long.parseLong(recvalvalue); will pose problem
         else
         if(recvartype.equals("short")){
              type = 9;
              result = Short.parseShort(recvalvalue); will pose problem
         //forvarval varvalue = new forvarval();
         //varvalue.forvarval(recvartype, recvalvalue);
    // this has to be done after sorting the problem of type casting string result = recvalvalue;
    //result = value; //<this will surely give me a problem as i m assigning string to double>??
    send.host(result);
    System.out.println("result received and the result is " +recvalvalue );
    now i need to assign the converted string in to a variable and use in the compuation ..thts where the challenge n not in teh conversion process...

  • Splitting and type casting huge string into arrays

    Hello,
    I'm developing an application which is supposed to read measurement files. Files contain I16 and SGL data which is type casted into string. I16 data is data from analog input and SGL is from CAN-bus data in channel form. CAN and analog data is recorded using same scan rate.
    For example, if we have 6 analog channels and 2 CAN channels string will be (A represents analog and C represents CAN):
    A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 .... and so on
    Anyway, I have problems reading this data fast enough into arrays. Most obvious solution to me was to use shift registers and split string in for loop. I created a for loop with two inner for loops. Number of scans to read from string is wired to N terminal of the outermost loop. Shift register is initialized with string read from file.
    First of the inner loops reads analog input data. Number of analog channels is wired to its N terminal. It's using split string to read 2 bytes at a time and then type casts data to I16. Rest of the string is wired to shift register. When every I16 channel from scan is read, rest of the string is passed to shift register of the second for loop.
    Second loop is for reading CAN channels. It's similar to first loop except data is read 4 bytes at a time and type casted to SGL. When every CAN channel from scan is read, rest of the string is passed to shift register of the outermost loop. Outputs of type cast functions are tunneled out of loops to produce 2D arrays.
    This way reading about 500 KB of data can take for example tens of seconds depending on PC and number of channels. That's way too long as we want to read several megabytes at a time.
    I created also an example with one inner loop and all data is type casted to I16. That is extremely fast when compared to two inner loops!
    Then I also made a test with two inner loops where I replaced shift register and split string with string subset. That's also faster than two inner loops + shift register, but still not fast enough. Any improvement ideas are highly appreciated. Shift register example attached (LV 7.1)
    Thanks in advance,
    Jakke Palonen
    Attachments:
    String to I16 and SGL arrays.vi ‏39 KB

    OK, there is clearly room for improvement. I did some timing and my two above suggestions are already about 100x faster than yours. A few teeaks led to a version that is now over 500x faster than the original code.
    A few timings on my rather slow computer (1GHz PIII Laptop) are shown on the front panel. For example with 10000 scans (~160kB data as 6+2) my new fastest version (Reshape II) takes 14 ms versus the original 7200ms! It can do 100000 scans (1.6MB data) in under 200 ms and 1000000 scans (15MB data) in under 2 seconds.
    I am sure the code could be further improved. I recommend the Reshape II algoritm. It is fastest and can deal with variable channel counts. Modify as needed.
    Attached is a LabVIEW 7.1 version of the benchmarking code, containing all algorithms. I have verified that all algorithms produce the same result (with the limitation that the cluster version only works for 6*I16+2*SGL data, of course). Remember that the reshape function is extremely efficient, because it does not move the data in memory. I have some ideas for further improvements, but this should get you going.
    Message Edited by altenbach on 08-05-2005 03:06 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    StringI16SGLCastingTimer.png ‏48 KB
    StringtoI16andSGLArraysMODTimer.vi ‏120 KB

  • Should Java introduce new primitive data types??

    In Java SE 5.0, many character- related methods (especially in the class Character) handle code points by using int type, i.e. return (code point) type is int, or receive (code point) int as parameter. This leads several problems. First, the variable used for storing returned result should be carefully stated, otherwise confusion may arise. Second, the parameters of method should be carefully ordered, otherwise conflict of method signature may meet.
    By those reasons, I suggest that Java should introduce new primitive data types for handling characters, they are:
    1. wchar
    this type states the variable stores 32-bit UNSIGNED integer, and it could be used to store either the code point, or the UTF-16 code of a character.
    2. ascii
    this type states the variable stores 8-bit UNSIGNED integer, and it could be used to store the code point of a elemental (ascii) character.

    short char, no. Nononono.
    No.
    wchar, I think I'd pref to see Java version 2 come
    out, and that be wchar by default, but that is not
    going to happen.
    I don't see a great need for it at this time.http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504839
    Though I do not think that Java developer would like to change too much program code for using proposed (unsigned) primitive data types, I still believe that Java developer will eventually introduce these types, because it is not efficient to pretend signed integer to unsigned integer, and the success of a programming language is determined by how it can meet the programmers' need.

  • Type casting issue

    Hello All,
    I've a Type casting issue. Could yu please help me resolving it.
    I'm trying to initialize the variable v with sysdate ('mon-dd-yy:hh:mi:ss') but couldn't initialize. I was able to do that in the body but is it not possible to do it in the declaration part?
    I was able to do like this
    DECLARE
      v varchar2(25);
    BEGIN
      SELECT to_char(sysdate,'mon-dd-yy:hh:mi:ss') INTO v FROM dual;
      DBMS_OUTPUT.PUT_LINE(v);
    END;
    Output looks like this: jan-19-12:04:32:11But how to do it in delaration part?
    DECLARE
      v varchar2(25);
      v := to_date(sysdate, 'mon-dd-...') ? ? ?
    BEGIN
        DBMS_OUTPUT.PUT_LINE(v);
    END;Thx
    Shank.

    You don't need to cast a sysdate to a date. It already is a date.
    SQL> alter session set nls_date_format = 'mon-dd-yy:hh:mi:ss';
    Session altered.
    SQL>
    SQL> DECLARE
      2    v varchar2(25);
      3    v_date date:= sysdate;
      4  BEGIN
      5      DBMS_OUTPUT.PUT_LINE(v_date);
      6  END;
      7  /
    jan-19-12:04:46:40
    PL/SQL procedure successfully completed.Hope this helps.

  • TYPE CASTING ERROR

    HI GURU's
    I AM REQUIRED TO GENERATE USER ID AUTOMATICALLY STARTING FROM 0001, 0002, 0003 AND GOES ON INCREMENTING BY 1.
    - I MADE USER ID FIELD OPTIONAL.
    - THEN I CREATED AN ENTITY ADAPTER TO TRIGGER AT PRE INSERT EVENT, TAKING INITIAL VALUE AS 0000 IN A INTEGER VARIABLE.
    - THEN OTHER VARIABLE STORES THE INCREMENTED VALUE OF INITIAL VALUE (INT ADD METHOD).
    - THEN I MAPPED THE ADAPTER RETURN VARIABLE WITH THE ENTITY VALUE USER ID OF USER FORM.
    WHEN I TRY TO CREATE USER IT SAY ERROR IN TYPE CASTING, OBVIOUSLY IT SHOULD SHOW BECAUSE I AM MAPPING INTEGER RETURN VARIABLE WITH THE STRING TYPE USER ID.
    KINDLY SHOW ME THE WAY TO ACHIEVE THIS.
    THANKS A LOT.

    Have you tried searching this on Google.
    See this link:
    http://www.javadb.com/convert-an-int-value-to-string
    In your Entity Adapter code, write few more lines from the method in the above link.
    THEN I CREATED AN ENTITY ADAPTER TO TRIGGER AT PRE INSERT EVENT, TAKING INITIAL VALUE AS 0000 IN A INTEGER VARIABLE.
    - THEN OTHER VARIABLE STORES THE INCREMENTED VALUE OF INITIAL VALUE (INT ADD METHOD).
    - THEN I MAPPED THE ADAPTER RETURN VARIABLE WITH THE ENTITY VALUE USER ID OF USER FORM.

  • Type casting for properties accessed in COM Object

    I have a com object that I need to access which provides my a
    list of addresses in an Array. The object give me a property that
    has a count for the number of addresses and then I have a loop that
    calls the property which contains the address details to get each
    individual address each time passing to the property the INDEX
    value on the loop.
    This errors out each time.
    The error I get is
    Error casting an object of type to an incompatible type.
    This usually indicates a programming error in Java, although it
    could also mean you have tried to use a foreign object in a
    different way than it was designed.
    It appears the the variable type of the index is not
    compatible with the property of the component(which is an int).
    IS there some way to type cast the variable used as the index
    for CFLOOP to that of an INT?

    You can try to use the JavaCast("int", myValue) function. It
    works great for Java objects, but I'm not sure how well it will
    work for COM. Worth a try, I guess.
    In your case it would be something like:
    <cfobject type="COM" context="INPROC" action="create"
    name="MR" class="DLLNAME">
    <cfloop from="1" to="#AddressCount#" index="i">
    <cfset VDname = mr.vdsname(JavaCast("int", i))>
    <cfset VDaddress = mr.vdsaddress(JavaCast("int", i))#>
    <cfset VDXML = mr.VDSXML(JavaCast("int", i))>
    </cfloop>

  • Type casting problem in the JSP

    Hi,
    I am type casting an Object variable to a interface Variable. I am not getting any error if i have the same code in the servlet but i am getting ClassCast Exception if i have the same code in the Scriplets part of the JSP.
    The code is as follows
    String strKey = " SomeString";
    Context context = new InitialContext();
    java.lang.Object obj = null;
         obj = context.lookup(strKey);
         ContentBroker objCB = null;
         objCB = (ContentBroker)obj; // Error is happening here
    ContentBroker is an inteface.
    I have included the jar files of ContentBroker in the classpath.
    Can anyone please tell me how to eliminate this error.?
    thanks in advance,
    Saravanan

    In that case it's a classloader issue.
    Since the object is bound in the context, I assume that you have made the class available to your server, and you have the class in WEB-INF/classes or in a jar inside WEB-INF/lib.
    Since they're being loaded by two different classloaders, the classes are seen as different by the JVM, thus the ClassCastException.
    Try removing the class from the web-app and let us know what happens.
    BTW. Which servlet container are you using?

  • Type casting in JAX-RPC

    Hello
    I was trying to do a JAX-RPC application, and I had some problems with type casting. My application worked fine with primitive types, vectors of primitive types, and beans with primitive type properties. But it didn't work with vectors of beans, or ArrayList's of beans... It couldn't deserialize the result on client side... Can anyone help?
    The Java Web Services Tutorial says that JAX-RPC supports beans and vectors, but I had the impression that this is not a "recursive" support, like "beans with vectors" or "vectors of beans"... Does it make sense?
    By the way, I was using a DII client...
    Thanks,
    Alexandre Murakami

    Hello!
    Thanks for the reply! I can't put the code of my application here (because it's quite big and it's from work)... But I followed the dii client example from the Web Services Tutorial...
    I'm trying to do a kind of a general client... The parameters are the URL of the service, the name of the operation, a list of parameters and the return type class.. And it takes the rest of the service information from the WSDL file... About the return type, I take the QName of the return type from the WSDL:
    <message>
    <part name="result" type="...">...
    then I call the call.setReturnType(QName, Class) method. The return type was an array of a very simple bean, something like:
    class Person {
    String name;
    int age;
    public String getName() {...}
    public void setName(...) {...}
    public int getAge() {...}
    public void setAge(...) {...}
    I don't know if the information I put here is enough... but anyway, thanks for the reply!
    Alexandre Murakami

Maybe you are looking for

  • Apple ID and Multiple Devices

    Hello,   There is about 4 devices logged onto my Apple ID account. Two are my devices and two of them are "friends" devices, who now refuse to log out and stop using my Apple ID. Is there any place in the Apple ID settings where I can log off of my a

  • Can not update my iphone 3gs...error 3259

    I have a 3gs Iphone and an Ipod Touch both of which don't update and both of which get the message 'Error 3259'. 

  • Writing to spread sheets with more than single precision

    Hi everyone, Im recording data by using the write to spread sheet VI in Labview 8, it records single precision which is a problem for me as I require greater  precision.  Are there ways around this issue? Thanks Solved! Go to Solution.

  • Font Installation not Happening

    I realize this is more of an encompassing "Design CS4" question, but since there isn't a forum dedicated to the package as a whole... .  I am having serious difficulties with installing fonts to the design software from my computer (Control Panel). 

  • Iphone 5S iphoto crashing when trying to select and create folders on IOS 8.0.2

    The iPhoto app keeps crashing when I try to make a new folder.  Don't get me started on the "recently added" tab.  I cannot access my entire library anymore through apps because they can't find my entire library.  They can only see the recently added