How i can control whether a char[] is null? - java

I wrote this code to control whether a char[] is null or not.
char[] xxx = new char[9];
for (int i = 0; i < 9; ++i)
{
if (xxx[i]==null)
{
xxx[i]=i;
}
}

Each element of a char[] is a char, which is a primitive type. Primitive types cannot be null, so your comparison will never return true. If you say more about what you are trying to accomplish, you may get some useful advice about how to do it.

What is char[] in your example? if _board is a char[] then you are checking if one of the char is null, chars can't be null since char is a primitive type.
I'm guessing you should do
if (_board == null)

if (xxx[i]==0)
this code works.0 means that in char is null.try it.

You are using the word "control" in a confusing way.
Your code will test if _board[i] is null. It is correct in that sense. It might fail if
_board was not defined.
i was not defined.
_board is not an array
_board is not an array of objects (only object references can be null)
It will "work" but not "do anything" if _board[i] is not null.

Related

Java Compare two ArrayList<Integer> [duplicate]

int [] nir1 = new int [2];
nir1[1] = 1;
nir1[0] = 0;
int [] nir2 = new int [2];
nir2[1] = 1;
nir2[0] = 0;
boolean t = nir1.equals(nir2);
boolean m = nir1.toString().equals(nir2.toString());
Why are both m and t false? What is the correct way to compare 2 arrays in Java?
Use Arrays.equals method. Example:
boolean b = Arrays.equals(nir1, nir2); //prints true in this case
The reason t returns false is because arrays use the methods available to an Object. Since this is using Object#equals(), it returns false because nir1 and nir2 are not the same object.
In the case of m, the same idea holds. Object#toString() prints out an object identifier. In my case when I printed them out and checked them, the result was
nir1 = [I#3e25a5
nir2 = [I#19821f
Which are, of course, not the same.
CoolBeans is correct; use the static Arrays.equals() method to compare them.
Use Arrays.equals instead of array1.equals(array2). Arrays.equals(array1, array2) will check the content of the two arrays and the later will check the reference. array1.equals(array2) simply means array1 == array2 which is not true in this case.
public static boolean perm (String s, String t){
if (s.length() != t.length()) {
return false;
}
char[] perm1 = s.toCharArray();
Arrays.sort(perm1);
char[] perm2 = t.toCharArray();
Arrays.sort(perm2);
return Arrays.equals(perm1, perm2);
}
boolean t = Arrays.equals(nir1,nir2)
I just wanted to point out the reason this is failing:
arrays are not Objects, they are primitive types.
When you print nir1.toString(), you get a java identifier of nir1 in textual form. Since nir1 and nir2 were allocated seperately, they are unique and this will produce different values for toString().
The two arrays are also not equal for the same reason. They are separate variables, even if they have the same content.
Like suggested by other posters, the way to go is by using the Arrays class:
Arrays.toString(nir1);
and
Arrays.deepToString(nir1);
for complex arrays.
Also, for equality:
Arrays.equals(nir1,nir2);
Use this:
return Arrays.equals(perm1, perm2)
Instead of this:
return perm1.equals(perm2);
Please have to look this

conversion from object to char in java

In one of my problem i am getting RuntimeException because there is necessary to convert object to char.I tried to do it by using charValueOf() method to get the primitive value of object but couldn't do it. Here is my code.....
while ((stack.size() > 0) && (stack.peek() != '('))
{
if (ComparePrecedence(stack.peek(), infix[i]))
{
}
}
boolean ComparePrecedence(char top, char p_2)
{
}
how can i solve the problem? thanks..
Its generally not a good idea to try to convert a generic object to a char as it doesn't make any sense. If the object is a Character you can use the following.
char ch = o.toString().charAt(0)
I think you got an exception because you didn't use an instance of character wrapper class. If you use an instance of the character wrapper class, then you can call/use charValue method.
The problem you are having is caused by the stack you are using. The stack is Object based, so it allows you to push char types, but when you pop or peek them, they will come out as Object types. If you are always going to be pushing char type values, you can change your stack code to accept a Generic Type such as <Character>.
Another option is to cast the Object back to (Character) when you peek or pop by doing:
while ((stack.size() > 0) && ((Character) stack.peek() != '('))
{
if (ComparePrecedence((Character) stack.peek(), infix[i]))
{
}
}

Java compare char on string array

Imagine I have a String array like this:
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"};
If I do this:
for (int i = 0; i < fruits.length;i++){
System.out.println(fruits[i][0].charAt(1));
}
it will print:
r
p
r
And if I do this:
for (int i = 0; i < fruits.length;i++){
Character compare = fruits[i][0].charAt(1);
System.out.println(compare.equals('r'));
}
it will print:
true
false
true
So here is my question. Is it possible to use charAt and equals on the same line, I mean, something like this:
System.out.println((fruits[i][0].charAt(1)).equals("r"));
Regards,
favolas
Yes, provided you convert the result of charAt() to Character first:
System.out.println(Character.valueOf(fruits[i][0].charAt(1)).equals('r'));
A simpler version is to write
System.out.println(fruits[i][0].charAt(1) == 'r');
I personally would always prefer the latter to the former.
The reason your version doesn't work is that charAt() returns char (as opposed to Character), and char, being a primitive type, has no equals() method.
Another error in your code is the use of double quotes in equals("r"). Sadly, this one would compile and could lead to a painful debugging session. With the char-based version above this would be caught at compile time.
Certainly! Try this:
System.out.println((fruits[i][0].charAt(1)) == 'r');
We're doing a primitive comparison (char to char) so we can use == instead of .equals(). Note that this is case sensitive.
Another option would be to explicitly cast the char to a String before using .equals()
If you're using a modern version of Java, you could also use the enhanced for syntax for cleaner code, like so:
public static void main(String[] args) {
String[][] fruits = {{"Orange","1"}, {"Apple","2"}, {"Arancia","3"}};
for (String[] fruit: fruits){
System.out.println((fruit[0].charAt(1)) == 'r');
}
}
The char data type, which is returned from String.charAt() is a primitive, not an object. So you can just use the == operator to perform the comparison as it will compare the value, not the reference.
System.out.println((fruits[i][0].charAt(1) == 'r'));

What causes the "Incompatible operand types" error?

I am trying to implement iSortableStack Interface via a class.
Here's my main function,
public class SampleStack<E> {
E ch;
#SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
ISortableStack<Character> s = new SortableStack<Character>();
SampleStack demo = new SampleStack();
while ((demo.ch == System.in.read()) != '\n')
if (!s.isFull())
s.push((Character) demo.ch);
while (!s.isEmpty())
System.out.print(s.pop());
System.out.println();
}
}
But I am getting one error, on this line,
while ((demo.ch == System.in.read()) != '\n')
Error : Incompatible operand types Object and int
What is wrong here ?
There are two severe problems here that have nothing to do with generics.
First, demo.ch == System.in.read() is a boolean expression. The result of read() (an int) will be auto-boxed to an Integer, and the identity of that object will be tested against demo.ch (which is null).
I think that what you want here is the assignment operator, =. This will assign the read() result to demo.ch.
The next problem is that it looks like you expect demo.ch to be a Character (based on the casts you are using). However, you are trying to assign an int (the result of read()) to it. Primitive types can be "auto-boxed" when necessary, that is, they can be converted to a wrapper object like Character or Integer, but only when the value to be converted is a constant expression that can be represented by the target type. Here, the value is variable, so the conversion cannot be performed implicitly.
You could work around this by explicitly casting the read() result to a char, and then letting the auto-boxing convert it to a Character, but that would hide EOF, which is represented by a value of -1. I recommend using something like this instead:
while (true) {
int ch = System.in.read();
if ((ch < 0) || (ch == '\n'))
break;
if (!s.isFull())
s.push((char) ch);
}
Note that we don't use demo here at all, so the problems with its type parameter are irrelevant.
SampleStack.ch is of type E. E is an object specified by your type parameters. Since you did not specify a type parameter, the compiler puts Object in for you. If you wanted ch to be a Character, you would want SampleStack<Character> demo = new SampleStack<Character>(); or in Java 7 SampleStack<Character> demo = new SampleStack<>();.
You haven't provided a type parameter when you instantiate SampleStack, so demo.ch is of type Object. That obviously can't be compared (or assigned, which is what I suspect you actually wanted to do, anyway) from the int coming from System.in.
You have == (equality test) when you want = (assignment). You're never actually assigning to demo.ch. The equality test returns boolean, rather than char, hence the error message.
You will also need to cast the result from System.in.read() to a character from an integer (or else use SampleStack<Integer>, or something like that.)
You have several errors in this code:
as people pointed out you're making a generic class but you're not generalizing it and using it raw, you need:
SampleStack<Character>
even if you change it it wont run as you have == instead of =
even if you change the above two it wont work as System.in.read() returns an int, not a character, You'd need to either make a stack of Integers OR read the value from the input to a variable and then cast it but its not a good practice. I'd use a Scanner or somethign similar to read what the user inputs like this:
Scanner sc = new Scanner(System.in);
char c = sc.nextChar();

Can an int be null in Java?

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Categories

Resources