I have the following code
System.out.println("" + null);
and the output is null.
How does Java do the trick in string concatenation?
Because Java converts the expression "A String" + x to something along the lines of "A String" + String.valueOf(x)
In actual fact I think it probably uses StringBuilders, so that:
"A String " + x + " and another " + y
resolves to the more efficient
new StringBuilder("A String ")
.append(x)
.append(" and another ")
.append(y).toString()
This uses the append methods on String builder (for each type), which handle null properly
Java uses StringBuilder.append( Object obj ) behind the scenes.
It is not hard to imagine its implementation.
public StringBuilder append( Object obj )
{
if ( obj == null )
{
append( "null" );
}
else
{
append( obj.toString( ) );
}
return this;
}
The code "" + null is converted by the compiler to
new StringBuffer().append("").append(null);
and StringBuffer replaces null with the string "null". So the result is the string "null".
Related
I want to use a lambda expression instead of a classic for.
String str = "Hello, Maria has 30 USD.";
String[] FORMAT = {"USD", "CAD"};
final String simbol = "$";
// This was the initial implementation.
// for (String s: FORMAT) {
// str = str.replaceAll(s + "\\s", "\\" + FORMAT);
// }
Arrays.stream(FORMAT).forEach(country -> {
str = str.replaceAll(country + "\\s", "\\" + simbol);
});
// and I tried to do like that, but I receiced an error
// "Variable used in lambda expression should be final or effectively final"
// but I don't want the str String to be final
For any string, I want to change the USD or CAD in $ simbol.
How can I changed this code to work ? Thanks in advance!
I see no problem with using a loop for this. That's how I'd likely do it.
You can do it with a stream using reduce:
str = Arrays.stream(FORMAT)
.reduce(
str,
(s, country) -> s.replaceAll(country + "\\s", Matcher.quoteReplacement(simbol)));
Or, easier:
str = str.replaceAll(
Arrays.stream(FORMAT).collect(joining("|", "(", ")")) + "\\s",
Matcher.quoteReplacement(simbol));
Consider using a traditional for loop, since you're changing a global variable:
for(String country: FORMAT) {
str = str.replaceAll(country + "\\s", "\\" + simbol);
}
Using Streams in this example will make things less readable.
I'm doing a project where I build a simple symbol table consisting of two arrays : ArrayOfKeys and ArrayOfValues.
The keys are words and the values are the frequencies of each word in a text.
I need to write a toString method for my ST class using this model:
public String toString() {
// write your toString() method here
}
Suppose the words "aaa" and "bbb" are read from the text and inserted in the ST.
The toString method will be called like this:
StdOut.println("Let's see ST1 with 4 pairs key-val: " + st1);
where "st1" is an instance of the ST class.
The output should be this:
Let's see ST1 with 4 pairs key-val: {'aaa': 1 , 'bbb': 1}
As I see, the entire symbol table should be printed in the return statement of the toString() method, because it needs to return a String. I don't know how to do this, let alone in the format shown above.
The best I could try was:
return (arrayOfKeys + ":" + arrayOfValues);
PS: I'm using Java version 1.8.0_121.
One relatively neat (IMHO) approach is to create a stream of the indexes the arrays have and let Collectors.joining do the heavy lifting for you:
String result =
IntStream.range(0, arrayOfKeys.length)
.mapToObj(i -> "'" + arrayOfKeys[i] + "': " + arrayOfValues[i])
.collect(Collectors.joining(" , ", "{", "}"));
You can try using StringBuilder to generate the string. Code should look something like below:
public String toString() {
StringBuilder sb = new StringBuilder("Let's see ST1 with 4 pairs key-val: {");
for(int i = 0; i< arrayOfKeys.size();i++) {
sb.append('\'' + arrayOfKeys[i] + '\': ');
sb.append(String.valueOf(arrayOfValues[i]));
if(i!=arrayOfKeys.size() -1) {
sb.append(" , ");
}
}
sb.append("}");
return sb.toString();
}
public String toString() {
String results = "{";
for (int i = 0; i < arrayOfKeys.length; i++){
results += "'"+arrayOfKeys[i]+"' : "+arrayOfValue[i]+",";
}
results+="}";
return results;
}
I want to initialize a String in Java, but that string needs to include quotes; for example: "ROM". I tried doing:
String value = " "ROM" ";
but that doesn't work. How can I include "s within a string?
In Java, you can escape quotes with \:
String value = " \"ROM\" ";
In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.
If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:
String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";
Or, if you want to do it with one String variable, it would be:
String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";
Of course, this actually replaces the original ROM, since Java Strings are immutable.
If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.
Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""
\ = \\
" = \"
new line = \r\n OR \n\r OR \n (depends on OS) bun usualy \n enough.
taabulator = \t
Just escape the quotes:
String value = "\"ROM\"";
In Java, you can use char value with ":
char quotes ='"';
String strVar=quotes+"ROM"+quotes;
Here is full java example:-
public class QuoteInJava {
public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}
}
Here is Out PUT:-
If you need to 'quote' in Java
you can use single ' or double " quote
Look into this one ... call from anywhere you want.
public String setdoubleQuote(String myText) {
String quoteText = "";
if (!myText.isEmpty()) {
quoteText = "\"" + myText + "\"";
}
return quoteText;
}
apply double quotes to non empty dynamic string. Hope this is helpful.
This tiny java method will help you produce standard CSV text of a specific column.
public static String getStandardizedCsv(String columnText){
//contains line feed ?
boolean containsLineFeed = false;
if(columnText.contains("\n")){
containsLineFeed = true;
}
boolean containsCommas = false;
if(columnText.contains(",")){
containsCommas = true;
}
boolean containsDoubleQuotes = false;
if(columnText.contains("\"")){
containsDoubleQuotes = true;
}
columnText.replaceAll("\"", "\"\"");
if(containsLineFeed || containsCommas || containsDoubleQuotes){
columnText = "\"" + columnText + "\"";
}
return columnText;
}
suppose ROM is string variable which equals "strval"
you can simply do
String value= " \" "+ROM+" \" ";
it will be stored as
value= " "strval" ";
I found below sysout in our project and it is always printing 'Not Null'. Even I have initialize the Val variable or not, it is printing 'Not Null'.
Also why it is not printing the "mylog" in front? Can someone explain?
String Val = null;
System.out.println("mylog : " + Val!=null ? "Not Null" :"Is Null");
Use paranthesis:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Otherwise it gets interpreted as:
whatToCheck = "mylog: " + val
System.out.println(whatToCheck !=null ? "Not Null" : "Is Null"
which evaluates to something like "mylog: null" or "mylog: abc".
And that is always a non-null String.
"mylog : " + Val!=null
will be evaluated to
"mylog : null"
which is not null.
Parenthesis for the rescue.
Why is null converted to the String "null"? See the JLS - 15.18.1.1 String Conversion:
... If the reference is null, it is converted to the string "null"
Also it's very important to understand that this is happening because of Java operator precedence.
Use brackets around your expression:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Check it following way:
String Val = null;
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Output :
mylog : Is Null
I have two strings in a java program, which I want to mix in a certain way to form two new strings. To do this I have to pick up some constituent chars from each string and add them to form the new strings. I have a code like this(this.eka and this.toka are the original strings):
String muutettu1 = new String();
String muutettu2 = new String();
muutettu1 += this.toka.charAt(0) + this.toka.charAt(1) + this.eka.substring(2);
muutettu2 += this.eka.charAt(0) + this.eka.charAt(1) + this.toka.substring(2);
System.out.println(muutettu1 + " " + muutettu2);
I'm getting numbers for the .charAt(x) parts, so how do I convert the chars to string?
StringBuilder builder = new StringBuilder();
builder
.append(this.toka.charAt(0))
.append(this.toka.charAt(1))
.append(this.toka.charAt(2))
.append(' ')
.append(this.eka.charAt(0))
.append(this.eka.charAt(1))
.append(this.eka.charAt(2));
System.out.println (builder.toString());
Just use always use substring() instead of charAt()
In this particular case, the values are mutable, consequently, we can use the built in String class method substring() to solve this problem (#see the example below):
Example specific to the OP's use case:
muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);
muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
Concept Example, (i.e Example showing the generalized approach to take when attempting to solve a problem using this concept)
muutettu1 += toka.substring(x,x+1) + toka.substring(y,y+1) + eka.substring(z);
muutettu2 += eka.substring(x,x+1) + eka.substring(y,y+1) + toka.substring(z);
"...Where x,y,z are the variables holding the positions from where to extract."
The obvious conversion method is Character.toString.
A better solution is:
String muutettu1 = toka.substring(0,2) + eka.substring(2);
String muutettu2 = eka.substring(0,2) + toka.substring(2);
You should create a method for this operation as it is redundant.
The string object instatiantiation new String() is unnecessary. When you append something to an empty string the result will be the appended content.
You can also convert an integer into a String representation in two ways: 1) String.valueOf(a) with a denoting an integer 2) Integer.toString(a)
This thing can adding a chars to the end of a string
StringBuilder strBind = new StringBuilder("Abcd");
strBind.append('E');
System.out.println("string = " + str);
//Output => AbcdE
str.append('f');
//Output => AbcdEf