(String) Meaning in Java - java

Decided to edit this question.
(String) refers to casting.
Ex:
protected String methodA(Vector X) {
return (String) X.get(0);
}
In this case the get method returns an object, and for the methodA to return a String there needs to be a cast to String. And the cast is done as demonstrated.

To my understanding, the (String) is a cast to string. Without being into the details, I suppose that the return type of get is Object, even if the contents are of String type. The cast is necessary to match the return type of method.

This method returns first element in the Vector cast to String.

If X.get(0) returns an Object but the underlying is String then another way besides (String) X.get(0) is to use X.get(0).toString(). That might be more familiar.

Related

Why is it necessary to cast an enumeration element to a String when printing it out?

Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
out.print(paramName);
}
From the above code I don't understand why the typecast of paramNames.nextElement() to String is necessary. Can some one explain this?
When I pass the parameter name from a form it is already in a String, then why do we use (String)?
Enumeration is a generic type, and should typically be used with a proper generic parameter. For example an Enumeration of Strings:
Enumeration<String> paramNames = ...;
This makes the signature of the nextElement() method look like this:
public String nextElement();
The reason they cast to a String is because that without a generic parameter, the compiler treats it as if you'd typed:
Enumeration<Object>
So the return type of nextElement() becomes Object, and you can't just assign an object to the String variable paramName.
Of course, if request.getParameterNames() doesn't return Enumeration<String>, but just Enumeration, then you can't do any better than that.
Because paramName is a String, you're telling the compiler to trust you that you know what you're doing and paramNames.nextElement() will definitely return a String. Your code will compile but might crash during runtime if paramNames.nextElement() will have an object of type that cannot be cast to String. Note that if you have Enumeration<String> then the cast is redundant.

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

Indicate datatype from a input string?

For example i have a string input "int",can i declare a variable base on that input?
(Not switch check please). I mean something like this (pseudo-code) or similar:
String str="int";
new (variable_name,"int");
// create new variable with int datatype.
You can do this:
String className = "MyClass";
Object obj = Class.forName(className).newInstance();
But it won't work for primitive types.
If instead of using primitive types you will use cannonical name of Object based class you can try to do this
public Object loadClass(String className) {
return Class.forName(className).newInstance(); //this throw some exceptions.
}
Not practically, Java is strongly typed and the type of all variables must be known at compile time if you are to do anything useful with them.
For example, you could do something like this;
String str = "java.lang.Integer";
Class clazz = Class.forName(str);
Object o = clazz.newInstance();
..which will give you an Object o whose type is determined at runtime by the value of the String str. You can't do anything useful with it though without first casting it to the actual type, which must be known at compile time.

how to cast string to integer at runtime

I am using reflection in java.
I am getting to know the type of method parameter I am passing at run time. So I am fetching the parameter value from file into a string variable.
SO now if i get to know that the parameter type as integer and if i pass an object containting the string value I am getting
argument type mismatch
java.lang.IllegalArgumentException: argument type mismatch
Class classDefinition = Class.forName("webservices."+objectName);
String methodName = set"+fieldNameAttay[i].substring(0,1)).toUpperCase()+fieldNameAttay[i].substring(1); Field f = classDefinition.getDeclaredField(fieldNameAttay[i]);
try
{
//argType = f.getType();
Method meth = classDefinition.getMethod(methodName,f.getType());
Object arg = new Object[]{fieldValueArray[i]}; //fieldValueArray[i] is always string array
meth.invoke(object, arg); //If f.getType is Integer this //throws ex
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
You can't cast a string to an integer - you can parse it though. For example:
if (parameterType == int.class && argumentType == String.class)
{
int integerArgument = Integer.parseInt((String) argumentValue);
// Now call the method appropriately
}
Of course, you also need to consider Integer as well as int.
How about
Integer.parseInt((String) stringObj)
Note that casting can happen only if the two objects belong in the same hierarchy. So this is not casting.
If the only types you are using are String and Integer, checking the type and then using Integer.parseInt might be the simplest thing to do.
However if you have more different types, I would suggest checking out the good old JavaBeans framwork: http://download.oracle.com/javase/tutorial/javabeans/index.html
And especially the PropertyEditors
http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditor.html
http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditorManager.html
The PropertyEditors allow you to set the value as text, and then retrieve the value as correct type. Assuming you have implemented and registered the property editors, the steps to get the correct type are similer to this:
Find out the type of the parameter
Retrieve a PropertyEditor for that type
Use setAsText and getValue in the property editor to convert the value to correct type
...or You can just adapt the same mechanism to your simple needs by implementing your own conversion framework with similar but simpler interfaces.
System.out.println(Integer.parseInt(obj.toString()))
There's another way to do it:
Integer number = Integer.valueOf("1");

How to check whether an Object is String or String Array in java?

A method is returning a Object or Object[] of type String but if I am casting with String[], it is giving class cast exception when it contains single string. How can i resolve this?
Is there any way to check whether it contains String or String[]?
Sure, use the instanceof operator:
if (x instanceof String) {
...
}
if (x instanceof String[]) {
...
}
etc. It's not ideal to have to do this, mind you... is there any way you could redesign your API to avoid this?
Rewrite the method to always return String[], even when there's only a single one.
Better yet, have it return List<String> and use Collections.singletonList() for the single-element case.

Categories