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 promotion
{
    public static void main(String args[])
    {
        byte a=10;
        byte b=2;
        byte c=a*b;
        System.out.println("Result of 10x2 = "+c);
    }
}
When we  run this code in a file named promotion.java we get the error as follows :-
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from int to byte

    at promotion.main(promotion.java:7)
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 :-
 public class promotion
{
    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);
    }
}
So 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.
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;
d=a*b/5;
System.out.println("Result of 10x2/5 = "+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...

Due to shortage of time i am not able to complete this post now but will update this post for sure...asap and add more interesting basics of Java Programming Language.

Comments

  1. Not bad , keep it up , maybe i will get to learn java and everything about it from here

    ReplyDelete

Post a Comment

Popular posts from this blog

FILE MANAGER

How to make a Turbo C++ Program compatible for CodeBlocks IDE