Jump to content
xisto Community
ultranet

Learning Java

Recommended Posts

Hey, I'm new and I want to leanr Java, Who can Help me?

Well, Many people are here to help you. But first let us know what you want. A small suggestion,
posting requests like these in other people's threads may not be good for you...I think.

OK. I will help you. What information do you want? Do you have any doubts? or you want
information like where to start etc..? Feel free to ask anything. But be clear....

Share this post


Link to post
Share on other sites

Hello xpress,Please help me. I am learning java and getting this error in this simple program :-class test { public static void main(String[] args) { byte b = 5; b = b * 2; System.out.println("Answer is "+b+"."); }}Please give me the correct code for this. Thank you in advance.

Edited by one_nikhil (see edit history)

Share this post


Link to post
Share on other sites

byte b = 5;

b = b * 2;

System.out.println("Answer is "+b+".");

}

The correct program is,

 

class test {

 

public static void main(String[] args){

 

byte b=5;

b=(byte)(b*2);

 

System.out.println("Answer is "+b+".");

}

}

 

Why did we add byte at b=b*2 ?

Because, java doesn't allow direct arithmetic operations with byte and short(to save from potential loss of precision). Java automatically promotes byte into int here. That is, the result of b*2 will be treated as int rather than byte by java compiler. So we are converting it back to byte by using that keyword before the expression.

 

A small suggestion. Use upper case for first letter in class name(use class Test instead of class test). It is a common convention in java.

Edited by xpress (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.