Cannot cast from object to int - java

Even though I have done the exact same thing with an integer array, I seem to be getting an 'Cannot cast from object to int' error while passing the integer from a servlet to a jsp
In my JavaBean
public int getNoOfVotes(){
return noOfVotes;
}
In my servlet
int noOfVotes = bean.getNoOfVotes();
request.setAttribute("totalVotes", noOfVotes);
In my jsp
int votes = (int)request.getAttribute("totalVotes");
Its in the jsp I am getting the error

request.getAttribute returns Object. You cannot cast Object to a primitive type int. But you may cast it to Integer.

reality,the obj couldn't cast to int,there are two method to cast.
the one is cast to String,then use Integer.valueof();
the other one is Integer.parsetoInt()

Try using this
int no = Integer.parseInt(request.getAttribute("totalVotes"));
I hope this helps.

Related

Why does this print exception?

String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);

Cannot cast from int to MyClass

I have a problem in dealing with the conversion of integer to string. This is my code :
MyClass getRow;
getRow = (MyClass) getListAdapter().getCount();
I found an error on this line: Cannot cast from int to MyClass
This is my MyClass ListView Adapter :
public String toString() {
return myclass;
}
Solved
I have found a solution by adding a few tricks to convert an integer to a string, like this :
int i ;
i = getListAdapter().getCount();
String str = String.valueOf(i);
TextView totalRow = (TextView) findViewById(R.id.totalRow);
totalRow.setText(str);
thanks for all of your answers, awesome Stackoverflow !
int is a primitive and not a class, so the compiler is correct. Why do you expect that an int transform magically into MyClass? What are you trying to do here?
If I understand you correct, you must assing the value of getRow() to your class somehow (either via a setter, by constructor or by accessing the member) and then you can use MyClass. Of course if you want to convert the int to a String object, you have to convert it:
String s = String.valueof(integervalue);
You cannot cast an int to an Object. In the first row you mention you are exactly doing that. getCount() returns an int and you try to cast it to (MyClass).
You never cast primitives to objects in java.
No, you cannot cast this. However, you can achieve a similar effect if you create a constructor for MyClass which accepts an integer as input. So something like:
public MyClass(int x) {
// do stuff to convert as you see fit here
}
then when using it, you do:
getRow = new MyClass( getListAdapter().getCount());

cast type error from long to decimal type object

I having the following code and member value is type object and in this process = long and i want to cast it to big decimal ,when i trying the following code i get error:java.lang.Double cannot be cast to [C
} else if (typeName.equals("java.math.BigDecimal"))) {
return new SwitchInputType<BigDecimal>(new BigDecimal((char[]) memberValue));
The error message:
java.lang.Double cannot be cast to [C
tells you that this cast is illegal:
(char[]) memberValue
so don't do it. The error message tells you that memberValue is a Double, so this should work:
return new SwitchInputType<BigDecimal>(new BigDecimal((Double) memberValue));
Depending on the declared type of memberValue the cast may be completely unnecessary, though it sounds like the declared type is Object. Alternately, since there is a BigDecimal constructor which accepts strings, you could try to get away with this, though it's not really any less-smelly:
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.toString()));
The [C represents the type "array of char", and indeed, you can't cast a Double to an array of char, nor should you want to. According to the message, memberValue is a Double, so you just want to do
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue));
If you are getting that error, it means that memberValue is a Double. In this case, you should probably just use
new BigDecimal(memberValue)
but I'd have to see more code to be sure.
The error message means that memberValue is a java.lang.Double object, and you are trying to cast it to char[]. That doesn't work, because a Double is not a char[].
In this case, you can just remove the cast, and call doubleValue() on the Double object:
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.doubleValue()));
This way, you're using the constructor of BigDecimal that takes a double instead of a char[].
If the type of memberValue is Object, you'll have to cast it to Double first:
((Double)memberValue).doubleValue()

Java declaration confusion for datatypes

I have a doubt about null assigning to variable in Java. In my program I have assigned null to String variable as String str_variable = null;. For the learning purpose i assigned null integer variable as int int_variable = null; It shows error Add cast with Integer. So that rewrite the above int declaration as Integer int_variable = null;. This does not shows errors. I do not know the reason of these two kind of declaration.
Please the difference between to me.
String str_variable = null;
int int_variable = null; // error.
Integer int_variable1 = null; // no error.
String and Integer are both classes, in a way they are not native data types that is why it is always okay for you to set null as an initial value, however for int you must always initialize it with a number, one good way to find out their appropriate initialization value is to create variables outside your main(), example String var1; int var2; then use System.out.println(var1); System.out.println(var2); within the main()
to see what was placed as an initial value when you run the program.
int is a primitive, Integer is a class.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
int is a primitive type, Integer is a wrapper class type extending Object class. Non-referencing objects can be null but primitives cannot. That's why you get an error message saying you need casting.
You can use a line like int num = (Integer) null;, this is how casting is done, however you will get NullPointerException when you try to use num anywhere in your code since a non-referencing(null) Integer object doesn't hold / wrap a primitive value.

How convert an object to int

I want to convert an object to int type....
eg:
Object obj=........;
int count = Integer.parseInt((String) obj);
when i use above code ai got cast exception.
Anyone know how to cast object to int...?
Use obj.hashCode(), to get an int that represents the object. But what is your purpose? The code you posted does not work - you try to cast the object to a string rather than calling toString(), but even then, unless the toString representation of the object is itself an integer, calling Integer.parseInt on it will throw an exception.
So what are you aiming at?
If tableres is a Hashtable, the values are prolly Integer, not int.
In that case, try:
int i = ((Integer) tableres.get ("mCount")).intValue();
Good luck, - M.S.

Categories