String sb1 = new String("Soft");
String sb2 = new String("Soft");
System.out.println("ANS1->" +sb1 == sb2);
System.out.println(sb1 == sb2 + " After result");
System.out.println("ANS2->" +sb1.equals(sb2));
This leads to output as below, but i dont understand why "ANS1" and "After result" texts are not displayed. Kindly help on this.
false
ANS2->true
Because : "ANS1->" +sb1 == sb2 ==> ("ANS1->" +sb1) == sb2.
Now, the compiler does this and prints false because ("ANS1->" +sb1) !=sb2.
Even : System.out.println("ANS1->" +sb1 == sb1); prints false :P
In addition to TheLostMinds´ answer:
System.out.println("ANS1->" + (sb1 == sb2));
System.out.println((sb1 == sb2) + " After result");
Now you see the "lost" strings.
Related
Boolean isValid = true;
String message = "prefix" + isValid != null ? " midfix " : "suffix";
System.out.println(message);
What do you think is the result of this? I'd expect prefix midfix. But actually the result is: midfix!
Is this an error in the java library itself (1.7)? Should I report a bug for this? Or does this work as intended, and I'm misusing it?
It can be "fixed" using:
String message = "prefix" + (isValid != null ? " midfix " : "suffix");
but anyways shouldn't it work without the brakets?
It is evaluated as :
String message = (("prefix" + isValid) != null) ? " midfix " : "suffix";
which is equivalent to :
String message = ("prefixtrue" != null) ? " midfix " : "suffix";
Therefore "midfix" is returned.
If you wish "prefix midfix" to be returned use parentheses:
String message = "prefix" + (isValid != null ? " midfix " : "suffix");
I have the next map values:
{title=varchar(50), text=text}
I am trying to convert it into two strings like this:
StringBuffer string = new StringBuffer();
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside) + ", ");
}
But what I want here - not inlude ", " at the last iteration. How can I do it?
Short java 8 alternative:
String result = values.entrySet().stream().map(e -> e.getKey() + " " + e.getValue())
.collect(Collectors.joining(", "))
Stream.map() to convert all entries in the map to a string description of the entry.
Note that Java 8 also finally adds the function String.join().
Use some indicator :
StringBuffer string = new StringBuffer();
boolean first = true;
for (String keyinside: values.keySet()) {
if (!first)
string.append (", ");
else
first = false;
string.append(keyinside + " " + values.get(keyinside));
}
BTW, it's more efficient to use StringBuilder (assuming you don't need thread safety).
I quite like Joiner from Google collections library. You could just do this:
on(",").withKeyValueSeparator(" ").join(values);
on is statically imported from com.google.common.base.Joiner.
If you use Maven, just add a dependency:
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
Take a counter which increments in every iteration and get a if condition which checks whether it is iterating the last time
A simple trick is
int i = 0 ;
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside));
if((i+1)<values.keySet().size()){
string.append(", ");
}
i++;
}
Also I suggest you to use StringBuilder if thread safety is not a concern
You can try this .by which we can remove the comma(,) at end.
Hope this helps you.
Map<String,String> s= new LinkedHashMap<String,String>();
s.put("1", "A");
s.put("2", "B");
s.put("3", "C");
StringBuffer sb = new StringBuffer();
String ans=null;
for (String keyinside: s.keySet()) {
sb.append(keyinside + " " + s.get(keyinside) + ", ").toString();
}
System.out.println(sb);
ans=sb.substring(0, sb.length()-2).toString();
System.out.println(ans);
Note: you can refer How to remove the last character from a string?
I have a String myString = "%d New Voicemail";
I'd like to do this for 2:
String myString = "%d New Voicemail";
System.out.println(String.format(myString, 2));
Output: 2 New Voicemail
I'd like to do this for 5:
String myString = "%d New Voicemail";
System.out.println(String.format(myString, 5));
Output: 5 New Voicemail
I'd like to do this for 1:
String myString = "%d New Voicemail";
System.out.println(String.format(myString));
Output: CRASH
Expected output: New Voicemail
As you can see, for "1" I just want to display the string without formatting. If I just leave out the extra param it crashes. Is there a simple solution I'm unaware of?
I can do this, but wondering if theres a simpler way:
int num;
if (num == 1){
System.out.println(myString.subString(3));
} else {
System.out.println(String.format(myString, num));
}
Try
System.out.printf("%s New Voicemail%n", num == 1 ? "" : num);
This is, of course, the extreme technique. But, once set up, it is simple to use, and the design team will not have any reason to grumble.
static String voicemail( int n ){
MessageFormat form = new MessageFormat("{0}");
double[] filelimits = {0,1,2};
String[] filepart = {"No New Voicemail",
"New Voicemail",
"{0,number} New Voicemails"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
Integer[] values = new Integer[]{n};
return form.format( values );
}
Test:
for( int i = 0; i <=3; ++i ){
System.out.println( voicemail(i) );
}
Output.
No New Voicemail
New Voicemail
2 New Voicemails
3 New Voicemails
While it is not OK to pass fewer arguments to printf than is expected by the format line, it's OK to pass more arguments. You can use a conditional expression for the format line itself, like this:
System.out.printf(num != 1 ? myString : myString.substring(3), num);
Demo.
Since you want to use two different instructions to print 1 or >1 voicemails, it's clear that you must have an if somewhere in your program. That's where you can change your format.
String format = "New Voicemail";
if (num == 1){
System.out.println(myString);
} else {
System.out.println(String.format("%d " + format, 5));
}
I'm concerned about this construct:
String out = "Text " + (obj==null ? "" : obj.getStr()+" ") + "text continues.";
It works and all, but I think it's ugly. Maybe I'm just too picky..
Anyway, I'm asking, is there some nicer way to do this kind of stuff?Or is this the generally accepted technique?
Use a StringBuilder:
final StringBuilder sb = new StringBuilder("Text ");
if (obj != null)
sb.append(obj.getStr()).append(' ');
final String out = sb.append("text continues.").toString();
Also, why .getStr()? Doesn't obj implement .toString()?
Note that if obj did implement .toString(), you could do "better" than that using Guava's Joiner:
private static final Joiner JOINER = Joiner.on(" ").skipNulls();
//
final String out = JOINER.join("Text", obj, "text continues.");
Ultimately, though, that is a question of style.
Well you can separate out the logic from the format, to start with:
String out = String.format("Text %stextcontinues",
obj == null ? "" : obj.getStr() + " ");
I like it better because it is concise.
The other way is the plain old if-then-else:
String toAdd = "";
if(object != null) {
obj.getStr() + " ";
}
String out = "Text " + toAdd + "text continues.";
String out = "Text text continues.";
if (obj != null)
out = "Text " + obj.getStr() + " text continues.";
I had to create an output depending on an boolean state like
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$
System.out.println(buff.toString());
The problem is the String creation statement
", " + smily == null ? ":)" : ":("
I tested it in 2 different eclipse environments (and may be also 2 diofferent java version, this i did not checked) and the result was different.
Result 1:
:(
Result 2:
false:(
Of course, if i added brackets it is working
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
Expected Result:
, :)
Can please somebody explain to me, why java interprets the statement that way?
Thanks
If you check the operator precedence (see this tutorial), then you will notice that addition (+) comes before equality (==). In other words, Java will first evaluate ", " + smily => ", null" before evaluating equality, therefor ", " + smily == null evaluates to false, and so the ternary operator evaluates to ":(".
BTW: You could have avoided this by not concatenating strings before adding them to the StringBuffer (the whole point of a StringBuffer is to make concatenation cheaper):
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", ");
buff.append(smily == null ? ":)" : ":(");
the expression ", " + smily == null ? ":)" : ":(" is evaluated as (", " + smily) == null ? ":)" : ":("
This explains your result 1. To be honest, I don't know why result 2 was possible.
StringBuffer.append() takes a String parameter. So when you put this without brackets
buff.append(", " + smily == null ? ":)" : ":(")
at the time of evaluation will be ", " + null. So when the evaluation happens it is always false.
As for why the same code returned two results I can only assume that two different Java versions were used and they handled this situation differently.
String smily = null;
StringBuffer buff = new StringBuffer();
if(smily == null){
buff.append(", " + ":)") ; //$NON-NLS-1$
}else{
buff.append(", " + ":(") ; //$NON-NLS-1$
}
Try this.....................
buff.append(", " + smily == null ? ":)" : ":(");
- In the above statement you are Not mentioning the smily == null ? ":)" : ":(" to be evaluated in the proper way it has to be.
- To solve this you have to use BODMAS rule, the below are always evaluated in the way it has been listed from Left to Right.
Bracket
Power
Division and Multiplication
Addition and Substraction
- Use Bracket to enclose the smily == null ? ":)" : ":("
Eg:
public class Test {
public static void main(String[] args){
String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$
System.out.println(buff.toString());
}
}
Output: , :)