1

How to create my own datatype in java, that will accept value range from 0 to 1024.

My declaration would be.

kilobyte a=10;

Is it possible?

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64

3 Answers3

4

No. Java doesn't allow that (i.e. creating a primitive). But you could create your own class for that.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
3

You cannot create your own primitive, but you could have a wrapper Object for that.

Dirty example here:

// note that class name doesn't follow Java conventions here
public class kilobyte {
    private int number;

    public kilobyte(Number number) {
        if (number == null) {
            throw new IllegalArgumentException("argument is null");
        }
        else if (number.intValue() > 1024 || number.intValue() < 0) {
            throw new IllegalArgumentException("argument not within 0 < x < 1024 range");
        }
        else {
            this.number = number.intValue();
        }
    }
    // TODO getter/setter
}
Mena
  • 47,782
  • 11
  • 87
  • 106
  • 1
    Personally, I'd probably have allowed `0` as a valid value. What's with accepting a `Number`, as opposed to using an int? For that matter, extending `Number` is potentially a viable option. Oh, and throwing an exception in a constructor [can get messy](http://stackoverflow.com/questions/1371369/can-constructors-throw-exceptions-in-java); in this sort of situation, it'd be better to use a static constructor anyways - especially with a _heavily_ input-constrained type, caching immutable objects is likely to show dividends here. – Clockwork-Muse Oct 18 '13 at 07:00
  • @Clockwork-Muse your comment contains all kinds of valid observations (+1 on my side). Note that my post says "dirty example" for a reason :) – Mena Oct 18 '13 at 07:46
1

No, you cant create your own primitive type neither overload the operators, so this is not possible in java.

libik
  • 22,239
  • 9
  • 44
  • 87