Long to String in java - java

There is a code :
Long val = 10L
If I want to take its value as a String which approach is correct?
val.toString() or (String)val?

val.toString() would work.
If you are not sure if val can be null, you can also do String.valueOf(val)

You'd do it like this with the String class:
String s = String.valueOf(val);
If your Long might be null and you don't want to get a 4-letter "null" string, you might use Objects.toString, like: String s = Objects.toString(val, null);
You reverse it using Long val = Long.parseLong(String); but in this direction you need to catch NumberFormatException

You can also do:
Long.toString(val);
A typecast does not work since String is not a primitive datatype.

Related

Get Class name without package from StackTraceElement

I have this ste.getClassName() which return a String like this pack.age.Foo.
ste is StackTraceElement.
How I could get only Foo? Or the only way is to do a method which extract Foo from that string?
There isn't a built in method for that. You could break up the string like #Naya and #Daniel Perez suggested, or let Class to the heavy lifting for you:
String simpleName = Class.forName(ste.getClassName()).getSimpleName();
String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
String[] parts = ste.getClassName.split(".");
parts[2] will be the Foo value.
.split allows you to choose a value for which the string will be divided into an array depending on the position of the divider.

Java string set default value if null

Is there a proficient way to set a string to some default value if assignment gives nullPointerException?
Say im initializing a string like this:
String myString= jsonElement.getAsJsonObject().get("myString").getAsString();
If it gives nullPointer i need to give it a default value, i know i can do it with an "if" check after but is that the only way? It would mean alot of checks as i am initiating around 20 strings.
Is there any way to do it like:
String myString = jsonElement.getAsJsonObject().get("myString")
.getAsString() || "defaultValue";
You can use Optional for that, as in:
Optional.of(jsonElement).map(element -> element.getAsJsonObject()).map(o -> o.get("myString")).map(e -> e.getAsString()).orElse("defaultValue");
How about make a method to do that.
String getOrDefault(JsonElement jsonElement, String key)
JsonObject obj = jsoneElement.getAsJsonObject().get(key);
return obj==null?"default":obj.getAsString();
}

Java object to URL params

I have Java POJO object and my goal is to convert it to URL parameters and use it in POST method.
...
public class PayseraRequest {
private int projectid = 123;
private int orderid = 987;
private String accepturl = "http://www.test.com";
...
My goal is convert object PayseraRequest to String urlParams
urlParams -> projectid=123&orderid=987&http%3A%2F%2Fwww.test.com&...`
Yes, write a method to do this, but you should URLEncode each parameter. projectid and orderid do not need URLencoding but it doesn't hurt. accepturl must definitely be UrlEncoded. It is good practice to encode anything you want to put into the query string of a URL.
See https://docs.oracle.com/javase/7/docs/api/index.html?java/net/URLEncoder.html
you can override the toString method of that class and with a say so StringBuilder get what you need.
You can check an example I have here:
https://github.com/lmpampaletakis/datumBoxSpringMVC/tree/master/datumBoxSpringMVC/src/main/java/com/lebab/datumbox
Your answer might be at SendRequest.java
You can replace the values of each parameter you want from your pojo

replace String with value of properties file in java

I have a code to replace stream of string. I need to search a specific string that is defined in the key of properties file
String result="";
int i=0;
while (i<listToken.size()){
result = listToken.get(i);
while (enuKey.hasMoreElements()) {
String key = (String)enuKey.nextElement();
// String value = propertiesSlang.getProperty(key);
if (listToken.get(i).equals(key)){
String value = propertiesSlang.getProperty(key);
listToken.get(i).replace(listToken.get(i), value);
System.out.print("detected");
}
}
i++;
}
But it doesn't replace word. How I can replace words using properties.
It's because you forgot to assign the result, using the method set():
listToken.set(i, propertiesSlang.getProperty(key)));
assuming listToken implements AbstractList
Why complicate things with replace(). As far as I understand your code you can simply do -
String value = propertiesSlang.getProperty(key);
listToken.set(i, value);
I see you have modified your code again to
listToken.get(i).replace(listToken.get(i), value);
Just so that you know String class is immutable. So operations like replace() or substring() will give you a new String and not modify the original one. Get the new String and set it in your list listToken.

How to convert String returned by prop.getProperty() into Integer using java

I am trying to read a config file and I want to use that properties value in some algebraic operations. So I need to convert the string returned by prop.getProperty(String str) into an integer.
I have tried converting it using:
1.)
Integer value = null;
String string = getProperty(key);
if (string != null)
value = new Integer(string);
return value;
2.)
String noofdivs = prop.getProperty("NO_OF_INITIAL_DIVS");
Integer noOfInitialDivs = Integer.valueOf(noofdivs);
3.)
String xyz = prop.getProperty("NO_OF_LINES_IN_A_DIV");
Integer noOfLinesInDiv = Integer.getInteger(xyz);
but none of them is working.
Can anybody help me out with this?
int value = Integer.parseInt(string);
You can then check for a NumberFormatException to see if it was properly parsed.
Even if it could be a little bit overengineered here, you could use Apache Commons Configuration to avoid converting yourself the properties. The framework has also the advantage to throw a ConversionException if the property your are reading is not of the expected type.
Integer value = env.getProperty("name property", Integer.class);

Categories

Resources