How to compare a char with a null? - java

I must compare if a char is null. I think about that (char is the name of my variable):
Character.toString(sauv).equals(null)
OR
Character.toString(sauv) == null
OR
char.equals(null)
OR
char == null
But it didn't work. How could I compare char with null?
I checked my method with a char table with size 4 and with 3 elements in the table. For example: {1,2,3, }
My method must check that I changed a char in this table, otherwise that null. The changed character must be returned.

char cannot be null.
try using '\0'. this might help yu

Related

Checking Character in a String using .equals() not working

I'm trying to check if a letter submitted by user is contained in a string, but it always return false. From what I read the .equals() function should work. I was expecting that if a user inputs the letter "a" it would return "pass" if the string was "america".
for (int i = 0; i < outputTest.length(); i++){
if (userInput.equals(outputTest.charAt(i))){
System.out.println("Pass");
}else {
System.out.println("Fail");
}
}
Based on outputTest.length() and outputTest.charAt() I am assuming that outputTest is String.
Based on userInput.equals I am assuming it is not primitive type like char (since primitive types don't have methods). It is also not Character, otherwise you would see Pass few times. So it most likely is also String.
outputTest.charAt(i) returns char, but you are comparing it with String which equals method looks like:
964 public boolean equals(Object anObject) {965 if (this == anObject) {966 return true;967 }968 if (anObject instanceof String) {969 String anotherString = (String)anObject;970 int n = value.length;971 if (n == anotherString.value.length) {972 char v1[] = value;973 char v2[] = anotherString.value;974 int i = 0;975 while (n-- != 0) {976 if (v1[i] != v2[i])977 return false;978 i++;979 }980 return true;981 }982 }983 return false;984 }
So since equals expects Object, char (returned from outputTest.charAt(i)) will be automatically boxed to Character, but since Character doesn't extend String test
if (anObject instanceof String)
will fail and you will immediately move to return false;.
You may want to use contains method if you want to check if one String contains another
outputTest.contains(userInput)
To find a string in another string, just do:
return text.contains(string);
To find a char in a string, do
return text.indexOf(ch) > -1;
What is the data type of your object userInput? You seem to be comparing a String object with a character which is returned by the charAt() method. That will always return false.
When you are learning to use methods, a good habit to develop is to look at what kind of data type the methods apply or return. For instance, you cannot code this: char scanner.nextLine() // nextLine() is to read String, not char. Therefore, in your code outputTest.charAt(i) // I am a char, and this userInput.equals() // I am a String, you are comparing different things. You cannot compare an apple with a desk because they are two different objects. The compiler will always tell you false.
I assume: String inputTest = scanner.nextLine(); for user input a letter, and you can consider "a" as a String with a length 1. (or any other letters inside)
if (outputTest.contains(userInput)) // now you are comparing String and String
System.out.println("Pass");
else
System.out.println("Fail");

char compariison not working. how do I do this?

I have a statement
if (x[i].equals(' ')) (i'm comparing one element of a char array to a space character to see if it is a space)
this is throwing an error.
so I googled it and found that you can't do this with a primitive.
I also found that == doesn't compare values.
so as far as I can tell from my research you can't compare the values of primitives.
is this true? if not how do you compare them?
== is used to compare the values of primitives, and the "reference values" of reference types (i.e. to see that two reference type variables are the same instance because they have the same memory address value). Use == for your char comparison, for int comparison, long, double, float, ...
You can read more about this in The Java Tutorials > Equality, Relational, and Condition Operators, and in ยง 15.21 of the JLS, where it states:
15.21.1. Numerical Equality Operators == and !=
The value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false.
and
15.21.3. Reference Equality Operators == and !=
At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.
== is used to compare primitives, for example a char comparison:
#Test
public void baz() {
char space = ' ';
assertTrue(space == ' ');
}
Chars are also numbers in Ascii-Code. A space is represented by 32 so you can test for if(x[i] == 32).
Primitive data types don't have method equals, try this for space character check:
if(32 == x[i]) {
//its a space
}
OR
if(' ' == x[i]) {
//its a space
}
OR
if(Character.isSpaceChar(x[i])) {
//its a space
}

what is the difference when string == is used for comparison with in System.out.println() and in a if statement

String att = "siva";
String ptt = "siva";
System.out.println("__________________________ptt.equals(att)_______"+ptt.equals(att));
**System.out.println("__________________________att == ptt________"+att == ptt);**
if(att == ptt){
System.out.println("true");
}else{
System.out.println("false");
}
On my log i find the following output:
__________________________ptt.equals(att)_______true
**false**
true
here if you look at the java code and the log (in bold). there is a difference .
In the print statement i have given a long underscore with some text. it is not appearing.
att==ptt gives false when it is given with in print statement. and true when it is given in if condition.
already i know,
what is a reference and what is a object.
what is difference between att==ptt and att.equals(ptt).
immutability of a string.
but just what to know why it returns false and true when printed in different forms? and why the text that i have entered in the print statement not reflected in log?
please correct it if am wrong.. or if any extra input is required.
In the print statement i have given a long underscore with some text.
it is not appearing.
Because, those underscore was concatenated with att and checked to referential equality(==) with ptt, and prints false, becuase concataneted String and ptt are not referentially equal. Change it like following to get you desired output
System.out.println("__________________________att == ptt________"+(att == ptt));
att==ptt gives false when it is given with in print statement. and
true when it is given in if condition.
Both are referring same String literal in String constant pool, but, in the previous case(your 1st question), att was concatenated with the under score and compared with ==
Change the Line to:
System.out.println("__________________________att == ptt________"+(att == ptt));
Now your output will be as expected. First it compare the reference of att and ptt and then it is printed. You only forgott the parentheses . Now the result will be the same like in the if-statement. And the result is true because you are using String literals to assign the value "siva". Internally this literals got the same reference. If you creat String objects like new String("siva") the output of your code will be false because you are comparing the reference with == and if you creat two objects the reference is different.

How do I compare a character to check if it is null?

I tried the below, but Eclipse throws an error for this.
while((s.charAt(j)== null)
What's the correct way of checking whether a character is null?
Check that the String s is not null before doing any character checks. The characters returned by String#charAt are primitive char types and will never be null:
if (s != null) {
...
If you're trying to process characters from String one at a time, you can use:
for (char c: s.toCharArray()) {
// do stuff with char c
}
(Unlike C, NULL terminator checking is not done in Java.)
Default value to char primitives is 0 , as its ascii value.
you can check char if it is null. for eg:
char ch[] = new char[20]; //here the whole array will be initialized with '\u0000' i.e. 0
if((int)ch[0]==0){
System.out.println("char is null");
}
Correct way of checking char is actually described here.
It states:
Change it to: if(position[i][j] == 0)
Each char can be compared with an int.
The default value is '\u0000' i.e. 0 for a char array element.
And that's exactly what you meant by empty cell, I assume.
You can use the null character ('\0'):
while((s.charAt(j)=='\0')
I actually came here from reading a book "Java: A Beginner's Guide" because they used this solution to compare char to null:
(char) 0
Because in ASCII table, null is at the position of 0 in decimal.
So, solution to OP's problem would be:
while((s.charAt(j) == (char) 0)
I also tried out the already offered solution of:
while((s.charAt(j)=='\0')
And it also worked.
But just wanted to add this one too, since no one mentioned it.
If s is a string and is not null, then you must be trying to compare "space" with char. You think "space" is not a character and space is just null, but truth is that space is a character. Therefore instead of null, use (which is a space) to compare to character.

Java String.indexOf and empty Strings

I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.
The Javadocs only say this method returns the index in this string of the specified string, -1 if the string isn't found.
To me this behavior seems highly unexpected, I would have expected a -1. Any ideas why this unexpected behavior is going on? I would at the least think this is worth a note in the method's Javadocs...
System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think
The empty string is everywhere, and nowhere. It is within all strings at all times, permeating the essence of their being, yet as you seek it you shall never catch a glimpse.
How many empty strings can you fit at the beginning of a string? Mu
The student said to the teacher,
Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.
The teacher responded to the student,
Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?
The teacher struck the student with a strap and instructed him to continue his meditation.
Well, if it helps, you can think of "FOO" as "" + "FOO".
int number_of_empty_strings_in_string_named_text = text.length() + 1
All characters are separated by an empty String. Additionally empty String is present at the beginning and at the end.
By using the expression "", you are actually referring to a null string. A null string is an ethereal tag placed on something that exists only to show that there is a lack of anything at this location.
So, by saying "".indexOf( "" ), you are really asking the interpreter:
Where does a string value of null exist in my null string?
It returns a zero, since the null is at the beginning of the non-existent null string.
To add anything to the string would now make it a non-null string... null can be thought of as the absence of everything, even nothing.
Using an algebraic approach, "" is the neutral element of string concatenation: x + "" == x and "" + x == x (although + is non commutative here).
Then it must also be:
x.indexOf ( y ) == i and i != -1
<==> x.substring ( 0, i ) + y + x.substring ( i + y.length () ) == x
when y = "", this holds if i == 0 and x.substring ( 0, 0 ) == "".
I didn't design Java, but I guess mathematicians participated in it...
if we look inside of String implementation for a method "foo".indexOf(""), we arrive at this method:
public int indexOf(String str) {
byte coder = coder();
if (coder == str.coder()) {
return isLatin1() ? StringLatin1.indexOf(value, str.value)
: StringUTF16.indexOf(value, str.value);
}
if (coder == LATIN1) { // str.coder == UTF16
return -1;
}
return StringUTF16.indexOfLatin1(value, str.value);
}
If we look inside of any of the called indexOf(value, str.value) methods we find a condition that says:
if the second parameter (string we are searching for) length is 0 return 0:
public static int indexOf(byte[] value, byte[] str) {
if (str.length == 0) {
return 0;
}
...
This is just defensive coding for an edge case, and it is necessary because in the next method that is called to do actual searching by comparing bytes of the string (string is a byte array) it would otherwise have resulted in an ArrayIndexOutOfBounds exception:
public static int indexOf(byte[] value, int valueCount, byte[] str, int strCount, int fromIndex) {
byte first = str[0];
...
This question is actually two questions:
Why should a string contain the empty string?
Why should the empty string be found specifically at index zero?
Answering #1:
A string contains the empty string in order to be in accordance with Set Theory, according to which:
The empty set is a subset of every set including itself.
This also means that even the empty string contains the empty string, and the following statement proves it:
assert "".indexOf( "" ) == 0;
I am not sure why mathematicians have decided that it should be so, but I am pretty sure they have their reasons, and it appears that these reasons can be explained in layman's terms, as various youtube videos seem to do, (for example, https://www.youtube.com/watch?v=1nBKadtFViM) although I have not actually viewed any of those videos, because #AintNoBodyGotNoTimeFoDat.
Answering #2:
The empty string can be found specifically at index zero of any string, because why not? In other words, if not at index zero, then at which index? Index zero is as good as any other index, and index zero is guaranteed to be a valid index for all strings except for the trifling exception of the empty string.

Categories