I understand that declaring variables of type Object or passing an Object variable as a parameter in a method is so that we can pass any object type e.g. Integer or String or an array. I just wanted to ask if we can also pass primitive data types or cast to integer primitive types too?
For example if I have a class Stack which allows us to push and pop objects of type Object, then i can use this class for Integer objects BUT can i use it for a primitive type int?
Yes you can, because Java will “auto-box” your primitive type. In other words, if you pass an
intto your method, it will first get converted to anInteger, then thatIntegerwill be passed as an argument to your method.This tutorial gives more details about how it works.