String s="";
while ((strLine = br.readLine()) != null) {
s=s.concat(strLine);
When I used this code I get the string I expect from the file ..
But if I used
String s = null;
What I get is null as the result of the s string. Can anyone explain me the reason for this?
Firstly, I suspect that's not your code - or it would throw a NullPointerException. I suspect you've actually got:
s = s + strLine;
After that, it's very simple - concatenating any string with a null String reference will give you null:
String x = null;
String y = x + "a";
System.out.println(y); // nulla
From section 15.18.1 of the JLS (string concatenation):
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Then from section 5.1.11:
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Note that your code is extremely inefficient at the moment - you should be using a StringBuilder.
Related
This question already has answers here:
String concatenation: concat() vs "+" operator
(12 answers)
Closed 8 years ago.
I was trying out string concatenation and the '+' operator on a string and encountered the following-
String xyz = "Hello" + null;
System.out.println("xyz= " +xyz);
String abc= "Hello".concat(null);
System.out.println("abc= " +abc);
The output for the first one was : Hellonull
The output for the second one was a Null Pointer exception
I don't understand why there were two different outputs.
When you concatenate null by + operator, it is always converted to "null" String. This explains the first output Hellonull.
The concat function looks internally like this:
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
} else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
Source: String concatenation: concat() vs "+" operator
As you can see, it calls s.length(), which in your case means null.length(); which causes the NullPointerException for your String abc= "Hello".concat(null); statement.
Edit: I just decompiled my own String.concat(String s) function and its implementation looks a little bit different, but the reason for the NullPointerException stays the same.
From Docs
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
"Hello" + null returns the same result as "Hello".concat(String.valueOf(null)).
String.valueOf(null) returns the string "null".
/**
* Concatenates this string and the specified string.
*
* #param string
* the string to concatenate
* #return a new string which is the concatenation of this string and the
* specified string.
*/
public String concat(String string) {
if (string.count > 0 && count > 0) {
char[] buffer = new char[count + string.count];
System.arraycopy(value, offset, buffer, 0, count);
System.arraycopy(string.value, string.offset, buffer, count, string.count);
return new String(0, buffer.length, buffer);
}
return count == 0 ? string : this;
}
the source code's first line in contact function calls the null's count. So it will throw Null Pointer exception.
Calling concat() on a null reference gives NPE, hence different results as "+" operator treats null reference as "null".
As an example I have abcdbab and I want to replace all ab with A.
The output is AcdbA.
I try this one but it gives an error.
char N = 65;
String S = "abcdbab";
S = S.replaceAll("ab", N);
System.out.print(S);
Is there any method to do this?
Use String.replace(CharSequence,CharSequence) (remember String is immutable, so either use the result or assign it back) like
String str = "abcdbab";
System.out.println(str);
str = str.replace("ab", "A");
System.out.println(str);
Output is
abcdbab
AcdbA
Just change the following line:
char N = 65;
to
String N = "A";
and it'll work fine.
There is no such method String#replace(CharSequence, char), you will need to find the one that is closes to your needs and adjust to it, for example, there is a String#replaceAll(CharSequence, CharSequence) method and char can be represented as a CharSequence (or a String), for example...
S = S.replaceAll("ab", Character.toString(N));
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
You can also change
S = S.replaceAll("ab", N);
to
S = S.replaceAll("ab", "" + N);
referencing here, http://www.tutorialspoint.com/java/java_string_replaceall.htm replaceAll takes a String, String not String, Char
I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?
You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring
What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.
String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);
This question already has answers here:
The concatenation of chars to form a string gives different results
(5 answers)
Closed 9 years ago.
the question says it all, here is the code :
public class Chars
{
public static void main(String[] args){
Chars c = new Chars();
String res = c.test("abcd");
System.out.println(res);
}
public String test(String str){
String res = "";
res += str.charAt(0) + str.charAt(2);
return res;
}
}
This returns : "196" which is the sum of the ASCII value of a and c !
Why does this happen? , I would expect to get "ac".
If I modify the second line in the test() method like this :
res = res + str.charAt(0)+str.charAt(2);
The result is indeed "ac".
Please somebody help me with this doubt. I just can`t find and answer !
Chars are not strings. You would expect to get "ac" if "a" and "c" were Strings. Chars are unsigned integers which represent characters, and if you add any two chars, the result is converted to int. You have to cast using (char) if you want to treat as a char or assign it to a variable which is declared as char.
The difference is in the way the concatenations are constructed.
First: res += str.charAt(0) + str.charAt(2);
Here, the two char values are added together first. Binary numeric promotion occurs (JLS, Section 5.6.2).
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
That means that the values are promoted to int, creating your 196. That is then added to str, appending "196".
Second: res = res + str.charAt(0) + str.charAt(2);
Here, the res + str.charAt(0) is performed first, and a String plus a char appends the char (via String Conversion, JLS 15.18.1, resulting in a new String.
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Then, the second char is appended similarly.
If you were to say
res = res + (str.charAt(0) + str.charAt(2));
then the result would be the same (appending the 196) as with +=.
JLS §15.18.1. String Concatenation Operator + explains why:
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
In your case, you are doing: char + char. Non of the operands is of type String, so the classical numerical addition is executed.
It's because charAt() returns char value, instead of String. Therefore + operator here doesn't stand for concatenation, but it's a simple addition of two numbers.
This works if both operands of + are a number. If one of them is s String, + does not peform addition anymore, but both operands are casts to String and concatenation is performed instead. Therefore if you include res into the mix, the result of
res + str.charAt(0)
will be a String and using the same logic, the whole thing
res += str.charAt(0) + str.charAt(2);
will also be evaluated to String.
In general, if you want to extract a character from a string and get a String of length 1, instead of a char, then instead of:
str.charAt(i)
you can do this:
str.substring(i, i+1)
or this:
Character.toString(str.charAt(i))
or:
("" + str.charAt(i))
This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 9 years ago.
What is the difference between a null string (String s = null) and an empty string (String s = "")?
This is what I have:
String s1 = ""; //print statement does not print any thing for s1 but s1.length()=0
String s2 = null;//print statement prints "null" for s2 but s2.length() gives exception
What does it mean?
String s1 = ""; means that the empty String is assigned to s1.
In this case, s1.length() is the same as "".length(), which will yield 0 as expected.
String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
Null means nothing. Its just a literal. Null is the value of reference variable. But empty string is blank.It gives the length=0. Empty string is a blank value,means the string does not have any thing.
No method can be invoked on a object which is assigned a NULL value. It will give a nullPointerException. Hence, s2.length() is giving an exception.
When Object variables are initially used in a language like Java, they have absolutely no value at all - not zero, but literally no value - that is null
For instance: String s;
If you were to use s, it would actually have a value of null, because it holds absolute nothing.
An empty string, however, is a value - it is a string of no characters.
String s; //Inits to null
String a =""; //A blank string
Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
Null isn't really a value - and as such, doesn't have properties. So, calling anything that is meant to return a value - such as .length(), will invariably return an error, because 'nothing' cannot have properties.
To go into more depth, by creating s1 = ""; you are initializing an object, which can have properties, and takes up relevant space in memory. By using s2; you are designating that variable name to be a String, but are not actually assigning any value at that point.