Why does this print exception? - java

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);

Related

Where is an uninstantiated Integer number going to be located in memory?

I have a question; I don't know if it is dumb or not...but I will ask anyway.
We all know that when we say
String name = "someName";
we know that this is a pooled string so it's not going to get on the heap but...
if we say
Integer integer = new Integer(888);
we know this is going to get on the heap...
then
Integer otherInteger = 444;
where is "otherInteger" going to get? what memory location?
Thanks!
String name = "someName"; String is immutable class and String type is reference or non-primitive type, so name reference point to "someName" object, which is placed in "String-constant- pool", in heap.( no stack).
Integer is wrapper class( provides the mechanism to convert primitive into object and object into primitive).
The code Integer otherInteger = 444; is an example of auto-boxing (https://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html) and compiler automatically converts this line to Integer otherInteger = Integer.valueOf(444); . So, Integer otherInteger= Integer.valueOf(444) return Integer object i.e this placed in heap.

Java Cast from Object to long to String

Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?
You can just do
String str = map.get("id").toString();
Use, for instance:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
But since the values of your map will be Longs anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at #BheshGurung's answer...
You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();
You have 2 issues here:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
Use this:
String str = ((Long)map.get("id")).toString();

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.

Why cannot cast Integer to String in java?

I found some strange exception:
java.lang.ClassCastException: java.lang.Integer
cannot be cast to java.lang.String
How it can be possible? Each object can be casted to String, doesn't it?
The code is:
String myString = (String) myIntegerObject;
Thanks.
Why this is not possible:
Because String and Integer are not in the same Object hierarchy.
Object
/ \
/ \
String Integer
The casting which you are trying, works only if they are in the same hierarchy, e.g.
Object
/
/
A
/
/
B
In this case, (A) objB or (Object) objB or (Object) objA will work.
Hence as others have mentioned already, to convert an integer to string use:
String.valueOf(integer), or Integer.toString(integer) for primitive,
or
Integer.toString() for the object.
No, Integer and String are different types. To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object.
For int types use:
int myInteger = 1;
String myString = Integer.toString(myInteger);
For Integer types use:
Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();
No. Every object can be casted to an java.lang.Object, not a String. If you want a string representation of whatever object, you have to invoke the toString() method; this is not the same as casting the object to a String.
You can't cast explicitly anything to a String that isn't a String. You should use either:
"" + myInt;
or:
Integer.toString(myInt);
or:
String.valueOf(myInt);
I prefer the second form, but I think it's personal choice.
Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.
Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.
Objects can be converted to a string using the toString() method:
String myString = myIntegerObject.toString();
There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.
You should call myIntegerObject.toString() if you want the string representation.
Casting is different than converting in Java, to use informal terminology.
Casting an object means that object already is what you're casting it to, and you're just telling the compiler about it. For instance, if I have a Foo reference that I know is a FooSubclass instance, then (FooSubclass)Foo tells the compiler, "don't change the instance, just know that it's actually a FooSubclass.
On the other hand, an Integer is not a String, although (as you point out) there are methods for getting a String that represents an Integer. Since no no instance of Integer can ever be a String, you can't cast Integer to String.
In your case don't need casting, you need call toString().
Integer i = 33;
String s = i.toString();
//or
s = String.valueOf(i);
//or
s = "" + i;
Casting. How does it work?
Given:
class A {}
class B extends A {}
(A)
|(B)
B b = new B(); //no cast
A a = b; //upcast with no explicit cast
a = (A)b; //upcast with an explicit cast
b = (B)a; //downcast
A and B in the same inheritance tree and we can this:
a = new A();
b = (B)a; // again downcast. Compiles but fails later, at runtime: java.lang.ClassCastException
The compiler must allow things that might possibly work at runtime. However, if the compiler knows with 100% that the cast couldn't possibly work, compilation will fail.
Given:
class A {}
class B1 extends A {}
class B2 extends A {}
(A)
/ \(B1) (B2)
B1 b1 = new B1();
B2 b2 = (B2)b1; // B1 can't ever be a B2
Error: Inconvertible types B1 and B2.
The compiler knows with 100% that the cast couldn't possibly work. But you can cheat the compiler:
B2 b2 = (B2)(A)b1;
but anyway at runtime:
Exception in thread "main" java.lang.ClassCastException: B1 cannot be cast to B2
in your case:
(Object) / \(Integer) (String)
Integer i = 33;
//String s = (String)i; - compiler error
String s = (String)(Object)i;
at runtime: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Use String.valueOf(integer).
It returns a string representation of integer.
Use .toString instead like below:
String myString = myIntegerObject.toString();

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