Regarding casting of the outcome - java

I have a method which return type is string below is the method
public String getHwIdentifier();
Now I am using this method ..
String s = till.getHwIdentifier();//return type of this method is string
I want to cast it in integer that is something like this
Int i = till.getHwIdentifier();
Please advise how take integer means how to cast it..

try parseInt from Integer class.
Integer.parseInt(till.getHwIdentifier());
but mind you, it'd throw NumberFormatException if the string is not a valid integer representation

Use parseInt(String s) method of Integer class which takes String and converts it to intif it is a number or throws NumberFormatException like this :
int i = Integer.parseInt(till.getHwIdentifier());

Pass the instance of the String to Integer.valueOf(String s).
So in your case:
Integer i = Integer.valueOf(till.getHwIdentifier);
See http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28java.lang.String%29 for more details.

There is no Java type/class named Int. There's int type and it's encapsulating Integer class.
You can parse an integer in a String to the int value with Integer.parseInt("1234");, or get the Integer value with Integer.valueOf("1234");. But notice if the String doesn't represent an integer you'll get a NumberFormatException.
String s = till.getHwIdentifier();//return type of this method is string;
try
{
Integer a = Integer.valueOf(s);
int b = Integer.parseInt(s);
}
catch (NumberFormatException e)
{
//...
}
Note: You could use Integer a = Integer.decode(s);, but Integer c = Integer.valueOf(s); is preferred as it won't create new objects if possible.

String s = till.getHwIdentifier();
int i = Integer.parseInt(s);
Make sure that your string is in the form of an integer. If your string contains xyz then you will get a java.lang.NumberFormatException.

Related

Can the integer once converted to String using toString() method be reconverted back to Integer? [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
public class ArrayManipulations {
public static void main(String[] args) {
String name = num.toString();
System.out.println(name); // want to convert this back to int
System.out.println(num.getClass().getName() + '#' + Integer.toHexString(num.hashCode()));
}
}
Now i want to convert the name back to integer.
is it possible???
Yes.
int i = Integer.parseInt(name);
Yes you can
Return an Object Integer :
Integer var = Integer.valueOf("0");
This method returns the relevant Number Object holding the
value of the argument passed. The argument can be a primitive data
type, String, etc.
Return a primitive int :
int var = Integer.parseInt("0");
This method is used to get the primitive data type of a certain
String. parseXxx() is a static method and can have one argument or
two.
The Integer class provides the following method for this task:
Integer.parseInt(String s);
Yes.
Integer.parseInt(Integer.toString(3));
should do the trick.
More in the Java Documentation.
If you want to convert String to int, you use:
int intNum = Integer.parseInt(name); //name is variable that you want to change back to int

Java program returns error: incompatible types: int cannot be converted to String

Why does this program return error: incompatible types: int cannot be converted to String ?
public class StringConcatenation{
public static void main(String []args){
int[] testing = {0,1,3,4,5,6};
String mark = "";
for(int i=0;i<testing.length;i++)
{
// mark += testing[i]; But this line works fine
mark = testing[i]; /* This line doesn't work */
}
System.out.println(mark);
}
}
StringConcatenation.java:8: error: incompatible types: int cannot be converted to String
mark = testing[i];
The first way uses string concatenation, which is special cased in the Java language to allow you to use any object or primitive type. However, you cannot just assign a random value to a String.
The + operator can handle a string and an integer, converting the integer to string before concatenating. But you can't assign an integer to a string. Has nothing to do with using an array.
The operation += which translates to addition over its current value, converts integer to string and then concatenates it to the current state of string. However when you try to assign an integer value to a reference which is of type string, compiler will throw an error.
There are languages that will do even this for you, but it just does not work like that in a strongly typed language like java.

Trying to read Integer from JSON file in java

I am trying to read a JSON file to create a new Object. I can read all the Strings in it but i throws a ClassCastException when trying to read an int. Here is the JSON file.
{"id1" : "string1",
"id2": "string2",
"id3": 100.0
}
And here is the java code.
public static Aparelho novoAparelho(JSONObject obj) {
Aparelho ap = null;
String tipe = (String) obj.get("id1");
String name = (String) obj.get("id2");
if(tipe.equals("anyString")) {
int pot = (int) obj.get("id3");
ap = new SomeObject(name, pot);
}
return ap;
}
It throws.
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Cast it to double first:
int pot = (int) (double) obj.get("id3");
ap = new SomeObject(name, pot);
Confusingly, there are three kinds of casts:
Those that convert values of primitives
Those that change the type of a reference
Those that box and unbox
In this case, you have an Object (which is actually a boxed Double), and you want a primitive int. You can't unbox and convert with the same cast, so we need two casts: first from Object to double (unboxing), and one from double to int (conversion).
Integers don't have decimal points.
You should be parsing for an int instead of casting as an int.
For example:
if (tipe.equals("anyString")) {
String pot = obj.get("id3");
int x = Integer.parseInt(pot);
ap = new SomeObject(name, x);
}
Since you know that the field is supposed to be an int, you can take advantage of the JSONObject api to handle the parsing for you:
if(tipe.equals("anyString")) {
int pot = obj.getInt("id3");
ap = new SomeObject(name, pot);
}
This is a bit more robust than the casting method -- if somebody changes the json that gets passed to you, the accepted answer might break.

String int variable clarification

I have received the following error message
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:45: error: incompatible types
number = decode(c);
^
required: int
found: String
1 error
in the beginning of the class i have
char c;
private int number = 0
This makes it an int so i understand that in order for the next line to compile i have to have two of the same data types. My understanding is that
str[1].valueOf(number);
number = decode(c);
public static String decode(char c){
switch (c) {
should make the variable NUMBER a string making decode and number equal data types because they are both strings.
I feel like i may be forgetting a step in order to make both strings data types. any thoughts?
char c = 0; //is not declared and initalized
number = Integer.parseInt(decode(c));
yes you are declaring number as Integer.
so you should cast it by using Integer.ParseInt.
You have the method public static String decode(char c) which returns a value of String, but the variable number accepts the value String which is declared as an Integer
Try having a return type of Integer like public static int decode(char c)
Your method returns a String.
You are trying to store that returned string in an int.
Java does not convert strings to integers automatically like this. You will have to do the conversion explicitly. You can use Integer.parseInt for this:
int number = Integer.parseInt(decode(c));
Note that a NumberFormatException will be thrown if the returned string isn't actually a valid integer.

How can i convert an object to an int in Java?

I'm working in Java and I would like to convert an Object to an int.
I do:
Collection c = MyHashMap.values();
Object f = Collections.max(c);
int NumOfMaxValues = Integer.parseInt(f);
But it's not working. It says:
No suitable method for parseInt.
How can I fix that?
Integer.parseInt()
expects a String. You can use
Integer.parseInt(f.toString())
and override the toString() method in your class.
Ideally, you should use generics to your advantage and have something along the lines of the below:
Map<Object,Integer> myHashMap = new HashMap<Object,Integer>();
Collection<Integer> values = myHashMap.values();
Integer value = Collections.max(values);
if (value != null)
{
int myInt = value;
}
You can't just convert any object to an int. How should that work. Think of a class like this:
class Car {
public String name;
public String owner;
}
You need to define a method yourself. Or you have to find out what specific object that is and how to convert it.
Integer.parseInt(f.toString());

Categories