nanosoft
nanosoft

Reputation: 3089

Setting byte field in an object

I have a simple program as below:

class SerializationBox implements Serializable
{

    private byte    serializableProp    = 10;

    public byte getSerializableProp()
    {
        return serializableProp;
    }

    public void setSerializableProp(byte serializableProp)
    {
        serializableProp = serializableProp;
    }
}

public class SerializationSample
{

    /**
     * @param args
     */

    public static void main(String args[]) 
    {

        SerializationBox serialB = new SerializationBox();
        serialB.setSerializableProp(1); // Here i get an error
}
}

At the indicated place in code I get error that "The method setSerializableProp(byte) in the type SerializationBox is not applicable for the arguments (int)".

I believed that as per the link http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html , I am allowed to pass -128 to 127 as the arguement.

Please let me know what I am missing?

Upvotes: 0

Views: 526

Answers (3)

Prabhaker A
Prabhaker A

Reputation: 8483

you are trying to call setSerializableProp() method with a integer literal.That is giving you compilation error.
So down cast the integer literal to byte like below.
setSerializableProp((byte)1)

Upvotes: 1

ifloop
ifloop

Reputation: 8386

serialB.setSerializableProp((byte)1);

This will explicitly cast your integer literal (1) into a byte

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34176

You have to cast the integer to byte:

serialB.setSerializableProp((byte) 1);

Notes:

  • When you do

    private byte serializableProp = 10;
    
  • 10 is a integer, not a binary number. To specify that the number is a binary you have to use the following syntax:

    private byte serializableProp = 0b10;
                                    ^^
    

Upvotes: 1

Related Questions