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.
Related
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;
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.
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;
Why does this program return error: incompatible types: int cannot be converted to String ?
public class StringConcatenation{
public static void main(String []args){
int[] testing = {0,1,3,4,5,6};
String mark = "";
for(int i=0;i<testing.length;i++)
{
// mark += testing[i]; But this line works fine
mark = testing[i]; /* This line doesn't work */
}
System.out.println(mark);
}
}
StringConcatenation.java:8: error: incompatible types: int cannot be converted to String
mark = testing[i];
The first way uses string concatenation, which is special cased in the Java language to allow you to use any object or primitive type. However, you cannot just assign a random value to a String.
The + operator can handle a string and an integer, converting the integer to string before concatenating. But you can't assign an integer to a string. Has nothing to do with using an array.
The operation += which translates to addition over its current value, converts integer to string and then concatenates it to the current state of string. However when you try to assign an integer value to a reference which is of type string, compiler will throw an error.
There are languages that will do even this for you, but it just does not work like that in a strongly typed language like java.
i am very very new to Java and i would like to know how can i compare 2 integers? I know == gets the job done.. but what about equals? Can this compare 2 integers? (when i say integers i mean "int" not "Integer").
My code is:
import java.lang.*;
import java.util.Scanner;
//i read 2 integers the first_int and second_int
//Code above
if(first_int.equals(second_int)){
//do smth
}
//Other Code
but for some reason this does not work.. i mean the Netbeans gives me an error: "int cannot be dereferenced" Why?
int is a primitive. You can use the wrapper Integer like
Integer first_int = 1;
Integer second_int = 1;
if(first_int.equals(second_int)){ // <-- Integer is a wrapper.
or you can compare by value (since it is a primitive type) like
int first_int = 1;
int second_int = 1;
if(first_int == second_int){ // <-- int is a primitive.
JLS-4.1. The Kinds of Types and Values says (in part)
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
If you want to compare between
1-two integer
If(5==5)
2- char
If('m'=='M')
3 string
String word="word"
word.equals("word")
int is primitive type.This itself having value but Integer is object and it is having primitive int type inside to hold the value.
You can do more operations like compare,longValue,..more by Using wrapper Integer.
== for Integer will not work the rang above -128 and 127. Integer hold cache value upto this range only in memory. More than this range you have to equals() method only to check Integer wrapper class.
equals() method will check the value stored in the reference location.
As int is primitive you can not use equals.
What you can do
Use Interger as wrapper
void IntEquals(Integer original, Integer reverse) {
Integer origianlNumber = original;
Integer reverseNumber = reverse;
if (origianlNumber.equals(reverse)) {
System.out.println("Equals ");
} else {
System.out.println("Not Equal");
}