Important Basics of Java Programming Language
Hello Guys....
This is my first post and in this i am going to talk about some of the important basics and concepts of Java Programming Language which are generally ignored by most of us...
I hope that after reading this post many basic concepts regarding java will be cleared to you.So let's get started:-
1. Automatic Type Promotion
Consider this code :-
public class promotionWhen we run this code in a file named promotion.java we get the error as follows :-
{
public static void main(String args[])
{
byte a=10;
byte b=2;
byte c=a*b;
System.out.println("Result of 10x2 = "+c);
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:So why do we get this error ???? as we know that the range of the byte is 256 and the multiplication of 'a' and 'b' is 20 which is <256 still this error occurs. The Solution to this error is given below :-
Type mismatch: cannot convert from int to byte
at promotion.main(promotion.java:7)
public class promotionSo what have we done ??? Actually we have typecasted the multiplication of a and b to a byte so that we get the result in byte.
{
public static void main(String args[])
{
byte a=10;
byte b=2;
byte c=(byte) (a*b); // Altered Code....
System.out.println("Result of 10x2 = "+c);
}
}
This is a very interesting Property of Java that during the calculations the java language automatically promote the data variables having small data types like - short,char,byte to int this is the reason for that error. So if we want to add a line to our code as -
int d;So, in this case we don't have to do any explicit typecasting as the result is calculated in 'int' and stored in 'int', so we get the output as desired...
d=a*b/5;
System.out.println("Result of 10x2/5 = "+d);
Not bad , keep it up , maybe i will get to learn java and everything about it from here
ReplyDeleteThanx bro
Delete