conversion from object to char in java - 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]))
{
}
}

Related

I have a problem with this code (cannot resolve method: 'equals( java.lang.String)

I'm trying to use this (.equals) method, but it's not working for some reason.
Scanner verb = new Scanner(System.in);
String verb1 = verb.nextLine();
char t = verb1.charAt(verb1.length() - 1);
if(t.equals("t")) {
System.out.println("Hello");
}
and the error message is this one:
cannot resolve method 'equals(java.lang.String)'
Primitives don't have a equals method(Primitives don't have any methods). You have to use ==:
if(t == 't') {
System.out.println("Hello");
}
or replace to
Character t = verb1.charAt(verb1.length() - 1);
if(t.equals('t')) { // you have to compare 'Character' to 'Character'
System.out.println("Hello");
}
char is a primitive. No primitive has equals method. They don't have any members at all. For this code to work, you would have to wrap your char using Character.valueOf(t) (but then you still have type missmatch you would have to write equals('t')) or what would be even easier use t == 't'.

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

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.

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();

How to see if an object is an array without using reflection?

How can I see in Java if an Object is an array without using reflection?
And how can I iterate through all items without using reflection?
I use Google GWT so I am not allowed to use reflection :(
I would love to implement the following methods without using refelection:
private boolean isArray(final Object obj) {
//??..
}
private String toString(final Object arrayObject) {
//??..
}
BTW: neither do I want to use JavaScript such that I can use it in non-GWT environments.
You can use Class.isArray()
public static boolean isArray(Object obj)
{
return obj!=null && obj.getClass().isArray();
}
This works for both object and primitive type arrays.
For toString take a look at Arrays.toString. You'll have to check the array type and call the appropriate toString method.
You can use instanceof.
JLS 15.20.2 Type Comparison Operator instanceof
RelationalExpression:
RelationalExpression instanceof ReferenceType
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
That means you can do something like this:
Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"
You'd have to check if the object is an instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], or Object[], if you want to detect all array types.
Also, an int[][] is an instanceof Object[], so depending on how you want to handle nested arrays, it can get complicated.
For the toString, java.util.Arrays has a toString(int[]) and other overloads you can use. It also has deepToString(Object[]) for nested arrays.
public String toString(Object arr) {
if (arr instanceof int[]) {
return Arrays.toString((int[]) arr);
} else //...
}
It's going to be very repetitive (but even java.util.Arrays is very repetitive), but that's the way it is in Java with arrays.
See also
Managing highly repetitive code and documentation in Java
Java Arrays.equals() returns false for two dimensional arrays.
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.
Therefore, the following is incorrect as a test to see if obj is an array of any kind:
// INCORRECT!
public boolean isArray(final Object obj) {
return obj instanceof Object[];
}
Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)
I use Google GWT so I am not allowed to use reflection :(
The best solution (to the isArray array part of the question) depends on what counts as "using reflection".
In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.
Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.
public boolean isArray(final Object obj) {
return obj instanceof Object[] || obj instanceof boolean[] ||
obj instanceof byte[] || obj instanceof short[] ||
obj instanceof char[] || obj instanceof int[] ||
obj instanceof long[] || obj instanceof float[] ||
obj instanceof double[];
}
You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.
public boolean isArray(final Object obj) {
return obj.getClass().toString().charAt(0) == '[';
}
1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.
You can create a utility class to check if the class represents any Collection, Map or Array
public static boolean isCollection(Class<?> rawPropertyType) {
return Collection.class.isAssignableFrom(rawPropertyType) ||
Map.class.isAssignableFrom(rawPropertyType) ||
rawPropertyType.isArray();
}
Simply obj instanceof Object[] (tested on JShell).

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