Infix to postfix evaluation - java

How do I convert char to Integer type?
int p2 = (int)stack2.pop();
int p1 = (int)stack2.pop();
int res = result(p2, p1, calStr.charAt(i));
stack2.push(res);
I did the above method, but getting a runtime error that java.lang.Character cannot be cast to java.lang.Integer
Exception in thread "main" java.lang.ClassCastException:
java.lang.Character cannot be cast to java.lang.Integer

Explanation
You can not directly cast a Character to an Integer, those are objects. The cast between them only works if we are talking about the datatypes char and int.
While Java indeed auto-boxes and -unboxes Integer to int, Character to char and vice versa, it does not automatically use this technique for a fast conversion between Integer to Character.
Solution
Of course you can do a transformation like:
Character -> char -> int -> Integer
So as code this could look like:
Character itemAsCharacter = stack2.pop();
char itemAsChar = itemAsCharacter.charValue();
int itemAsInt = (int) itemAsChar;
Integer itemAsInteger = Integer.valueOf(itemAsInt);
Or in short:
// Last step uses the implicit auto-boxing of int -> Integer
Integer item = (int) stack2.pop().charValue();
The backwards direction works similar:
Integer resultAsInt = ...
Character result = (char) resultAsInt.intValue();
stack2.push(result);
Note
Please note that the class Stack, also Vector, are outdated classes in Java. There are classes with the same functionality that provide more methods, are more robust and simply more up-to-date. Examples for LIFO data-structures are listed under the interface Deque, the most common used implementation is LinkedList and there is also an array-variant, the ArrayDeque.
Here is the relevant excerpt from the documentation of Stack:
A more complete and consistent set of LIFO stack operations is
provided by the Deque interface and its implementations, which should
be used in preference to this class.

Related

What is the use of intValue() when you can directly assign Integer value to primitive int? [duplicate]

What is the difference between them?
l is an arraylist of Integer type.
version 1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
version 2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;
l.get(i); will return Integer and then calling intValue(); on it will return the integer as type int.
Converting an int to Integer is called boxing.
Converting an Integer to int is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper classes.
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer is null, and you directly assign it to int then it will throw NullPointerException.
Prior to java 5, the programmer himself had to do boxing/unboxing.
As you noticed, intValue is not of much use when you already know you have an Integer. However, this method is not declared in Integer, but in the general Number class. In a situation where all you know is that you have some Number, you'll realize the utility of that method.
The Object returned by l.get(i) is an instance of the Integer class.
intValue() is a instance method of the Integer class that returns a primitive int.
See Java reference doc...
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#intValue()
Java support two types of structures first are primitives, second are Objects.
Method that you are asking, is used to retrieve value from Object to primitive.
All java types that represent number extend class Number. This methods are in someway deprecated if you use same primitive and object type since [autoboxing] was implemented in Java 1.5.
int - primitive
Integer - object
Before Java 1.5 we was force to write
int i = integer.intValue();
since Java 1.5 we can write
int i = integer;
Those methods are also used when we need to change our type from Integer to long
long l = integer.longValue();
Consider this example:
Integer i = new Integer(10);
Integer j = new Integer(10);
if (!(i == j)) {
System.out.println("Surprise, doesn't match!");
}
if (i.intValue() == j.intValue()) {
System.out.println("Cool, matches now!");
}
which prints
Surprise, doesn't match!
Cool, matches now!
That proves that intValue() is of great relevance. More so because Java does not allow to store primitive types directly into the containers, and very often we need to compare the values stored in them. For example:
oneStack.peek() == anotherStack.peek()
doesn't work the way we usually expects it to work, while the below statement does the job, much like a workaround:
oneStack.peek().intValue() == anotherStack.peek().intValue()
get(i) will return Integer object and will get its value when you call intValue().In first case, automatically auto-unboxing happens.
They are exactly the same. As other posters have mentioned, you can put either the Integer object or the int primitive into the array. In the first case, the compiler will automatically convert the Integer object into a primitive. This is called auto-boxing.
It's just a convenience method for getting primitive value from object of Number: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Number.html
Consider the code:
Integer integerValue = Integer.valueOf(123);
float floatValue = integerValue.floatValue();
The last line is a convenient method to do:
float floatValue = (float)(int)integerValue;
Since any numeric type in Java can be explicitly cast to any other primitive numeric type, Number class implements all these conversions. As usual, some of them don't make much sense:
Integer integerValue = Integer.valueOf(123);
int intValue = integerValue.intValue();
int intValue2 = (int)integerValue;
int intValue3 = integerValue;

Autoboxing for String in java

Integer l = Integer.valueOf("100"); // valid no compilation
Integer l = "100"; //Error : cannot convert from string to integer
Why I am facing the above error please suggest to me. (Need to use Autoboxing concept for second line)
Any value in quotes in java is treated as a String, and strings are objects, Auto-boxing is not supported in JAVA for Objects, So If you need then you have to do explicitly.
auto-boxing is only allowed from primitives to it's wapper classes.
The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for auto-boxing and unboxing:
Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
You can read more about this here.
Firstly, this is not called an Autoboxing but is an ordinary static method call with a String as a parameter. The simplest examples of autoboxing are:
Integer i = 1;
Character ch = 'a';
Your snippet tries to instantiate a String as an Integer which are in the Java world incompatible types. Autoboxing happens only for the primitive data types.
Integer l = "100"; // Cannot convert from String to Integer
Integer l = 100; // Autoboxing happens
From JLS, ยง5.1.7:
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. [...]
"100" in Java is of type String. String is not a primitive and therefore boxing does not apply.

When converting primitive data types to Objects, should you cast or create a new object?

This may break the discussion vs. answer rules, but I figure there's a preferred way of doing things.
--
Let's say you need to convert a primitive data type to an Object. Let's use int --> Integer as an example. You can do this by casting or straight up making a new Object. For example:
int a = 5; int b = 10;
Integer c = new Integer(a);
Integer d = (Integer) b;
Which is the better way to do it, a --> c or b --> d? I suspect they perform the same operation, so which one is usually used?
Thanks in advance.
Let's say you need to convert a primitive data type to an Object.
Let's use int --> Integer as an example. You can do this by casting or
straight up making a new Object. For example:
int a = 5; int b = 10;
Integer c = new Integer(a);
Integer d = (Integer) b;
Which is the better way to do it, a --> c or b --> d? I suspect they
perform the same operation, so which one is usually used?
Java compilers in versions 5 and later perform autoboxing to convert between a primitive value and it's corresponding boxed object. Autoboxing blurs, but does not erase, the distinction between primitive values and objects.
The following line is discouraged:
Integer c = new Integer(a);
This is because a new object is always created and prevents cached Integer objects from being reused.
This line is transformed by the Java compiler:
Integer d = (Integer) b;
Instead, this line becomes
Integer d = Integer.valueOf(b);
This is the code you would get if you omitted the cast from the assignment altogether. The primitive value is boxed into its corresponding object using the valueOf() function. This is the preferred way to assign primitive values to their objects because this allows the JVM to reuse frequently cached objects.
None of the above.
Use Integer.valueOf as it yields to significantly better space and time performance by caching frequently requested values.
From the docs of Integer.valueOf
Returns an {#code Integer} instance representing the specified
{#code int} value. If a new {#code Integer} instance is not
required, this method should generally be used in preference to
the constructor {#link #Integer(int)}, as this method is likely
to yield significantly better space and time performance by
caching frequently requested values.
But with autoboxing, the compiler will do it automatically for you.
Integer i = 1;
Which is a syntactic sugar for
Integer i = Integer.valueOf(1);
None of the above. You can lean on autoboxing in this scenario to take care of the casts.
That would make your code this:
int a = 5;
int b = 10;
Integer c = a;
Integer d = b;

Real world application of widening / narrowing conversion?

Can someone please explain why you would ever use widening or narrowing conversion? I've read a lot about these but no one ever gives me a practical example. Thanks!
(Java) Widening and Narrowing Conversions have to do with converting between related Types. Take, for example, the relationship between an abstract (super) class and its (child) subclass; let's use the java.lang.Number Class (abstract) and a direct subclass Integer. Here we have:
(superclass) Number
__________/\__________
/ | | \
(concrete subclasses) Integer Long Float Double
Widening Conversion: occurs if we take a specific type (subclass) and attempt to assign it to a less specific type (superclass).
Integer i = new Integer(8);
Number n = i; // this is widening conversion; no need to cast
Narrowing Conversion: occurs when we take a less specific type (superclass) and attempt to assign it to a more specific type (subclass), which requires explicit casting.
Number n = new Integer(5); // again, widening conversion
Integer i = (Integer) n; // narrowing; here we explicitly cast down to the type we want - in this case an Integer
There are certain issues that you need to be aware of such as ClassCastExceptions:
Integer i = new Integer(5);
Double d = new Double(13.3);
Number n;
n = i; // widening conversion - OK
n = d; // also widening conversion - OK
i = (Integer) d; // cannot cast from Double to Integer - ERROR
// remember, current n = d (a Double type value)
i = (Integer) n; // narrowing conversion; appears OK, but will throw ClassCastException at runtime - ERROR
One way to handle this is to use an if statement with the instanceof keyword:
if( n instanceof Integer) {
i = (Integer) n;
}
Why would you want to use this? Let's say you are making a hierarchy of personnel for some program and you have a generic superclass called "Person" which takes a first and last name as parameters, and subclasses "Student", "Teacher", "Secretary", etc.. Here you can initially create a generic person, and assign it (through inheritance) to, say, a Student which would have an additional variable field for studenID set in it's constructor. You can use a single method that takes the more generic (wider) type as a parameter and handle all subclasses of that type as well:
public static void main(String[] args) {
Person p = new Student("John", "Smith", 12345);
printInfo(p);
}
// this method takes the wider Person type as a parameter, though we can send it a narrower type such as Student if we want
public static void printInfo(Person p) {
System.out.println("First: " + p.getFirstName());
System.out.println("Last: " + p.getLastName());
if (p instanceof Student) {
System.out.println( (Student)p).getStudentID() ); // we cast p to Student with Narrow Conversion which allows us to call the getStudentID() method; only after ensuring the p is an instance of Student
}
}
I realize this may not be the ideal way to handle things, but for the sake of demonstration I thought it served to show some of the possibilities.
If some code returns an int containing a true/false value, you could shorten it yourself to a bool which is what it properly represents.
You can also do the opposite.
You can widen a char to int to do some comparisons with ascii values.
You can take an instance of Dog and widen it to IAnimal to pass it to a function.
You can shorten a IAnimal to Dog when you know the type of animal in a List<IAnimal> in a factory or elsewhere for whatever reason.
You use implicit conversions to do math with numerical values of different types. For example, if now() returns a timestamp in seconds as a long:
long t = now()
long nextMinute = t + 60
you have done an implicit widening conversion of 60 (an int) to a long so you can add it to t. Being able to do such conversions makes math much easier to code.
One canonical example of widening and narrowing conversions is how certain file I/O libraries work. Often, a file processing library will have a function / method that reads a single character from a file. If there is a character to read, the function should return that character, and if no characters are left it should return a sentinel value EOF to signal this.
Because any character can appear in a file, typically the function / method would have this signature:
int readCharacter();
Here, the function returns an int that holds a char value if a character was read and which holds EOF as a sentinel otherwise. EOF is typically chosen as an integer that is too big to hold in a char. That way, you can do this:
while (true) {
int ch = readCharacter();
if (ch == EOF) break;
char actualCharValue = (char) ch;
/* process actualCharValue here */
}
Hope this helps!
Take this...
Conversion - Specialized -> Generalized, then it is known as Widening, when you are becoming more general.
Such as Surgeon -> Medico. In this case, you do not need a casting. Because, a surgeon is a Medico by default. So, it is natural that a surgeon can perform all those stuffs that a Medico can do.
While on the other hand,
Conversion - Generalized -> Specialized, then it is known as narrowing, when you are becoming more specialized.
Such as Medico -> Surgeon. Well, in this case, you must have to add casting. Because, a medico can be a surgeon or a physician or a nurse. Think of it, if you ask a nurse to operate on you...
Horrible, right ???
Hope you got the idea.

Java HashSet and data type Short, incompatibility?

Running this code:
public class SomeSet {
public static void main(String[] args) {
Set<Short> s = new HashSet<Short>();
for (short i = 0; i < 100; i++) {
s.add(i);
s.remove(i - 1);
}
System.out.println(s.size());
}
}
Will print the value 100.
Why does it print this value?
s.remove(i - 1);
The line above will attempt to remove Integer objects from the set, because all integer calculations in Java have int (or long) results. Since the set contains Short objects, the remove() method will not have any effect.
This (and similar problems) is the main reason why you should almost never use short (and, more so, Short). Using a Set implementation to contain autoboxed numbers incurs a massive (easily 1000%) overhead, so it's rather pointless to try and save space by using Short rather than Integer.
The problem is that remove(i-1) calls the remove method with an Integer object, since i-1 is of type int (which gets auto-boxed into an Integer).
To make sure that you call remove with a Short object use this:
s.remove((short) (i - 1));
The type of i - 1 is int, so it gets autoboxed to an Integer.
Normally you'd expect a generic collection to prevent you performing operations which have arguments of the wrong type, but the interface to Set<E> is a bit loose.
Because the remove method of Set<E> takes an Object rather than an E, the compiler doesn't warn you that you're removing a different type to what the set contains.
To force it to be a Short, cast the numeric value to (short). (casting to (Short) isn't allowed, and you'd have to cast the numeric value to use Short.valueOf)
Note that the add method is generically typed boolean add(E o) so in your case of Set the add method will take a short, whereas the remove method is not generically typed boolean remove(Object o) so i - 1 autoboxes to a Integer. For any value of i new Short(i).equals(new Integer(i)) will always be false.
Note that if you try s.add(i - 1); you will get a compiler error because i - 1 becomes an instance of Integer and the types Integer and Short do not match.

Categories