Widening Primitives

While working on different primitive data types we will get unexpected result. Some of these are below.

package com.gudla.widening;

public class WideningPrimitive {
    void test(){
        //concatenating String and Character
        System.out.println("It is the output from the test");
        System.out.println("X"+'y');
        System.out.println('x'+"Y");
        //If we use characters using + sign it will convert to decimal and adds those
        System.out.println('v'+'x'+"Y");
        //After the string everything will be treated as string
        System.out.println('v'+'x'+"Y"+'z'+'a');
        System.out.println();
        
    }
    
    void test1(){
        System.out.println("It is the output from the test1");
        //concatenating String and integer
        System.out.println("X"+20);
        // we use first integer then it will be added after string it will consider
        //integer also string so it concatenating.
        System.out.println(20+40+"ABC"+30+50);
        System.out.println();
    }
    void test2(){
        System.out.println("It is the output from the test2");
        System.out.print("Y"+"Z");
        System.out.println('v'+'x');
        System.out.println();
    }
    void test3(){
        System.out.println("It is the output from the test3");
        // When we try to print with different primitive data types
        //Always it will type cast to higher data type
        System.out.println('c'+20);
        System.out.println(20+30.0);
        System.out.println(1000L+20); 
        System.out.println();
    }
   void test4(){
        System.out.println("It is the output from the test4");
        //Prefix with 0 in a number then java compiler will treat it as octal number.
        System.out.println(040);
    }
}

Output of above program.

It is the output from the test
Xy
xY
238Y
238Yza

It is the output from the test1
X20
60ABC3050

It is the output from the test2
YZ238

It is the output from the test3
119
50.0
1020

It is the output from the test4
32

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s