Why is there no unsigned type is java?

Just wondering? Why no unsigned int or unsigned long? I have often used these in the past but java requires me to do some clever stuff to get over the limitation.

i found this on the net somewhere. it doesn't mention anything about java but it does seem to fit the typical "don't include anything that can be confusing or misunderstood" mold that java utilizes:
"One problem is that unsigned types tend to decrease your
ability to detect common programming errors. Another is that
they often increase the likelihood that clients of your classes
will use the classes incorrectly.
Consider first error detection. Suppose a programmer defines
an Array object as follows:
int f(); // f and g are functions that return
int g(); // ints; what they do is unimportant
Array<double> a(f()-g()); // array size is f()-g()
There�s nothing wrong with this definition for a, except for the
possibility that the programmer writing it made an error. Instead
of the size of the array being f()-g(), perhaps it
should have been g()-f(). Or maybe it should have been
f()+g(). Or possibly it should have been f()-g()+1; off-byone
errors are certainly common enough. Heck, it�s even possible
that f()-g() is correct, but f() or g() is returning a
bad value. Any of these scenarios could lead to the Array
constructor being passed a size that was less than zero. As
the author of the Array class, there�s no way you can keep
clients from making mistakes such as these, but you can do
the next best thing: you can detect such errors and act on
them.
Well, actually, maybe you can�t. You can�t if you declared Array�s
constructor to take an unsigned value, because if a
negative number is passed to a function as an unsigned, the
number seen by the function isn�t negative at all. Instead, it�s
a very large positive number. As a result, you�d have no way
within the Array constructor of distinguishing between a
large, but valid, positive size value and a large, but invalid,
positive size value arising from passing in a negative number.
Hence, you�d be unable to detect programming errors that result
in negative array sizes being requested. Because such errors
are not uncommon, this makes your class easy to use
incorrectly."

Similar Messages

  • Unsigned types in java

    hi there,
    i was wondering if there is any way to handle unsigned int in java. im making some byte processing and i have a "switch case" statement like below
    so when it comes at 0x80 it does not enter the case because it converts it as -1.
    im using java 1.7
    ByteBuffer record;
    pkgId = record.get();
    switch ((int) pkgId) {
    case 0x75:
    break; /* 117 */
    case 0x7D:
    break; /* 125 */
    case 0x80:
    break; /* 128 */
    case 0x82:
    break; /* 130 */
    case 0x86:
    break; /* 134 */
    case 0x87:
    break; /* 135 */
    }

    user8999602 wrote:
    hi there,
    i was wondering if there is any way to handle unsigned int in java.Use a long.
    im making some byte processing and i have a "switch case" statement like below
    so when it comes at 0x80 it does not enter the case because it converts it as -1.
    im using java 1.7
    ByteBuffer record;
    pkgId = record.get();
    switch ((int) pkgId) {
    case 0x75:
    break; /* 117 */
    case 0x7D:
    break; /* 125 */
    case 0x80:
    break; /* 128 */
    case 0x82:
    break; /* 130 */
    case 0x86:
    break; /* 134 */
    case 0x87:
    break; /* 135 */
    }Looks more like you want an unsigned byte. The usual approach to that is to use an int, but you need to mask it. The byte 0x80 has the value -128, so when you simply cast to an int, it sign extends it, and you get 0xFFFFFF80, which is an int value of -128.
    int pkgIdInt = pkgId & 0xFF;
    switch (pkgIdInt);Alternatively, you could just cast each case value to byte, but that's too cluttered for my taste.

  • Why is there no WSDL type support for Web Api?

    So I am just getting started with .Net WebApi and one thing that I am noticing straight away is that there is no Contract defining how the Api looks and should be consumed (Request/Responses from each Action), this is usually in the form of a WSDL for WCF/Soap.
    It seems to me like this is something that would be very valuable and make life a lot easier for consumers of your Api.
    Is there a reason there isn't one? Is there a programming paradime or principle that I am unaware of? Is there a way I could create one?

    SOAP, REST AND PEOPLE'S CREATIVITY
    SOAP needs a description document like WSDL because each resource can be consumed with different messages, there are no definition on the protocol about constraints to the possible names/messages that you can manipulate a resource.
    For example, in SOAP your web service that allow clients manipulate an user can expose the operation that create an user in many different messages, like:
    addUser
    createUser
    insertUser
    Of course, these are just few sample messages, because I've see a lot of funny web services method names. There are really creative people out there.
    In other hand, if you are exposing your underlying system using web api that really respect the REST principles, the client just need to know that you have a resource named Users, because there is 99% of chance that you can create an user in this way
    POST /Users
    And this occurs for each operation you want to expose using SOAP or a web api REST.
    Despite being SOAP a protocol, which restricts what you can or can not do, and be REST a style architecture, which leaves many open points of how to do things. There are efforts to define conventions of how to expose and consume REST web apis.
    DESCRIBING A WEB API REST
    In the field of how to describe a web api REST I can cite
    Swagger. It is not a attempt to create a WSDL like to web api REST, but it is a good attempt to create an open standard for describing web apis REST.
    Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services.
    I use Swagger a lot and really love it, mainly because
    Swagger UI that allow you generate a nice live console and documentation for your web api.
    There are many implementations of Swagger for most of languages: C#, Java, Python, Ruby, etc.
    If you are using ASP .NET Web API, there a some projects to auto generate the Swagger specification, like
    Swagger.NET
    GENERATING CLIENTS TO A WEB API REST
    Because the constraints of REST, like the limited set of verbs (GET, POST, PUT, DELETE, etc) is not so difficuty to generate a client library to a web api REST.
    Projects like
    WebApiProxy can easily generate clients do C# and Javascript.
    CONVENTIONS FOR WEB API REST
    To keep our lifes as developers easier is good define some conventions of how our web api REST will behave, the best effort I know in this field is the very good
    Apigee - Web Api Design ebook. The e-book is not an attempt to create a bible or a mantra about how to design your api, but rather a collection of conventions observed in large web REST apis, like Twitter, Facebook, Linkedin, Google, etc.

  • Why is there a data type NUMC?

    Hi ABAP masters,
    working in database support for several years I've very often seen the problems that arise from the awkward data type NUMC.
    A numeric type stored as characters.
    What I always wondered is: what is this data type really good for?
    The leading zero output display alone is hardly a valid reason to waste storage and complicate the usage of the data of that type.
    I cannot imagine any use for this data type that wouldn't be better done by using integer types.
    So, if you know what the reasoning behind this data type is, please let me know.
    thanks and best regards,
    Lars

    NUMC data type can be used to maintain positive numbers with leading Zeros
    Most of SAP's important numbers like Sales Order numbers, Customer numbers, Delivery documents,
    Material numbers, Sales Org, Division, Company Codes, Distribution Channel are CHARs only
    But if their Data is containing only digits, SAP Transactions will automatically add Leading zeros for them and store in the database as Raw data.
    If those SAP numbers contains at least one non-digit character, then leading zeros will not be added.
    Example: if 54 is assigned to BUKRS it will be stored in DB as 0054
                   if 5A is assigned to BUKRS it will be stored in DB as 5A only
    Leading zero concept is very useful for Date and Time calculations.
    Month, Day, hours etc., must be declared as NUMC for better calculations
    Example:
        PARAMETERS p_year TYPE I.          "instead of Integer we can use type N LENGTH 4 also here
        DATA  v_month TYPE N LENGTH 2.
        DATA  v_day     TYPE N LENGTH 2.
        DATA  v_year    TYPE N LENGTH 4.       then calculations will be easy
        DATA  FDATE   TYPE D.
        v_year = p_year.
        v_day  = 1.              "1st day of Month
        DO 12 TIMES.
            v_month = sy-index.           "Leading zero will be added automatically
            CONCATENATE v_year  v_month  v_day  INTO  FDATE.
            WRITE / FDATE.                "Every month 1st day of selected year
        ENDDO. 
    Example:  Customer number contains uneven digits.  It should be converted to a 10 digit number
                     with "C" as 1st Character.  Logic will be
                     PARAMETERS custno TYPE I.               
                     DATA  v1                     TYPE  N  LENGTH  10.
                     DATA  str_custno         TYPE C LENGTH 11.
                     v1 = custno.       "customer number will be converted to 10 digit number
                     CONCATENATE 'C'  V1   INTO  str_custno.
    please correct me, if I am wrong
    Thanks and Regards
    Nagababu Tubati

  • About unsigned types

    I find that there are no unsigned types in Java, and I wonder why it does not provide
    any unsigned types.
    Now I am reading a file generated by C programs, and some of them may return negative
    bytes rather than positive.
    What I have done is to do some convertion like this
    int data = ((byte)signedByte+256)%256I wonder if this is a stupid way to get the right data. Any suggestions are appreciated!

    hi paulcw
    I tried FileInputStream, but it still returns negative
    value.Well, it returns a -1 at end of input, but otherwise it only returns positive numbers. At least that's what happened when I tested it. And not only that, but it makes no sense for it to return any negative numbers for the bytes it reads, because if it did, using -1 as an end-of-input indicator wouldn't work.

  • Are there non-public classes in Java SDK?

    Or are ALL classes in all packages of the Java SDK public?
    I have looked in the sources spot checking and didn't find a non public (default) class.
    If all classes are public, why?
    There exists a means in Java language to define a class as default ("class MyClass" instead of "public class MyClass") visibility. So why isn't it used by Java SDK (if this is really true)?

    I dont know what language you're programming in.
    If you don't specify
    public class
    or
    private class
    the class is "protected".
    Read the spec.If you read the spec, you'll see that, with respect to a class:
    (per section 6.6.2) Classes from outside the package the class lives in that extend the class have access to protected members.
    (per section 6.6.5) Classes from outside the package this thing lives in that extend this class do not have access to default members.
    Relevant part of section 6.6.5 (Example: Default-Access Fields, Methods, and Constructors) is:
    If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.
    This is default access, not protected access
    Lee

  • Why is there no JavaBeans interface?

    I've been using beans for a while now, and I don't understand this? Why is there no interface such as java.beans.Bean that defines the method calls to addPropertyListener and removePropertyListener, etc?
    Even if the interface didn't define any methods, it would be useful as an "instanceof" operand. This must have been discussed at some point, but I couldn't find anything through searches.

    Most of the beans I write are non-graphical, so I would not want to be forced to implement addPropertyListener and removePropertyListener.
    I do not think the creators wanted to have some beans implement or extend the Bean that you propose, while other beans would not.
    I like the fact that you do not need to implement an interface or extend a class to be considered a bean. This means that as long as you have an empty constructor, you have a JavaBean.

  • Unsigned data types in Java

    I know this is beating an old dead horse, but I find it frustrating that Java does not support unsigned types. I frequently work with binary file formats that store data in unsigned types. In Java there is no easy way to work with these files. For example, if the file has unsigned longs it is a problem. Also, if the file has unsigned ints, a very common occurrence, I have to "upcast" those numbers into longs. This is expensive from a time and space point of view since data files from satellites can be hundreds of megabytes or gigabytes in size and I have to double them in size just to capture the final bit. It is also inefficient to process these files because now I am using longs (64-bits) on systems that are usually optimized for 32-bits which means processing code takes a big performance hit.
    Also, there is simple confusion. For example, if I provide data from a file to a user and they see "long" where they know they data is an int they start asking questions and I have to start explaining why it is a long instead of an int. Scientists don't like data to be "translated" for integrity reasons so I have make these long explanations how upconverting to a long is not really a translation, etc. It just creates a lot of confusion and problems.
    Also, look at from a developer point of view. The developer has a spec in front of him listing the data types and is now reading the corresponding java class where the data gets loaded--all the data types are different because of the upconverting--it creates confusion.
    Is there any hope of having unsigned types or we all condemned to a lifetime of upconverting?

    JohnChamberlain wrote:
    I thought it was obvious that you need to upconvert unsigned values because otherwise the number will be wrong if the sign bit is set.No. A 32-bit scalar with the high bit set is still correct (bit-for-bit). You only get problems if you perform arithmetic, right-shift or widening-conversion on it, or make a decimal String representation.
    For example, lets say the file has an unsigned int (uint32) value of 0xF1234567 which in decimal is 4,045,620,583. This is a positive number. If you load this value into a Java int value it will be interpreted as the negative number -249,346,713.For a given value of "interpreted"; Integer.toHexString(0xF1234567) produces the expected result.
    Further example: if you load a file containing uint32 values into Java ints and then average all the values you might come out with a negative number. Obviously this is impossible because the file contains only positive numbers so the average of those numbers cannot be negative.Obviously if you need to do this on a number of large 32-bit scalars you need the sum scalar to be 64-bit which means you can mask your way out of any issues when you perform the widening conversion.
       int[] x = { 0xF1234567, 0xF1234565, 0xF1234557 };
       long sum = 0L;
       for(int i=0;i<x.length;++i) { sum += 0xffffffffL & x; }
    int average = (int)(sum/x.length); // average is now "correct" (bit-for-bit)
    Maybe it wasn't clear that I need to not only load the values but use them.You did fail to mention that.
    The files I load get passed on to other applications where the values get used and obviously that includes doing calculations on them so the values have to be correct. I cannot load a bunch of UInt32s into Java ints and say "pretend they are positive numbers".I get the impression you are not really interested in finding solution.
    It can be releasing to have a whinge but don't let it distract you from thinking outside the box.
    I think part of the problem here is that Java programmers do not have to work with binary files or binary protocols so they do not appreciate that doing this has serious problems in Java.I have done binary protocols. Not having unsigned scalars was never a problem.
    For example, take unsigned longs. If you are working with a binary source that has these you have no alternative except to use the BigInteger package and convert every value into an object, an incredibly painful and CPU-intensive operation if you dealing with files with gigabytes of data.You might want to consider alternatives, like
    unsigned right-shifting ('>>>') the incoming values for 64-bit scalar fields where dividing by 2 would be acceptable,
    etc.

  • Is there a date data type in java???

    Hi guys!
    Is there a date data type in java???
    How to declare date data type variable?
    Your reply is greatly appreciated!
    -=samer=-

    RTFM
    there's about 8 date types, depending on what you want
    see
    java.util.Date
    java.util.Calendar
    GregorianCalendar
    SimpleDateFormat
    System.currentTimeMillis()

  • Why is there a java enable function in the settings app if java ia not supported by ipad2?

    Why is there a java enable function in the settings app of the ipad2, ios5, when java is not supported by ios5 on the ipad2?  The adds say that java neo, I think that is what it is supposed to be called, was supposedly introduced into the ios5 format to deal with this?

    If you're looking in the settings for Safari, that's JavaScript, which despite the similarity in names is completely different from Java. Java is not, never has been, and all indications are never will be supported in iOS. I have no idea what "java neo" might be, but I've never seen Java mentioned in any way in any of Apple's iPad ads.
    Regards.

  • Selecting #of bits for data types in Java

    hi,
    i would like to know if we can constrain compiler on allocating memory to basic data types, such as int, float, short etc. i would like to read an exactly four byte integer into an int, 2 byte short into a short etc. i need to read these parameters exactly of their specified number of bytes - not more or less - as if i read anything more/less, i will be reading a part of other parameter.
    i know that C allows us to do this by letting us to specify number of bits we like to allocate for each data type (for eg. unsigned int:16; means i need an unsigned int of exactly 16bits (2 bytes long) -no more and no less).
    Is there anything similar i can do in Java?
    any suggestion is greately appreciated.
    Thanks,

    All primitive types in Java are well-defined. In contrast to C/C++, an int in Java is allways 32 bits, using one's complement, a char is allways 16 bits etc.
    Java does not give you direct acces to physical memory - that would compromise the basic design of Java.
    You can read individual bytes from files, and you can do all the integer arithmetic in Java as you can in C/C++. To convert eg. fout bytes to one int, you could do the following:
    byte b1= (some byte value),
         b2,
         b3,
         b4;
    int i= (((b1 << 8) | b2 << 8) | b3 << 8) | b4;
    b1 being the most significant byte, b4 being the least significant.
    Did this answer you questions?

  • Unsigned Long in java

    Hi all,
    I have a code in C which i want to convert into java.. Iam facing problem because java does not support
    unsigned long.The code in c look like this:
    WCD.cardno = ( SerBuf[3]* 0x00010000UL+
    SerBuf[4]* 0x00000100UL+
    SerBuf[5]* 0x00000001UL);
    I want to convert this code into java. What i have done is something like this
    cardno = (tempBuffer[3]*0x01000000 + tempBuffer[4]*0x00010000 + tempBuffer[5]*0x00000100 +tempBuffer[6]*0x00000001);
    Can anyone help me out. This program is for serial port implementation.
    Thanks
    Kiran

    kiranJNI wrote:
    Basically how can we achieve unsigned long in java???In your case, this isn't going to be a problem for two reasons.
    AFAIK, there aren't any numbers where multiplying them as unsigned numbers is going to be different from multiplying them as signed numbers and still give a valid result. To make this easier, let's work with signed vs unsigned bytes. Negative numbers are those in the range 0x80 to 0xFF; these are the only numbers where the "value" of the byte differs between signed and unsigned. Now think of those numbers as unsigned numbers. The only unsigned numbers you could multiply them by and still remain within the range of a byte are 0 and 1. If you multiply by 2, the result is 0x100, which is larger than what a byte can represent. If the result will remain within the range of the data type, it don't think there are any numbers where signed and unsigned multiplication return a different bit pattern.
    Furthermore, your example doesn't even need multiplication. You're multiplying by powers of 2, so all you really need is a series of shifts and adds.

  • How to map C/C++ unsigned char[] to Java

    hi all,
    I'm using w2k OS.
    Given that C code:
    BYTE *fBuf;
    fBuf = new BYTE[256];
    Is there anyone of you know how to pass/map the unsigned char to java?
    regards
    elvis

    why did you classify this as byte? how do you did
    that?They probably guessed. It is probably a good guess.
    You can use the following to determine the size exactly.
    First determine what "BYTE" is exactly. You will have to find that in an include file somewhere. Your IDE might do this for you automatically.
    So, for example you might find the following...
    typedef unsigned char BYTE;
    So then you would know that the type is actually "unsigned char".
    Once you have this information you then look in limits.h (this is an ANSI C/C++ file so it will exist somewhere.) In it you find the "..._BIT" that corresponds to the type. For the type given above you would be looking for "CHAR_BIT" (because unsigned and signed chars are the same size.)
    On my system that would be...
    #define CHAR_BIT 8
    That tells you that there are 8 bits in the BYTE value. So now you need to find a java type that also has at least 8 bits. And the java "byte" value does.

  • Why is there no scaling for high resolution monitors in Adobe Bridge CC?

    Why is there no scaling for high resolution monitors in Adobe Bridge CC?
    Photoshop CC, Illustrator CC and Indesign CC have 200% scaling for high resolution monitors in their preferences panel but Bridge CC does not, when will this feature be added to Bridge CC Adobe???

    qsea wrote:
    Why is there no scaling for high resolution monitors in Adobe Bridge CC?
    Photoshop CC, Illustrator CC and Indesign CC have 200% scaling…
    Inconsistency between or among applications in the artificial "suites" should come as no surprise.
    The "suite" concept is a fabrication of Adobe marketing and bean-counting types.  The engineering teams are totally independent of each other, they are not only in different buildings but in different cities and states of the American Union, even in different countries.
    The fact that they have little if any communication among them is highlighted by requests occasionally made in these forums by top Adobe engineers to let the other teams know when there are problems in one application that impact our workflow in another one.

  • Incompatible types - found java.lang.String but expected int

    This is an extremely small simple program but i keep getting an "incompatible types - found java.lang.String but expected int" error and dont understand why. Im still pretty new to Java so it might just be something stupid im over looking...
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Lab
    public static void main(String []args)
    int input = JOptionPane.showInputDialog("Input Decimal ");
    String bin = Integer.toBinaryString(input);
    String hex = Integer.toHexString(input);
    System.out.println("Decimal= " + input + '\n' + "Binary= " + bin + '\n' + "Hexadecimal " + hex);
    }

    You should always post the full, exact error message.
    Your error message probably says that the error occurred on something like line #10, the JOptionPane line. The error is telling you that the compiler found a String value, but an int value was expected.
    If you go to the API docs for JOptionPane, it will tell you what value type is returned for showInputDialog(). The value type is String. But you are trying to assign that value to an int. You can't do that.
    You will need to assign the showInputDialog() value to a String variable. Then use Integer.parseInt(the_string) to convert to an int value.

Maybe you are looking for

  • Enabling FI-SL extractor with delta capability

    I am working on enabling FI-SL (3FI_SL_*) extractor with delta capability. Implemented OSS note 328197 successfully and also related OSS notes. This works on totals table. Source system is 4.6C Tested BW01, BW03 and everything seems to be fine, and s

  • Reports 10g Question

    Hello All, I am in the process of converting reports from 6i ti 10g. When I run my report in Web Layout nothing shows up. Is it an environment setup issue ? How do fix this issue ? Pls help... Thanks, Anna

  • Change logo in BW report

    Hi All, I need to change the logo for all BW reports. Can you please tell me the steps involved. Your quick response will be appreciated. Thanks in advance, Sananda

  • Arpeggios - why don't they playback from 1st beat of 1st bar ?!

    Using an AU plugin synth in Logic 8 (say FM8 or Gladiator) with an arpeggio preset - why when i record into the 1st 4 bars of a song by holding a single note down and then quanitise it so it should start playing on EXACTLY beat 1 of bar 1 - do i hear

  • OSX Adobe Acrobat Pro 11.0.03 -- persistently hiding all toolbars (always)

    Is there any way to force hiding all toolbars as the default when opening documents? I found the option to restore settings for documents previously saved with Adobe, however, I want to open all documents (including ones not previously saved with Ado