0
public class UnIntentionalObjectCreation {

  private static Byte sumOfIntegerUptoN(Byte N) {
    Byte sum = 0;
    for (Byte i = 0; i < N; i++) {
        sum += i;
    }
    System.out.println(sum);
    return sum;
  }

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    sumOfIntegerUptoN(10);
    long end = System.currentTimeMillis();
    System.out.println((end - start));

  }
}

Error in 6 line :- Inconvertible type found Error in 14 line:- UnIntentionalObjectCreation cannot be applined to (int)

Naman
  • 27,789
  • 26
  • 218
  • 353

3 Answers3

1

So your method accepts a Byte, while you are passing an int. You can simply replace Byte variables/methods with int.

public class UnIntentionalObjectCreation {

  private static int sumOfIntegerUptoN(int N) {
    int sum = 0;
    for (int i = 0; i < N; i++) {
        sum += i;
    }
    System.out.println(sum);
    return sum;
  }

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    sumOfIntegerUptoN(10);
    long end = System.currentTimeMillis();
    System.out.println((end - start));

  }
}

Should do the work.

Tom
  • 16,842
  • 17
  • 45
  • 54
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
0

Byte is an object but his behaviour is different form Integer, Long and Double, you cannot use it for basic arithmetic operations. And even if you can assign an integer number to a Byte object like this:

Byte a = 10;

Quite strangely, you cannot pass an integer number as parameter like you did calling sumOfIntegerUptoN method.

In your case, instead of a Byte I suggest to use a primitive data type like an int.

Byte object is immutable, so you cannot increment and decrement it.

The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.

You should have a look at what is autoboxing and autounboxing in Java and which kind of primitive data type exists in java.

There is also another aspect I suggest to take care, a Byte is only 8 bit, so the range of number your can handle is quite small (-128/+127).

freedev
  • 25,946
  • 8
  • 108
  • 125
0

There are few things I could notice -

One

sumOfIntegerUptoN(10); // this is expected to be of Type

which can be modified as -

sumOfIntegerUptoN(((Integer)10).byteValue()); // wraps the integer converted to byte into Byte

Two

sum += i; //where both these are Byte

the operation is not permitted according to the doc here. Since the values of the variables in the expression above are not known at the compile time.

As it happens in your case, do take a look at Why can not I add two bytes and get an int and I can add two final bytes get a byte?

Hence would recommend changing all the Byte occurrences in your code to int and perform operations accordingly.

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353