How to cast an Object to an int - java

How can I cast an Object to an int in java?

If you're sure that this object is an Integer :
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.
If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :
int i = Integer.valueOf((String) object);
It can throw a NumberFormatException if your object isn't really a String with an integer as content.
Resources :
Oracle.com - Autoboxing
Oracle.com - Primitive Data types
On the same topic :
Java: What's the difference between autoboxing and casting?
Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
Convert Object into primitive int

Scenario 1: simple case
If it's guaranteed that your object is an Integer, this is the simple way:
int x = (Integer)yourObject;
Scenario 2: any numerical object
In Java Integer, Long, BigInteger etc. all implement the Number interface which has a method named intValue. Any other custom types with a numerical aspect should also implement Number (for example: Age implements Number). So you can:
int x = ((Number)yourObject).intValue();
Scenario 3: parse numerical text
When you accept user input from command line (or text field etc.) you get it as a String. In this case you can use Integer.parseInt(String string):
String input = someBuffer.readLine();
int x = Integer.parseInt(input);
If you get input as Object, you can use (String)input, or, if it can have an other textual type, input.toString():
int x = Integer.parseInt(input.toString());
Scenario 4: identity hash
In Java there are no pointers. However Object has a pointer-like default implementation for hashCode(), which is directly available via System.identityHashCode(Object o). So you can:
int x = System.identityHashCode(yourObject);
Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.
You can also use object.hashCode(), but it can be type specific.
Scenario 5: unique index
In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:
class ObjectIndexer {
private int index = 0;
private Map<Object, Integer> map = new WeakHashMap<>();
// or:
// new WeakIdentityHashMap<>();
public int indexFor(Object object) {
if (map.containsKey(object)) {
return map.get(object);
} else {
index++;
map.put(object, index);
return index;
}
}
}
Usage:
ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject); // 1
int y = indexer.indexFor(new Object()); // 2
int z = indexer.indexFor(yourObject); // 1
Scenario 6: enum member
In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal(), for example:
enum Foo { BAR, BAZ, QUX }
// ...
Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1

Assuming the object is an Integer object, then you can do this:
int i = ((Integer) obj).intValue();
If the object isn't an Integer object, then you have to detect the type and convert it based on its type.

#Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.

You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.

Answer:
int i = ( Integer ) yourObject;
If, your object is an integer already, it will run smoothly. ie:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
If your object is anything else, you would need to convert it ( if possible ) to an int first:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here

I use a one-liner when processing data from GSON:
int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;

If the Object was originally been instantiated as an Integer, then you can downcast it to an int using the cast operator (Subtype).
Object object = new Integer(10);
int i = (Integer) object;
Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i as Integer instead and then call intValue() on it.
But if it initially wasn't created as an Integer at all, then you can't downcast like that. It would result in a ClassCastException with the original classname in the message. If the object's toString() representation as obtained by String#valueOf() denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf() or new Integer() for this.
Object object = "10";
int i = Integer.valueOf(String.valueOf(object));
See also:
Inheritance and casting tutorial

int i = (Integer) object; //Type is Integer.
int i = Integer.parseInt((String)object); //Type is String.

Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.
Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
int num = i; //Java 1.5 or higher

You can't. An int is not an Object.
Integer is an Object though, but I doubt that's what you mean.

If you mean cast a String to int, use Integer.valueOf("123").
You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.

I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.
Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.

int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.

For Example Object variable; hastaId
Object hastaId = session.getAttribute("hastaID");
For Example Cast an Object to an int,hastaID
int hastaID=Integer.parseInt(String.valueOf(hastaId));

Refer This code:
public class sample
{
public static void main(String[] args)
{
Object obj=new Object();
int a=10,b=0;
obj=a;
b=(int)obj;
System.out.println("Object="+obj+"\nB="+b);
}
}

so divide1=me.getValue()/2;
int divide1 = (Integer) me.getValue()/2;

We could cast an object to Integer in Java using below code.
int value = Integer.parseInt(object.toString());

If you want to convert string-object into integer...
you can simply pass as:
int id = Integer.valueOf((String) object_name);
Hope this will be helpful :-)

Integer x = 11
int y = x.intValue();
System.out.println("int value"+ y);

Finally, the best implementation for your specification was found.
public int tellMyNumber(Object any) {
return 42;
}

first check with instanceof keyword . if true then cast it.

Related

Casting a primitive vs Creating a object of the primitive

I'm not habitual to casting a primitive data type to an object. Saw some code like:
public static int CompareAges(Person p1, Person p2) {
Integer age1 = p1.getAge();
return age1.compareTo(p2.getAge());
}
The instantiation of age1 seemed extraneous, so I tried to write the code as:
public static int CompareAges(Person p1, Person p2) {
return p1.getAge().compareTo(p2.getAge());
}
But that raised a compiler error because p1.getAge() is a primitive data type int and not an Integer, which is an object.
Intuitively, I did:
public static int CompareAges(Person p1, Person p2) {
return ((Integer) p1.getAge()).compareTo(p2.getAge());
}
and it worked!
The question: What did I miss? Since when did we start casting primitives as value types?
It's what happens internally:
1. Integer age1 = p1.getAge();
Integer != int
Integer = Integer.valueOf(int)
Integer age1 = Integer.valueOf(p1.getAge());
2. p1.getAge().compareTo(p2.getAge());
int.compareTo(int)
^^^
// it's just a primitive type, as a result - the compile error
3. ((Integer) p1.getAge()).compareTo(p2.getAge())
Integer.compareTo(int)
Integer.compareTo(Integer.valueOf(int))
((Integer) p1.getAge()).compareTo(Integer.valueOf(p2.getAge()))
4. (Integer) p1.getAge() ---> Integer.valueOf(p1.getAge())
// why so? look at callOfCode's answer
But, in my opinion, ((Integer) p1.getAge()).compareTo(p2.getAge()) looks ugly.
I would replace it to
p1.getAge() > p2.getAge() ? 1 : (p1.getAge() < p2.getAge() ? -1 : 0)
or to
Integer.compare(p1.getAge(), p2.getAge()) // java 7+
I wouldn't like to do casting in this case.
More about "autoboxing/unboxing" you may find here.
Each primitive has its own boxing type
The Boxing could be implicit (Autoboxing) or explicit like you did it in your code.
p2.getAge() is an Example of AutoBoxing or Implicit Boxing. The method compareTo takes an Object. As it is a primitive, Java converts it automatically to the correspondent Boxing Object (Integer). You did the explicit Boxing with the cast (Integer) p1.getAge()
Difference between new Integer(primitive); and Integer integer = (Integer)primitive; Is only on bytecode level. In the first case, new object of Integer class is created in memory. In the second case, Integer.valueOf(primitive) is called internally. This is the static method that checks if primitive falls into range of -128 to 127 and if it falls, it returns value from integer cache and no new object is being created. If it not falls into that range, new Integer object is instantiated. It is used for efficiency. But such efficiency is unsignificant novadays.
int z = 1;
Integer a = (Integer)z;
Integer b = (Integer)z;
//Prints true, since Integer object is retrieved from cache (range of -128 to 127)
System.out.println(a == b);
int w = 999;
Integer c = (Integer)w;
Integer d = (Integer)w;
//Prints false, since 999 is not in cache, new Integer objects are instantiated and they points to different places in memory
System.out.println(c == d);

Is there a Integer class in c#?

We have Integer class in JAVA, but I couldn't find any equivalent class in C#? Does c# have any equivalent? If not, how do I get JAVA Integer class behavior in c#?
Why do I need this?
It is because I'm trying to migrate JAVA code to c# code. If there is an equivalent way, then code migration would be easier. To addon, I need to store references of the Integer and I don't think I can create reference of int or Int32.
C# has a unified type system, so int can be implicitly boxed into an object reference. The only reason Integer exists in Java is so that it can be converted to an object reference and stored in references to be used in other container classes.
Since C# can do that without another type, there's no corresponding class to Integer.
Code migration won´t work out of the box for any type of language without any manual changes. There are things such as a class Integer that simply does not exist within (C# why should it anyway, see recursives answer), so you´d have to do some work on your own. The nearest equivalent to what you´re after is Int32 or its alias int. However you may of course write your own wrapper-class:
public class Integer
{
public int Value { get; set; }
public Integer() { }
public Integer( int value ) { Value = value; }
// Custom cast from "int":
public static implicit operator Integer( Int32 x ) { return new Integer( x ); }
// Custom cast to "int":
public static implicit operator Int32( Integer x ) { return x.Value; }
public override string ToString()
{
return string.Format( "Integer({0})", Value );
}
}
The beauty of C# is that it has a unified type system. Everything derives from object, even primitive types. Because of this, all keywords are simply aliases for a corresponding class or struct. Java does not use a unified type system, so a separate Integer class is required to wrap the int primitive. In C# int is synonym for the Int32 struct.
What you're looking for has been right in front of you the whole time. Start using the dot notation directly on the int keyword (i.e. int.whatever()) to access the all goodness of the .NET version of the Javian Integer class.
I did some testing with Nullable types in a console application and it appears that they do not behave as you wish. For example:
static void Main(string[] args)
{
int? x = 1;
Foo(ref x);
Console.WriteLine(x);//Writes 2
}
private static void Foo(ref int? y)
{
y += 1;
var l = new List<int?>();
l.Add(y);
l[0] += 1;//This does not affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 2
Foo2(l);
}
private static void Foo2(List<int?> l)
{
l[0] += 1;
Console.WriteLine(l[0]);//writes 4
}
But if you roll your own generic class to wrap primitive/value types for use within your application you can get the behavior you are expecting:
public class MyType<T>
{
public T Value { get; set; }
public MyType() : this(default(T))
{}
public MyType(T val)
{
Value = val;
}
public override string ToString()
{
return this.Value.ToString();
}
}
static void Main(string[] args)
{
var x = new MyType<int>(1);
Foo(x);
Console.WriteLine(x);//Writes 4
}
private static void Foo(MyType<int> y)
{
y.Value += 1;
var l = new List<MyType<int>>();
l.Add(y);
l[0].Value += 1;//This does affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 3
Foo2(l);
}
private static void Foo2(List<MyType<int>> l)
{
l[0].Value += 1;
Console.WriteLine(l[0]);//writes 4
}
int, int? and System.Int32 are all struct and thus value types and does not compare to Java's Integer wrapper class which is a reference type.
System.Object class though a reference type can cause issue as boxing creates immutable object. In short, you can't alter a boxed value.
int a = 20;
Object objA = a; //Boxes a value type into a reference type, objA now points to boxed [20]
Object objB = objA; //Both objA & objB points to boxed [20]
objA = 40; //While objB points to boxed [20], objA points to a new boxed [40]
//Thus, it creates another ref type boxing a 40 value integer value type,
//Boxed values are immutable like string and above code does not alter value of previous boxed value [20]
Console.WriteLine($"objA = {objA}, objB={objB}");
//Output: objA = 40, objB=20
What exactly corresponds to Java's Integer is a custom generic wrapper class.
int a = 20;
Wrapper<int> wrapA = new Wrapper<int>(a);
Wrapper<int> wrapB = wrapA; //both wrapA and wrapB are pointing to [20]
wrapA.Value = 40; //Changing actual value which both wrapA and wrapB are pointing to
Console.WriteLine($"wrapA = {wrapA}, wrapB={wrapB}");
//Output: wrapA = 40, wrapB=40
Console.ReadKey();
Implementation of the wrapper class is given below:
public class Wrapper<T> where T : struct
{
public static implicit operator T(Wrapper<T> w)
{
return w.Value;
}
public Wrapper(T t)
{
_t = t;
}
public T Value
{
get
{
return _t;
}
set
{
_t = value;
}
}
public override string ToString()
{
return _t.ToString();
}
private T _t;
}
As pointed out in other answers, C# has a unified type system so everything derives from object. If you need to handle null values then use int? to specify that the integer object can be null.
c# have a integer type called int link is here
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx

Casting int to Object on java

I have a question: I work in environment of Eclipse.
Sometimes the computer does not give to the following casting:
int a ...
Object ans = (int) a;
But only this conversion:
int a ...
Object ans = (Integer) a;
I understand why you can do the casting between Object to Integer, but why primitive variable - there are times when you can, and there are times you can not do a casting?
Thank you
I am attaching the code which the compiler not let me make casting between int variable to object:
/** #return minimum element */
public Object minimum(){
return minimum(this.root);
}
public Object minimum(BSTNode node){
if (node.left != null) return minimum(node.left);
return node.data;
}
/** #return maximum element */
public Object maximum(){
return maximum(this.root);
}
public Object maximum(BSTNode node){
if (node.right != null) return maximum(node.right);
return node.data;
}
public Object findNearestSmall(Object elem) {
int diff;
diff = (int)maximum() - (int)minimum();
if (compare(minimum(), elem) == 0) return elem;
else return findNearestSmall(elem, this.root, diff);
}
public Object findNearestSmall(Object elem, BSTNode node, int mindiff){
if(node == null) return (int)elem - mindiff;
int diff = (int)elem - (int)node.data;
if(diff > 0 && mindiff > diff) mindiff = diff;
/* Case 2 : Look for in left subtree */
if(compare(node.data, elem)>-1)
return findNearestSmall(elem, node.left, mindiff);
else
/* Case 3 : Look for in right subtree */
return findNearestSmall(elem, node.right, mindiff);
}
Before Java 1.5, you couldn't even do this:
int a;
...
Object x = (Integer) a;
The compiler would complain that a is of a primitive data type, and therefore cannot be cast to an object.
Starting with Java 1.5, Java introduced the concept of automatic boxing. So, the following became OK:
int a;
...
Object x = (Integer) a;
Because the compiler knows how to convert from a primitive int to the boxed type Integer automatically; and from Integer to an Object it's, well, not a problem.
However, what you're trying to do:
int a;
...
Object x = (int) a;
Is basically telling the compiler to avoid boxing. You explicitly tell the compiler to leave a as an int, and put a reference to that int into an Object. The compiler isn't designed to deal with such a case.
You cannot cast from a referenced data-type to a primitive data-type i.e. you cannot:
Object x = (int)a;
You can however do:
Object x = (Integer)a;
because Integer is a class and int is a primitive data-type.
If I assume it correctly, the functionality you want to achieve is get the integer's value from Object x which can be done as:
Object x = (Integer)a;
//Do something and somewhere else
int z = ((Integer)x).intValue();
This may through a ClassCastException if it is not of Integer class.
You should look into the difference between int which is a primitive type, and Integer, which is a wrapper class in Java.
An Integer is also an Object and stays as an Object on the Heap.
An int is a primitive type. It is NOT an Object. An Object has its own state and behavioral properties, int doesn't have those. So you get a compilation error when trying to convert an Object to a primitive. On the other hand, Converting an int to Object is possible because of Autoboxing
But I am able to execute the following code. I am using jdk 1.6 and the following code is not throwing me any errors or runtime exceptions.
int i=5;
Object test = (int)i;
System.out.println(test.getClass());
Output: class java.lang.Integer
int is a primitive type.
Way of declaration: int a = 5;
Integer is a wrapper class (it extends Object).
Way of declaration: Integer a = new Integer(5);
When you write
Integer a = 5;
compiler automatically converts it to
Integer a = new Integer(5);
This feature is called Autoboxing (since Java 5.0)
int can not be casted to Object as it is not a referenced data type (object) at all.
But it can be casted to other primitive types.
On the other hand, Integer can be casted to Object.
When you write
Object ans = (Integer) a;
compiler does autoboxing and then casts it.
Object ans = (int) a;
gives a compiler error because the cast to int is successful, but it can not be assigned to an Object reference.
Hope this helps.
Good luck.

What is the main difference between primitive type and wrapper class?

What is the difference between these two lines?
int pInt = 500;
and
Integer wInt = new Integer(pInt);
Or
Integer wInt = new Integer(500);
None.
That's the exact same thing. In the first case you just have a supplementary variable.
Note that with autoboxing you rarely need to have both an int and an Integer variables. So for most cases this would be enough :
int pInt = 500;
The main case where the Integer would be useful is to distinguish the case where the variable is not known (ie null) :
Integer i = null; // possible
int i = null; // not possible because only Object variables can be null
But don't keep two variables, one is enough.
In Java, an instance of a primitve class holds the actual value of the instance, but instance of a wrapper class holds a reference to the object. i.e. The address of the place where the object would be found.
When you write a program with this line:
Integer integer = 500;
The compiler changes it to this:
Integer integer = new Integer(500);
This process is called autoboxing. That is automatically putting a primitive-instance in a "box" of Integer. Hence, output of the following program:
public class PrimitiveToObject {
public static void main(String[] args) {
printClassName(1);
printClassName(1L);
printClassName((char)1);
}
public static void printClassName(Object object){
System.out.println(object.getClass());
}
}
is this:
class java.lang.Integer
class java.lang.Long
class java.lang.Character
Also this:
int i = integer;
changes into this:
int i = integer.intValue();
This is called unboxing.
As you can see above, the dot operator(.) is used on the variable named integer but not on i. That is: a wrapper's object can be dereferenced, but not a primitive instance.
Boxing and unboxing may slow down the program a little bit. Hence, to a newbie, wrappers may look like added burden, but they are not so. Wrappers are used at places where the object needs to be a reference type. eg: Map<Integer,String>map=new HashMap<Integer,String>(); is a valid statement, but Map<int,String>map=new HashMap<int,String>(); is not a valid statement.
Another typical case where wrapper is very useful: In MySQL, NULL is a valid entry for a column of INT type. But in Java, int cannot have a null value, Integer can. This is because in SQL NULL symbolises Not Available. So if you are using JDBC to insert integer values in a MySQL table, a null in your java program will help in inserting NULL in the MySQL table.
A wrapper class can also be useful in a case similar or anologous to this:
Boolean decision; // Using wrapper for boolean.
if("YES".equalsIgnoreCase(consent))
decision = Boolean.TRUE; // In favour
else if("NO".equalsIgnoreCase(consent))
decision = Boolean.FALSE; // Not in favour
else if("CAN'T SAY".equalsIgnoreCase(consent))
decision = null; // Undecided
For starters
int pInt = 500; , here pInt is not an object whereas in
Integer wInt = new Integer(500);
wInt is an reference
This is also a reason why java is not pure Object Oriented Language. Because everything is not object with java.
Wrapper class will have a box in that box it will cover the primitive data types there are 8 primitive data types namely byte,int ,long ,double, float, short ,Boolean ,char these all covered in wrapper class .
to use primitive data types we use like int a;
but to use wrapper class we need to use like Integer a = new Integer(i);
The types of data are the same, but there are situations that manipulation of objects is more convenient than primitive types, like data structures, where you need more control of your data types.
For example, objects can be null and primitive types can't.
You also can't call methods in a primitive type (.compareTo(), .equals(), ...), but in wrapper classes you can.
The information below describe the types in primitive and wrapper class:
Primitive Types | Wrapper Class (Superclass = Object)
boolean - Boolean
char - Character
Primitive Types | Wrapper Class (Superclass = Number)
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
To understand how the wapper classes works, consider the example below:
public final class IntWrapper {
private final int intVal;
IntWrapper(int intVal) {
this.intVal = intVal;
}
public int getInt() {
return intVal;
}
}
Now we can make an object out of our new IntWrapper class and 'box' the primitive int value 41:
int i = 41;
IntWrapper iw = new IntWrapper( i ); // box the primitive int type value into the object
i = iw.getInt(); // unbox the value from the wrapper object
My example IntWrapper class is immutable, immutable means that once its state has been initialized its state cannot be changed.
When the final keyword is applied to a class, the final class cannot be extended. In other words, a final class can never be the superclass of a subclass. A final class can be the subclass of superclass, not problem there. When a class is marked final, all of its methods are implicitly final as well.
It is important to note that when final is applied to a reference variable it does not prevent the members of the object instance from changing values.
This example is to better understanding how the wrapper classes works inside.
Next, to create Integer, Double and other wrapper classes, you can write:
Integer i = new Integer(4);
Double d = new Double(9.62);
Boolean b = new Boolean("true");
Character c = new Character('M');
To get the encapsulated number into wrapper objects, you can write:
long l = i.longValue();
double e = i.doubleValue();
float f = d.floatValue();
short s = d.shortValue();
Each wrapper class include special methods to convert between primitive type to wrapper objects, that represent not number values:
boolean bo = b.booleanValue();
char ch = c.charValue();
Up to Java 5 version, the creation of objects from wrapper classes had to be in the syntaxes like above, but to simplify these operations, mainly related to insertion of values in the data structures offered in Java collections (that only accept objects), now exists the autoboxing or boxing and autounboxing or unboxing options.
The autoboxing or boxing allows you to insert a primitive value to reference of equivalent wrapper types or Object type:
// Same result of Double d = new Double(-2.75);
Double objD = -2.75;
// Same result of Object objI = new Integer(13);
Object objI = 13;
The autounboxing or unboxing allows you to insert a wrapper object into a variable of primitive type, converting automatically between equivalent types:
// Same result of double vd = objD.doubleValue();
double vd = objD;
// Same result of int vi = objI.intValue();
int vi = objI;
The most important practical difference I've seen is Integer is way more slower to initialize and do calculations with, than int. I would avoid Integer unless necessary.
int x = 20_000_000;// 20 millions
for (int i = 0; i < x; i++) {
ix += 23;
}
it takes 138 ms(average over 50 trials) to complete the loop when ix is an Integer but only takes 10 ms when ix is an int

How to assign an "Object variable" to an integer variable

I'm required to build a program in Java, while I have no idea about it.
I have an integer value stored in an object variable..
And I want to assign the value to another integer variable. but I can't find a way to convert an object to integer...
may you please help with this ..
thanks in advance ..
Here is my Code :
public class Bank extends unicastRemoteObject implements BankInterface
{
String[] columnNames = {"Account","Balance"};
Object[][] data = {{"a",10,},{"b",20}};
public Bank() throws RemoteException { //constructor
}
public int getRowCount() { // number of accounts
return data.length;
}
public Object getValueAt(int row, int col) { // returns the value of the cell
return data[row][col];
}
public void deposit(int account, int amount) throws RemoteException {
// work Description:
// find the tuple by searching about the account number
// add the amount to balance..
// conversions are needed
Object accnum; // to store the account number in. *string*
Object balancevalue; // to store the balance in. *integer*
for ( int i=0 ; i<=getRowCount() ; i++)
balancevalue = getValueAt(i,2)); // assign the current balance value..
accnum = getValueAt(i,1); // assign the account number..
int a = 0; // we will assign the integer type of accnum to a.
int b = 0; // we will assign the integer type of balancevalue to b.
if( a == account ) { // we find the account number.
b= b + amount ; // add the amount to the balance.
// we need to change the integer "b" into Object to store it in Data[i][2].
}
}
int to Object
int b = 10;
Object o = new Integer(b);
You can wrap your int into an Integer, which is a subclass of Object.
Object to int
Object o = new Integer(10);
int b = (Integer) o;
You can retrieve the value by casting o back to Integer. The JVM will then convert implicitely the Integer back to int.
Having something like Object[][] data is very bad design. Instead, you should have a class Account with fields accountNumber and balance with the approriate types. Then you have a List<Account>, everything is clean and typesafe, and the getValueAt() method becomes unneccessary.
Your data array already stores Object types - account number as String, balance as Integer (an Object wrapper for the primitive int). In your deposit method, you need to parse the account number String to an int value and get the primitive int value of the balance from the Integer.
Here is an example of how to make the conversions in the code you have shown.
for ( int i=0 ; i<=getRowCount() ; i++)
Integer balancevalue = (Integer)getValueAt(i,2));
String accnum = (String)getValueAt(i,1);
int a = Integer.parseInt(accnum); // parse String to int
int b = balancevalue.intValue(); // get primitive value of Integer wrapper
if( a == account ) { // we find the account number.
b= b + amount ; // add the amount to the balance.
// create new Integer (is an Object)
Integer newBalance = new Integer(b);
// store in the data array
data[row,2] = newBalance;
For the final step - conversion from int to Integer to store in the data array - you could rely on autoboxing instead of explicitly creating the Integer wrapper. So the last two lines of code could be replaced with this:
// store in the data array
data[row,2] = b;
You can use the Integer object which is a wrapper for an int primitive type.
Just do
Data[i][2] = b;
Auto boxing should work.
If you are using older version of java you can do
Data[i][2] = Integer.valueOf(b);

Categories