Eclipse how to convert automatically? - java

Say I have:
p.size = packetLine[0]; // where packetLine is of type String[] and element at that position is number represented by String
I don't want always to write
Integer.parseInt
or reverse
String.valueOf
Eclipse gives propositions to correct the error, can I make it to advice to convert the values?
At the moment it suggests to change the type. I would like third proposition 'Convert to Int' or 'Convert to String;
This is particularly annoying when repeating thousand times, I might just introduce my own method for converting like toInt or toString2, but in build solution would be better.

Yup, you're stuck with either a method on your class (toInt() like you suggested) or a static utility method. (Which is nice, if you prefer not to have lots of try/catch, you can choose to return 0 for malformed integers. Or whatever is appropriate. I like 0 instead of exception.)
The only "built-in" casting is turning anything to a String (with its toString() method), during concatenation. Like,
String s = "as a string, it is: " + anything; // and null becomes "null".
Sometimes you see this:
String s = "" + something; // shorthand
(Numeric types are implicitly cast for you, too. But mostly you're supposed to be type safe and all that.)

What you are asking for is not casting. Java uses the term casting for two operations:
Converting a numeric primitive to another numeric primitive by approximating the original value as much as possible e.g. int to double.
Storing the contents of an object reference variable to a more specific reference variable, if and only if the referred object can actually be stored there.
What you are asking for is conversion from String to a primitive type and vice versa. It does not usually make sense to provide shortcuts for this. There are more than one ways to do it and none is universal. E.g. a numeric String can be interpreted as an octal or a hexadecimal number and a float can be converted to a String with a varying number of floating point digits, depending on the required precision...
EDIT:
You might be able to make your life easier with repeated operations by creating custom editor templates in Eclipse. Editor templates are accessible along with the rest of the content assist proposals when you press Control+Space. Template creation is not always straightforward, but it can be quite helpful in some cases.

You can't add implicit casts in java, as the language doesn't support it, outside of primitive types / class hierarchies.

Related

Variable handling Functions in java

I'm new to the java language. I'm a php developer. There exist a lot of Variable handling Functions in the php language.
But I find it hard to imagine there aren't any built in functions that check whether value is numeric, is null, etc...
Can anyone explain why this is? Why does java not provide simple functions such as these?
PHP lets you store almost any value in any variable, and converts between types as necessary. Java does not automatically convert between most types - if you want a conversion, you have to do it yourself.
All of the is_something functions would be pointless - you know the type of a variable since you declared it!
If you have a reference to an object, you can determine the type of the object (not the variable) that it refers to using instanceof or reflection:
Object x = "hello";
// the variable x is of type Object, but it refers to a String. How can we tell?
System.out.println(x instanceof Integer); // prints "false"
System.out.println(x instanceof String); // prints "true"
System.out.println(x.getClass().getName()); // prints "java.lang.String"
However, most of the time, this simply isn't something you need to do.
So, all of the is_something functions are unnecessary, and all of the somethingval functions wouldn't fit well in the language (although there's no technical reason they couldn't exist). What else is there?
get_defined_vars - again, redundant. You know what variables are defined because you defined them!
empty (returns true if a variable doesn't exist or contains false). Using a variable that doesn't exist is a compile-time error, so you can just use thing == false (or !thing if it's a boolean) instead of empty(thing).
get_resource_type - the closest match in Java is thing.getClass().getName() instead of get_resource_type(thing).
gettype - useless for the same reason the is_something functions are useless.
import_request_variables - The language Java has no built-in concept of GET variables, POST variables or cookies. Even if it did, this wouldn't work very well, because you'd have to declare all the variables anyway.
is_null - use thing == null instead of is_null(thing).
isset - again, you can't use variables that don't exist. So just use thing != null instead of isset(thing).
serialize and unserialize - Java has a serialization system, which is more complex but more flexible. Look up ObjectOutputStream and ObjectInputStream.
settype - makes no sense, as the type of a variable cannot be changed.
strval - use String.valueOf.
unset - makes no sense. Variables exist until the end of their scope.
print_r and var_dump and var_export - the only ones that might actually be useful and don't already exist. Sadly, it just doesn't exist, though you can get something similar if you override toString in all of your classes.
But i imagine any in build function is not check a value is numeric, is null, etc...
Why java is not provide simple functions such like this?
First reason: Java supports method overloading.
In Java, you typically don't write a single method that handle all sorts of arguments with all sorts of different types. Instead, you can write multiple overloads of the same method: same method name with different declared argument types, and/or different numbers of declared arguments.
The compiler sorts out at compile time which overloaded method to call based on the static types of the argument expressions.
In this model, there is no need to a bunch of functions for sorting out whether values are numeric, null, etcetera.
Second reason: Java does not allow primitive types and object types to be used interchangeably.
For example you cannot declare an argument type that would accept both an int value and a String value. And an int argument type can never accept a null.
(Actually, the primitive wrapper classes like Integer and Java 5's addition of autoboxing / unboxing tend to blur the distinction. But the underlying hard distinction between primitive and reference types remains. Autoboxing is syntactic sugar.)
Third reason: There is instanceof and testing for == null.
As #Malik points out, in the cases where the tests do make sense in Java, they can be implemented with built-in constructs, without resorting to library "functions". The functions are unnecessary.
(AFAIK, no mainstream 3rd-party utility library has implemented the equivalent of the PHP functions you are talking about ... which supports the view that they are unnecessary. If enough people thought the functions were necessary, there would be a library and we would know about it.)
It is also worth noting that most of the "variable handling functions" are to do with dynamically declared variables in PHP. Java doesn't support that. If you want to implement a dynamic binding between names (strings) and values in Java, use a Map class.
PHP as you are aware doesn't tend to care what you store in a variable, you declare a name, give it a value and it will try and interpret it itself. In Java, you explicitly declare the type of variable you would like.
Something like an integer (whole number) can be presented by the primitive data type int, so you could use
int myNumber = 7;
And the code would know for sure that this is an integer, as you have explicitly stated that this is the case. Refer to this page for other java primitives.
If you are using a String (which is an object) in Java, you can use the function isEmpty() to determine if there are any characters in it. You can do a check on objects in Java to see if they have been instantiated by using object == null.
Some compilers will actually give you warnings if you have not initialised variables before you check them, whether these are objects or primitives.
To get a good feel of how data types work in Java, refer to the Oracle documentation I linked, it is very useful, and ill contain a lot of information of other aspects of Java you may have questions with.
First of all why check variable type when you explicitly define a variable with a type. Secondly, you can check the type in Java although you should already know the type.
Integer x = 3;
if (x instanceof Integer) {
System.out.println("Integer");
}
String s = "test";
if (s instanceof String) {
System.out.println("String");
}

Explicit type casting vs using suffix for float/double Java - difference?

Based on the snippet below:
// as primitive
MyClass.primitiveMethod(double val); // method signature
MyClass.primitiveMethod(12); // ok
// as object
MyClass.objectMethod(Double val); // method signature
MyClass.objectMethod(12); // error
MyClass.objectMethod(12d); // ok
MyClass.objectMethod((double)12); //ok
Q1: While both 12d and (double)12 seem to work, are there any difference between specifying suffix and explicit casting? (behaviour/performance)
Q2: Why MyClass.objectMethod(12) must be considered an error? While 12 is supposed to be resolved to an Integer object, can't Java be smart enough to know that 12 is also a value Double value and just accept it?
For the first question: I'd expect the conversion to double to be performed by the compiler, but I wouldn't like to say for sure without checking. I'd use the suffix instead, for clarity. (If I need to check, that means anyone maintaining the code would have to check too... why not just use a literal of the right type to start with?)
12 is resolved to an int, not an Integer - and there's no implicit conversion from int to Double. Just because there's an implicit conversion from int to double and another from double to Double doesn't mean there's one straight there.
It could have been included, of course - but it would have meant making the language more complicated for a pretty small level of benefit.
Frankly, I never use 12d. To make it clear that a number is a double, I use 12.0. For floats, you have to say 12.0f.
It's one extra character to type, but I find it by far the most "natural". YMMV.
ADDED
As to your actual question, autoboxing primitives to and from wrappers can have unexpected results, (a great boon for the Java Puzzlers book!) and I prefer to avoid it as much as possible. If the method requires a Double, in the calling code I will usually explicitly make it so
objectMethod(Double.valueOf(12.0));
Although have to admit, that's a lot of typing for something relatively minor! However, when de-autoboxing (say, the method returns a Double) I almost always say
double d = result.doubleValue();
and it is worth it because it's a reminder that result is an Object and it might be null. When you get some unexplained NPE, say, the method returns null because the FooBarServer is not connected, this will help you realize what is going on. Or, even better, remind the original code to test for a null result first!
Use the suffix (literal)
It could be, but it seems it isn't. int isn't automatically wrapped in a Double
But most importantly - prefer primitives to wrappers.
A1: No, they end up both the same after the compiler is done with them.
A2: An int primitive is autoboxed to an Integer object. See the Java Language Specification, 5.1.7 Boxing Conversion. Would you rather Java guessed at what you meant and changed the Object class for you? No, it's far better that the programmer tells the machine what to do rather than have the machine guess at the programmer's intentions.
'12d' is a double literal. '(double) 12' is an operation on an int literal. You are not guaranteed that the latter will optimize to the former, not that it's likely to make a difference. The correctly typed literal is cleaner and more self-documenting, so use that. Why specify an unnecessary conversion?
For the first question, use the suffix, 12d is more brief and clear.
For the second... saying 12 you are using int, primitive and using Double you are speaking about an object (a wrapper for double) and they are not the same.

Java Language Design with toString

We did they make the decision to not implement a toString method for int[], but instead let it inherit the toString method from Object?
They did implement more reasonable toString methods for arrays. They are located in the java.util.Arrays class.
As for reasoning. I'm assuming by the overrides provided in the Arrays class, that trying to implement a generic toString for different types of arrays is either complex or impossible. The toString method would have to know what type of array it was working on, and output the data approrpiately. For instance, Object[] must use toString on each element, while char[] must output the character, and the numeric datatypes must be converted to a numeric string.
The methods in Arrays get this for free, because the types are fixed due to the overrides.
I guess because of the following reasoning: how would they know how users would want to present their array? It might "array size: 10" or it might be "[x,y,z]".
They gave you a default, if you want to make it something else it is easy to do.
You can use apache's ToStringBuilder make it easier...
http://commons.apache.org/lang/api/org/apache/commons/lang/builder/ToStringBuilder.html
My guess would be is that because Array objects weren't created in Java source code by the language designers - they are created by the Java compiler. Remember, you can have an array of any object type and so the compiler creates the Array object as appropriate for the type you require.
If they were to create a standard method, it's not immediately obvious how this should work. For example, executing toString() and concatenating the results might be OK for a small array but it doesn't work for a multidimensional array or an array with 1,000 entries. So I think no toString() method is created to keep all arrays consistent.
Admittedly, it is annoying and sometimes I do think something along the lines of "Array[" + size + "] of " + getClassName() would be so much better than the default.
A bit of guesswork here, but...
There isn't an obvious string representation of an int array. People do it in different ways: comma separated, space separated, enclose in brackets or parentheses or nothing. That probably drove the decision not to implement it in Java 1.1, along with it being low priority code (since anyone can implement a method to write an array as a string themselves very simply).
Now you can't upgrade it in Java 1.2 or later because that would break back compatibility for anyone already using the old behaviour. You can however add a utility class that implements some functionality, and that's what they did with java.util.Arrays.

Creating Nullables types in java

I am trying to create a nullalble object in Java but no idea how to do this , in C# this would be done like this
int? someTestInt;
This allows me to check for for null , while in certain cases i can use a 0 value ,this isnt always possible since certain execution paths allow 0 values
I'm not entirely sure what you want, but if you want to have an integer value that also can be declared null, you probably want to use the Integer class:
Integer nullableInteger = 1;
nullableInteger = null;
System.out.println(nullableInteger); // "null"
There are corresponding classes for each primitive: Character, Long, Double, Byte, etc. The 'standard library' numeric classes all extend the Number class.
Note that Java autoboxes these objects automatically since JDK 1.5, so you can use and declare them just like the primitives (no need for e.g. "new Integer(1)"). So, although they are technically objects (and, therefore, extend the Object class, which the primitive int type does not), you can do basic arithmetics with them. They are converted to object operations at compile time.
Java does not support nullable primitives. You can use the Integer type if you want the ability to store nulls.
(This is a duplicate of this post:
How to present the nullable primitive type int in Java?)
Perhaps try the Integer type in Java.

What is the technical name of the syntactic feature "long foo = 12L;" style casting of harded-coded values in Java?

Today, I was trying to cast a hard-coded value into a short and S did not work. So, I went to search for it, but I realized that I do not even know what this feature of Java's syntax is called. Is there a name for it? If not, is there at least a list of all of the possible ways to cast hard-coded numeric values?
Epilouge
After getting the answer "Literals", I was able to answer my question about shorts. In case you are wondering, there is no short literal in Java. You just have to explicitly cast it as so: (short)12.
They are called literals.
From the Primitive Data Types page of The Java Tutorials:
A literal is the source code
representation of a fixed value;
literals are represented directly in
your code without requiring
computation.
There's a list of literals that can be used in the Primitive Data Types page under the Literals section.
Section 3.10: Literals of the Java Language Specification, Third Edition has a complete list as well.

Categories