pass value in Boolean Object - java

public class BuildStuff {
public static void main(String[] args) {
Boolean test = new Boolean(true);
Integer x = 343;
Integer y = new BuildStuff().go(test, x);
System.out.println(y);
}
int go(Boolean b, int i) {
if(b)
return (i/7);
return (i/49);
}
}
This is from SCJP , I understand that answer is "49", but I have a doubt. When we create an object and pass a value in that object. Let's say: Dog d = new Dog("tommy"); in this statement d is reference to object Dog and Dog has "name" instance variable set to "tommy". But it doesn't mean d = tommy.
However, in case of Boolean, when we passed true in Boolean Object. It sets reference to true. Why it is in case of Boolean? Is there any other class too?

The passed-in Boolean b can be converted to a primitive boolean with an unboxing conversion, resulting in the expression true for the if statement.
All primitive types have corresponding built-in wrapper classes for them, and Java will unbox/box as necessary.
Boolean <=> boolean
Byte <=> byte
Character <=> char
Short <=> short
Integer <=> int
Long <=> long
Float <=> float
Double <=> double
(An unboxing conversion will fail with a NullPointerException if the corresponding wrapper class instance is null:
Boolean test = null;
// NPE
boolean b = test;
)
Here's Java's tutorial on boxing and unboxing.

From the javadoc: The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.
If you have
Boolean a = new Boolean(true);
Boolean b = new Boolean(true);
a and b are different objects, but a.booleanValue() and b.booleanValue() return the same primitive. This can be verified by testing a == b versus a.equals(b).
There are other classes like this, viz. Integer, Double, etc. As others have already mentioned, you should look into autoboxing and unboxing.

Related

Casting a primitive vs Creating a object of the primitive

I'm not habitual to casting a primitive data type to an object. Saw some code like:
public static int CompareAges(Person p1, Person p2) {
Integer age1 = p1.getAge();
return age1.compareTo(p2.getAge());
}
The instantiation of age1 seemed extraneous, so I tried to write the code as:
public static int CompareAges(Person p1, Person p2) {
return p1.getAge().compareTo(p2.getAge());
}
But that raised a compiler error because p1.getAge() is a primitive data type int and not an Integer, which is an object.
Intuitively, I did:
public static int CompareAges(Person p1, Person p2) {
return ((Integer) p1.getAge()).compareTo(p2.getAge());
}
and it worked!
The question: What did I miss? Since when did we start casting primitives as value types?
It's what happens internally:
1. Integer age1 = p1.getAge();
Integer != int
Integer = Integer.valueOf(int)
Integer age1 = Integer.valueOf(p1.getAge());
2. p1.getAge().compareTo(p2.getAge());
int.compareTo(int)
^^^
// it's just a primitive type, as a result - the compile error
3. ((Integer) p1.getAge()).compareTo(p2.getAge())
Integer.compareTo(int)
Integer.compareTo(Integer.valueOf(int))
((Integer) p1.getAge()).compareTo(Integer.valueOf(p2.getAge()))
4. (Integer) p1.getAge() ---> Integer.valueOf(p1.getAge())
// why so? look at callOfCode's answer
But, in my opinion, ((Integer) p1.getAge()).compareTo(p2.getAge()) looks ugly.
I would replace it to
p1.getAge() > p2.getAge() ? 1 : (p1.getAge() < p2.getAge() ? -1 : 0)
or to
Integer.compare(p1.getAge(), p2.getAge()) // java 7+
I wouldn't like to do casting in this case.
More about "autoboxing/unboxing" you may find here.
Each primitive has its own boxing type
The Boxing could be implicit (Autoboxing) or explicit like you did it in your code.
p2.getAge() is an Example of AutoBoxing or Implicit Boxing. The method compareTo takes an Object. As it is a primitive, Java converts it automatically to the correspondent Boxing Object (Integer). You did the explicit Boxing with the cast (Integer) p1.getAge()
Difference between new Integer(primitive); and Integer integer = (Integer)primitive; Is only on bytecode level. In the first case, new object of Integer class is created in memory. In the second case, Integer.valueOf(primitive) is called internally. This is the static method that checks if primitive falls into range of -128 to 127 and if it falls, it returns value from integer cache and no new object is being created. If it not falls into that range, new Integer object is instantiated. It is used for efficiency. But such efficiency is unsignificant novadays.
int z = 1;
Integer a = (Integer)z;
Integer b = (Integer)z;
//Prints true, since Integer object is retrieved from cache (range of -128 to 127)
System.out.println(a == b);
int w = 999;
Integer c = (Integer)w;
Integer d = (Integer)w;
//Prints false, since 999 is not in cache, new Integer objects are instantiated and they points to different places in memory
System.out.println(c == d);

Is there a Integer class in c#?

We have Integer class in JAVA, but I couldn't find any equivalent class in C#? Does c# have any equivalent? If not, how do I get JAVA Integer class behavior in c#?
Why do I need this?
It is because I'm trying to migrate JAVA code to c# code. If there is an equivalent way, then code migration would be easier. To addon, I need to store references of the Integer and I don't think I can create reference of int or Int32.
C# has a unified type system, so int can be implicitly boxed into an object reference. The only reason Integer exists in Java is so that it can be converted to an object reference and stored in references to be used in other container classes.
Since C# can do that without another type, there's no corresponding class to Integer.
Code migration won´t work out of the box for any type of language without any manual changes. There are things such as a class Integer that simply does not exist within (C# why should it anyway, see recursives answer), so you´d have to do some work on your own. The nearest equivalent to what you´re after is Int32 or its alias int. However you may of course write your own wrapper-class:
public class Integer
{
public int Value { get; set; }
public Integer() { }
public Integer( int value ) { Value = value; }
// Custom cast from "int":
public static implicit operator Integer( Int32 x ) { return new Integer( x ); }
// Custom cast to "int":
public static implicit operator Int32( Integer x ) { return x.Value; }
public override string ToString()
{
return string.Format( "Integer({0})", Value );
}
}
The beauty of C# is that it has a unified type system. Everything derives from object, even primitive types. Because of this, all keywords are simply aliases for a corresponding class or struct. Java does not use a unified type system, so a separate Integer class is required to wrap the int primitive. In C# int is synonym for the Int32 struct.
What you're looking for has been right in front of you the whole time. Start using the dot notation directly on the int keyword (i.e. int.whatever()) to access the all goodness of the .NET version of the Javian Integer class.
I did some testing with Nullable types in a console application and it appears that they do not behave as you wish. For example:
static void Main(string[] args)
{
int? x = 1;
Foo(ref x);
Console.WriteLine(x);//Writes 2
}
private static void Foo(ref int? y)
{
y += 1;
var l = new List<int?>();
l.Add(y);
l[0] += 1;//This does not affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 2
Foo2(l);
}
private static void Foo2(List<int?> l)
{
l[0] += 1;
Console.WriteLine(l[0]);//writes 4
}
But if you roll your own generic class to wrap primitive/value types for use within your application you can get the behavior you are expecting:
public class MyType<T>
{
public T Value { get; set; }
public MyType() : this(default(T))
{}
public MyType(T val)
{
Value = val;
}
public override string ToString()
{
return this.Value.ToString();
}
}
static void Main(string[] args)
{
var x = new MyType<int>(1);
Foo(x);
Console.WriteLine(x);//Writes 4
}
private static void Foo(MyType<int> y)
{
y.Value += 1;
var l = new List<MyType<int>>();
l.Add(y);
l[0].Value += 1;//This does affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 3
Foo2(l);
}
private static void Foo2(List<MyType<int>> l)
{
l[0].Value += 1;
Console.WriteLine(l[0]);//writes 4
}
int, int? and System.Int32 are all struct and thus value types and does not compare to Java's Integer wrapper class which is a reference type.
System.Object class though a reference type can cause issue as boxing creates immutable object. In short, you can't alter a boxed value.
int a = 20;
Object objA = a; //Boxes a value type into a reference type, objA now points to boxed [20]
Object objB = objA; //Both objA & objB points to boxed [20]
objA = 40; //While objB points to boxed [20], objA points to a new boxed [40]
//Thus, it creates another ref type boxing a 40 value integer value type,
//Boxed values are immutable like string and above code does not alter value of previous boxed value [20]
Console.WriteLine($"objA = {objA}, objB={objB}");
//Output: objA = 40, objB=20
What exactly corresponds to Java's Integer is a custom generic wrapper class.
int a = 20;
Wrapper<int> wrapA = new Wrapper<int>(a);
Wrapper<int> wrapB = wrapA; //both wrapA and wrapB are pointing to [20]
wrapA.Value = 40; //Changing actual value which both wrapA and wrapB are pointing to
Console.WriteLine($"wrapA = {wrapA}, wrapB={wrapB}");
//Output: wrapA = 40, wrapB=40
Console.ReadKey();
Implementation of the wrapper class is given below:
public class Wrapper<T> where T : struct
{
public static implicit operator T(Wrapper<T> w)
{
return w.Value;
}
public Wrapper(T t)
{
_t = t;
}
public T Value
{
get
{
return _t;
}
set
{
_t = value;
}
}
public override string ToString()
{
return _t.ToString();
}
private T _t;
}
As pointed out in other answers, C# has a unified type system so everything derives from object. If you need to handle null values then use int? to specify that the integer object can be null.
c# have a integer type called int link is here
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx

Method to box primitive type

Here is a table of primitive types and their equivalent wrapper class.
Primitive type Wrapper class
============== =============
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
I would like to create a method that would convert any given primitive variable into an appropriate class. I have tried something like below, but that obviously does not work. Any help would be appreciated:
public static <T> T forceBox(T t) {
switch (T) {
case boolean.class : return new Boolean(t);
case int.class : return new Integer(t);
// etc
}
}
the caller code looks like:
int x = 3;
System.out.println("x wrapper type: " + forceBox(x).getClass());
Though this is completely unnecessary in most cases, just use
public static <T> T forceBox(T t) { // compiler will add the conversion at the call site
return t;
}
Though you can also just use
Object o = <some primitive>;
The conversion is already done when needed as part of the boxing process.

Why doesn't Java autobox int to Integer for .equals(Object) method?

I was working on some java classes, and was overriding the .equals(Object) method to test an integer variable of my class, and was surprised when it threw errors saying I could not use the primitive type int, when I was sure it said in the java docs that the compiler will automatically autobox primitive types into the wrapper types for methods.
public boolean equals(Object o)
{
if (!(o instanceof myClass))
return false;
myClass mc = (myClass)o;
return (this.myInt.equals(mc.getMyInt()));
}
I suppose that "this.myInt" is a int and not a Integer. Autoboxing would work in the parameter. Here are some exemple
int a = 1;
int b = 1;
Integer c = 1;
Integer d = 1;
a.equals(b); // doesnt work as equals isn't define on int
c.equals(b); // work, c is an Integer/Object and b is autoboxed
c.equals(d); // work, both are Integer/Object
You could just use return (this.myInt==mc.getMyInt()); . the equals() method is only defined for Objects.

What is the main difference between primitive type and wrapper class?

What is the difference between these two lines?
int pInt = 500;
and
Integer wInt = new Integer(pInt);
Or
Integer wInt = new Integer(500);
None.
That's the exact same thing. In the first case you just have a supplementary variable.
Note that with autoboxing you rarely need to have both an int and an Integer variables. So for most cases this would be enough :
int pInt = 500;
The main case where the Integer would be useful is to distinguish the case where the variable is not known (ie null) :
Integer i = null; // possible
int i = null; // not possible because only Object variables can be null
But don't keep two variables, one is enough.
In Java, an instance of a primitve class holds the actual value of the instance, but instance of a wrapper class holds a reference to the object. i.e. The address of the place where the object would be found.
When you write a program with this line:
Integer integer = 500;
The compiler changes it to this:
Integer integer = new Integer(500);
This process is called autoboxing. That is automatically putting a primitive-instance in a "box" of Integer. Hence, output of the following program:
public class PrimitiveToObject {
public static void main(String[] args) {
printClassName(1);
printClassName(1L);
printClassName((char)1);
}
public static void printClassName(Object object){
System.out.println(object.getClass());
}
}
is this:
class java.lang.Integer
class java.lang.Long
class java.lang.Character
Also this:
int i = integer;
changes into this:
int i = integer.intValue();
This is called unboxing.
As you can see above, the dot operator(.) is used on the variable named integer but not on i. That is: a wrapper's object can be dereferenced, but not a primitive instance.
Boxing and unboxing may slow down the program a little bit. Hence, to a newbie, wrappers may look like added burden, but they are not so. Wrappers are used at places where the object needs to be a reference type. eg: Map<Integer,String>map=new HashMap<Integer,String>(); is a valid statement, but Map<int,String>map=new HashMap<int,String>(); is not a valid statement.
Another typical case where wrapper is very useful: In MySQL, NULL is a valid entry for a column of INT type. But in Java, int cannot have a null value, Integer can. This is because in SQL NULL symbolises Not Available. So if you are using JDBC to insert integer values in a MySQL table, a null in your java program will help in inserting NULL in the MySQL table.
A wrapper class can also be useful in a case similar or anologous to this:
Boolean decision; // Using wrapper for boolean.
if("YES".equalsIgnoreCase(consent))
decision = Boolean.TRUE; // In favour
else if("NO".equalsIgnoreCase(consent))
decision = Boolean.FALSE; // Not in favour
else if("CAN'T SAY".equalsIgnoreCase(consent))
decision = null; // Undecided
For starters
int pInt = 500; , here pInt is not an object whereas in
Integer wInt = new Integer(500);
wInt is an reference
This is also a reason why java is not pure Object Oriented Language. Because everything is not object with java.
Wrapper class will have a box in that box it will cover the primitive data types there are 8 primitive data types namely byte,int ,long ,double, float, short ,Boolean ,char these all covered in wrapper class .
to use primitive data types we use like int a;
but to use wrapper class we need to use like Integer a = new Integer(i);
The types of data are the same, but there are situations that manipulation of objects is more convenient than primitive types, like data structures, where you need more control of your data types.
For example, objects can be null and primitive types can't.
You also can't call methods in a primitive type (.compareTo(), .equals(), ...), but in wrapper classes you can.
The information below describe the types in primitive and wrapper class:
Primitive Types | Wrapper Class (Superclass = Object)
boolean - Boolean
char - Character
Primitive Types | Wrapper Class (Superclass = Number)
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
To understand how the wapper classes works, consider the example below:
public final class IntWrapper {
private final int intVal;
IntWrapper(int intVal) {
this.intVal = intVal;
}
public int getInt() {
return intVal;
}
}
Now we can make an object out of our new IntWrapper class and 'box' the primitive int value 41:
int i = 41;
IntWrapper iw = new IntWrapper( i ); // box the primitive int type value into the object
i = iw.getInt(); // unbox the value from the wrapper object
My example IntWrapper class is immutable, immutable means that once its state has been initialized its state cannot be changed.
When the final keyword is applied to a class, the final class cannot be extended. In other words, a final class can never be the superclass of a subclass. A final class can be the subclass of superclass, not problem there. When a class is marked final, all of its methods are implicitly final as well.
It is important to note that when final is applied to a reference variable it does not prevent the members of the object instance from changing values.
This example is to better understanding how the wrapper classes works inside.
Next, to create Integer, Double and other wrapper classes, you can write:
Integer i = new Integer(4);
Double d = new Double(9.62);
Boolean b = new Boolean("true");
Character c = new Character('M');
To get the encapsulated number into wrapper objects, you can write:
long l = i.longValue();
double e = i.doubleValue();
float f = d.floatValue();
short s = d.shortValue();
Each wrapper class include special methods to convert between primitive type to wrapper objects, that represent not number values:
boolean bo = b.booleanValue();
char ch = c.charValue();
Up to Java 5 version, the creation of objects from wrapper classes had to be in the syntaxes like above, but to simplify these operations, mainly related to insertion of values in the data structures offered in Java collections (that only accept objects), now exists the autoboxing or boxing and autounboxing or unboxing options.
The autoboxing or boxing allows you to insert a primitive value to reference of equivalent wrapper types or Object type:
// Same result of Double d = new Double(-2.75);
Double objD = -2.75;
// Same result of Object objI = new Integer(13);
Object objI = 13;
The autounboxing or unboxing allows you to insert a wrapper object into a variable of primitive type, converting automatically between equivalent types:
// Same result of double vd = objD.doubleValue();
double vd = objD;
// Same result of int vi = objI.intValue();
int vi = objI;
The most important practical difference I've seen is Integer is way more slower to initialize and do calculations with, than int. I would avoid Integer unless necessary.
int x = 20_000_000;// 20 millions
for (int i = 0; i < x; i++) {
ix += 23;
}
it takes 138 ms(average over 50 trials) to complete the loop when ix is an Integer but only takes 10 ms when ix is an int

Categories