Showing posts with label Integer. Show all posts
Showing posts with label Integer. Show all posts

Java Autoboxing / Unboxing with Example code

In older versions of java , int (or any other primitive value) are not accepted by a collection. Consider the following code for converting array to ArrayList which gives the compile error due to Collection accepts object references not primitive int values. The solution for this error is to box primitive values into the appropriate wrapper class . In this case we have to convert int to Integer wrapper class . Now replace the line lst.add(numbers[i]); with lst.add(new Integer(numbers[i])); here we have converted int to Integer wrapper class.



import java.util.*;
class listExample
{
public static void main(String args[])
{
List lst = new ArrayList();
int numbers[] ={10,30, 55, 65,33};
for (int i=0;i<5;i++)
{
lst.add(numbers[i]); // Error listExample.java:13: cannot resolve symbol , symbol : method add (int) , location: interface java.util.List . Solution : Replace lst.add(numbers[i]); with lst.add(new Integer(numbers[i]));
System.out.println(numbers[i]);
}
}
}

When we need an int, we have to unbox the Integer using the intValue method . Consider the following lines of code , where add method accepts two Object references (Not a primitive value) , when we compile the code in older version of java , it throws error , because we are adding two objects reference and assigning to a primitive int variable. . Replacing the int d=a+b; with int d=a.intValue()+b.intValue(); will solve the problem.


class Addition
{
public static void main(String args[])
{
Integer k=new Integer(123);
Integer k1=new Integer(1523);
add (k, k1);

}
public static void add( Integer a , Integer b )
{
int d=a+b; // using unbox
System.out.println("Addition = " + d );

}
}

The following example illustrates autoboxing and unboxing . In the main function , we have declared 4 variables a, b , c, d . a & b are primitive type variables. c & d are Integer class variables. Now in our code , we have assigned primitive type int value to Integer c & Integer d . In older version , the this line gives compile error. But in java 1.5 , it does not give any error due to autoboxing . The autoBoxUnbox( Integer a , Integer b ) accepts two object reference. So when we call autoBoxUnbox(a,b) where a , b are int values , in java 1.5 no error is coming due to autoboxing. In the autoBoxUnbox method , the line int d=a+b; d is an int variable. but a & b are Integer variable. Here a & b are converted to int variable by unboxing in java1.5 , In java 1.4 we have to use Integer.intValue() to convert Integer to int.


import java.util.*;
class autoBoxUnbox
{
public static void main (String args[])
{
int a = 100;
int b = 100;
Integer c=300;
Integer d=300;
autoBoxUnbox(a,b);
autoBoxUnbox(c,d);
}

public static void autoBoxUnbox( Integer a , Integer b ) // using autoboxing
{
Integer c=a+b;
int d=a+b; // using unboxing
System.out.println("Given Numbers " + a + " , " + b);
System.out.println("Addition = " + c );
System.out.println("Addition using unbox= " + d );
System.out.println(" ");
}
}


Output :

D:\as2\JF2>java autoBoxUnbox
Given Numbers 100 , 100
Addition = 200
Addition using unbox= 200

Given Numbers 300 , 300
Addition = 600
Addition using unbox= 600
Read more...

int Vs Integer in Java Example ,Difference between Integer Wrapper & int primitive

int is a primitive data type . It is a 32-bit signed two's complement integer which can have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Integer is a wrapper class for int. The constuctor for Integer class is Integer(int num / String str) . So Integer class wraps a primitive type int value in an object. An object of Integer class contains a single field whose type is int .
An int stores a number where as Integer points a reference of an object that contains a number .Integer class is an example of immutable object which represents a single value that cannot change over the lifetime of the object.

We may use Integer rather than a primitive due to some of the below mentioned reasons.
1. Some Methods of a class (for example methods of collection class like List , Map, etc can hold object references) accept only object reference (not primitive value) as an argument . 2. Integer class has many methods & constants which can be used in many ways . For example Constants of the Integer class, such as MIN_VALUE & MAX_VALUE, SIZE which is used to define the lower , upper value & number of bits to represent an int value and Methods of Integer Class su as parseInt , toString() are useful when dealing with an int.

Converting an Integer to int vice versa is very easy .
To convert to Integer from int. // box
int number =100;
Integer numWrap=new Integer(number);

//To convert to int from Integer // unbox
Integer numWrap1=new Integer(200);
int num =numWrap1.intValue();

If you use java 1.4 , then you have to manually box , unbox using the above commands.

The following example code will be compiled with java version 1.5 and above .No need to box manually. In Java 1.5 , new feauture autoboxing , unbox is introduced .

 

class intVsInteger
{
public static void main(String[] args)
{
int num1 = 100;
int num2 = 100;
int num3 = 160;
int num4 = 160;
Integer num5=300; // by autoboxing available from jdk 1.5
Integer num6=300; // by autoboxing
int num7=num5+num6; // by autoboxing

System.out.println( "num1= "+num1 );
System.out.println("num2= "+num2 );
System.out.println("num1==num2 " + ( num1==num2) );
System.out.println( "num3= "+num3 );
System.out.println("num4= "+num4 );
System.out.println("num3==num4 " + (num3==num4) );
System.out.println( "num5= "+num5 );
System.out.println("num6= "+num6 );
System.out.println("num5==num6 " + (num5==num6) );
System.out.println("Below value using Integer class");
intVsInteger(num1,num2);
intVsInteger(num3,num4);
intVsInteger(num5,num6);
}

public static void intVsInteger( Integer a , Integer b ) // using autoboxing
{
System.out.println( "a= "+a );
System.out.println("b= "+b );
Integer c=a+b;
int d=a+b; // using unbox
System.out.println("c= " + c );
System.out.println(a==b );

}
}


Output of the program

D:\as2\JF2>java intVsInteger
num1= 100
num2= 100
num1==num2 true
num3= 160
num4= 160
num3==num4 true
num5= 300
num6= 300
num5==num6 false
Below value using Integer class
a= 100
b= 100
c= 200
true
a= 160
b= 160
c= 320
false
a= 300
b= 300
c= 600
false

The intVsInteger method accepts Integer object . So the object reference is passed to the method not the value. if both are pointing to the same reference of the object , then the output will be true otherwise the output will be false.When using primitive type , if both values are equal means , num1=num2 will be true.


Read more...

Java String to Integer Example . Use of Integer.ValueOf(), parseInt()

/* Many times , We may come accross a situation where a string needs to be changed to an Integer . For example when we accept a input through keyboard , it will be read as String . For doing any calculation , we have to convert the string to an integer . Integer Object has methos like valueOf & parseInt for converting sting to integer.
We can convert String to Integer using the following ways

Integer.valueOf - converts String to Integer Object
Integer.parseInt - converts String to int primitive type
If we pass a string to the constructor of the Integer object , it returns Integer Object. */



import java.io.*;
public class StringToInt {
public static void main(String[] args) {

Example1();
Example2();
}

// Example 1:

private static void Example1()
{

System.out.println("Example 1 ");
String numStr ="110";
Integer number = new Integer(numStr);

String numStr1="0005";
int number1 = Integer.valueOf(numStr1);

String numStr2="0007";
int number2=Integer.parseInt(numStr2); //converts to integer primitive type.

System.out.println( "Number String is ( string concatenation)" + numStr+numStr2+numStr2);

int result=number+number1+number2;
Integer result1=number+number1+number2;

System.out.println("Input Numer" + number);
System.out.println("Input Numer1" + number1);
System.out.println("Input Numer2" + number2);

System.out.println( "After Converting Integer ( string concatenation) " + number+number1+number2);
System.out.println( "result " + result);
System.out.println( "result1 " + result1);

}

// Example 2:

private static void Example2()
{

BufferedReader br=new BufferedReader (new InputStreamReader(System.in) );

String numStr="";
int number=0;
int sum=0;

System.out.println("Example 2 ");
System.out.println("Enter Numbers to add & type quit to exit ");

do
{

try
{
numStr=br.readLine();
number = Integer.parseInt(numStr);
}
catch (Exception e)
{
if (numStr.equalsIgnoreCase("quit") )
{
System.out.println("Quiting....");
number=0;
}
else
{
System.out.println("Invalid Input");
number=0;
}
}
sum = sum + number;
} while (numStr.compareTo("quit") !=0);

System.out.println("Sum is =" +sum);
}

}



Output :
--------

D:\as2\JF1>java StringToInt
Example 1
Number String is ( string concatenation)11000070007
Input Numer110
Input Numer15
Input Numer27
After Converting Integer ( string concatenation) 11057
result 122
result1 122
Example 2
Enter Numbers to add & type quit to exit
7
5
3
7
2
quit
Quiting....
Sum is =24
Read more...

 
Copyright 2011 Java Online