how to read appropriately on java document in terms of using methods - java

when I look at the java documents to see how to use methods.
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString()
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toString()
I find two methods that confuse me, first one is
static String valueOf(char[] data)
Returns the string representation of the char array argument.
that's the information I find on java docs, but I cannot find any information on how to use it, and how do I know I need to use String.valueOf() instead of something.valueof() based on java docs?
second method is
String toString()
This object (which is already a string!) is itself returned.
How do I know when it is to use Integer.toString() or something.toString() based on the information provided by java docs.
Could anyone tell me how to extract those information? This issue has bothered me for a long time. Happy holidays^_^

You need to have a method in a class before you can call it whether by using an instance of that class or using the class itself if it is static.
In the case here, valueOf() is only found in the String class and it is static so you can only call it using String.valueOf().
But that is not the case of toString() because it is not static and can be called through an instance like something.toString().
Basically they seem to perform the same function but valueOf() is treated special a bit. Such that it can take null values but toString() will throw a NullPointerException if variable of null value is used.

I cannot find any information on how to use String valueOf(char[] data), and how do I know I need to use "String.valueOf()" instead of something.valueof() based on java docs?
It's very straightforward. If you have a char array, and you want a String, you use this method. If you have something other than a char array, or you want something other than a String, you use a different method.
How do I know when it is to use Integer.toString() or something.toString() based on the information provided by java docs?
If you have an int or an Integer, and you want a String, then you use this method. If you have something that is not an int or an Integer, or you want something other than a String, you use a different method.
For instance, Double.toString() converts a double or a Double to a String.
Generally, you look at the class you want to convert to, and find a method that does the conversion. Sometimes, like the toString() method, the method is in the class you want to convert from.

Related

Is it possible to change a method's return type for the method chain?

I am implementing a method, myAssert(String s), it needs to behave like this,
condition1: it can work with isEqualTo(o) in a way of myAssert("test").isEqualTo(someObj) to check if they are 2 equal objects
condition2: it can work with startsWith(String s2) in a way of myAssert("this is a string").startsWith("this is")
Apparently myAssert needs to change its return type to be a string or an object. I know in https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html or https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html there are APIs to get information in a class.
But is there any API I can use to retrieve the information about the method channing?
Any comments are appreciated.

Use parseInt to create wrapper objects

I’m reading the book Beginning Java 9 fundamentals and in relation to creating wrapper objects the author says:
“All wrapper classes are immutable. They provide three ways to create
their objects:
1-Using constructors.
2-Using the valueOf() factory methods.
3-Using parseXxx() method, where Xxx is the name of the wrapper class. It is not available in the Character class.
The first and the second point I have clear, but the third I do not finish to understand it completely.
But the API says that Integer.parseXxx returns a primitive.
Does it make any sense?
The only way I see using parseXxx to create a wrapper object is to actually have the target type be a wrapper type itself. i.e:
Integer number = Integer.parseInt("123");
Yet, parseInt is not really creating a wrapper object but rather the value returned by parseInt is being autoboxed to its corresponding wrapper type.
Yes, the static method Integer.parseInt(String) attempts to parse the given string into a primitive integer. Failing to do that, it will throw an exception.
So basically, there is no need to wrap it, as it guaranteed either succeeding, or "letting you know" it couldn't by throwing.
A look at the source code of Integer class confirms that Integer.parseInt returns int primitive. Below is how the method signature,
public static int parseInt(String s, int radix)
The api basically Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, for api to work.
And it can be used as below, in java program, to get the int primitive from String
int newInt = Integer.parseInt("99");

how to make a string variable to have only few predefined values in java

I want to create a class that define a string variable which can have only few predefined value.
public class Constraint{
String const; // I want this constraint value to be fixed to either of {greaterthan,lesserthan,greaterthanequalto or lesserthanequalto}
public Constraint(String const){
this.const = const;
}
}
Program should throw an error if any other value is sent.
I wan to use something like enum over here, but i want to do so for Strings.
The concept you are looking for is called Enum.
Simply do not try to re-invent a less powerful, less "standard" workaround.
Seriously: enums give you compile time safety. Use them.
The alternative would be that your "constant" class contains a final, fixed Set of "valid" strings; and you simply check in your "setter" that incoming strings are listed in that Set. And of course, you should make sure that users of your constant class can access the content of that Set, so they can "know" those valid strings when they need to.

Is it better to do toString() or cast the Object to String [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
(String) or .toString()?
I have an Object. Is it better to do like this
final String params = myObject.toString();
or
final String params =(String)myObject;
ToString will work with all objects (as long as they are not null). If you cast to a String then the object has to be a String, otherwise it will fail. So my guess is that you want a toString() call, but it depends on what you want to do!
It depends what you're trying to do.
When you cast the object to string like (String)myObject you're actually trying to convert the object to a string, so you can get the class cast exception.
However, when calling myObject.toString you get a logical representation in String format of that object and it depends on implementation of toString() method of that object.
When you use (String)request.getAttribute("buyertosellerpersoni d") request.getAttribute("buyertosellerpersonid") returns you an object which you typecast into a String object. Incase the object that you're trying to typecast isn't actually a String object, you'll get a ClassCastException. Make sure that you always set the attribute "buyertosellerpersonid" with a String value.
When you use request.getAttribute("buyertosellerpersonid").toString()
the toString() method of the object returned by request.getAttribute("buyertosellerpersonid") is called.
Now it depends on the implementation of the toString() method of this object as to what it will return. If it is a string that you've put in the attribute "buyertosellerpersonid" then you'll get the String value. If it is anything else, then you'll get the unsigned hexadecimal representation of its hashcode.
It is always a better idea to typecast the object. This makes sure that you always get the correct object, and it will throw an exception otherwise. You must catch such exceptions to ensure correct functioning of your program.
(String)myObject works fine only if myObject is instance of class String.
In the case of myObject.toString() calls toString() method of class myObject. toString method is inherited from Object class.
It is totally irrelevant and pointless
performance questions to worry about.
Who reallycares? The chances of it making any difference to your overall
algorithm are vanishingly small. Use the one that makes most sense in
your code.
One more thing , There is a difference in the two, you can only cast if object really is a String
object whereas you can call toString() on any Object, not just a String.

JSR223: Calling Java "varargs" methods from script

I have a method that looks like this on Java:
public void myMethod(Object... parms);
But I can't call this method as expected from the scripts.
If, in ruby, I do:
$myObject.myMethod(42);
It gives me org.jruby.exceptions.RaiseException: could not coerce Fixnum to class [Ljava.lang.Object
If I try the following in Javascript:
myObject.myMethod(42);
Then it gives me sun.org.mozilla.javascript.internal.EvaluatorException: Can't find method MyClass.test(number). (#2) in at line number 2
Of course, if I change the signature to take one single object then it works.
I assume that this is because someone along the line does not know how to convert, say Integer to Integer[] with the value at the first position.
I believe something like myMethod({42, 2009}) would work in Ruby, but this seems ugly - I wanted to be able to just do myMethod(42, 2009) to make it less confusing, specially for other languages. Is there any better workaround for this?
Thanks.
Java internally treats the variable-length argument list as an array whose elements are all of the same type. That is the reason why you need to provide an array of objects in your JRuby script.
It works like this:
myMethod [42, 2009].to_java
The to_java method constructs a Java array from a Ruby array. By default, to_java constructs Object arrays as needed in this case. If you need a String array you would use
["a","b","c"].to_java(:string)
More on this at the JRuby wiki
It seems like this is a known bug in jruby. See method dispatch on Java objects / classes should try to find a matching varargs method and NameError thrown when trying to pass argument to a Java method that is defined as having variable length arguments.
According to the link Rhino does support vararg.
Varargs are handled by the compiler as an Object[] which is what the error message describes.
I do not have JRuby experience, but does it work if you have an array argument?

Categories

Resources