Is this an object in Java? - java

When I write this piece of code in Java:
int []Array;
Array = new int[]{1,2,3,4,5};
Is "Array" an object? If so, What type?

From Java Tutorials: Arrays (emphasys mine):
An array is a container object that holds a fixed number of values of a single type.
From this sentence, the answer to your questions:
Is Array an object?
A: Yes.
If so, What type?
A: int[].

In java array is consider as object of the array declared type.
Try this one to get the type of the array.
System.out.println(Array.getClass().getComponentType());

It may be confusing, but you don't create an array with a type called "Array." You define it relative to the type of its contents.
So you create an array of integers like this
int[] first = new int[10];
or
int[] second = new int[] {3, 5, 7, 9};
The brackets tell you it's an array type. And first and second are both objects.
See this resource for more details.
Now just to confuse matters, there is a utility class called Arrays. This class is useful for things like sorting, searching, and other common operations.

If you write the piece of code, as given, then Array is an object of type int[] (as stated in comments).
also an Object (rule of thumb) is "everything" whose type-declarator begins with a majuscle
(uppercase letter)
//short intro to fields:
access modifier | static | final | type | name
public/private/2 more | or not | constant | primitve or Object<T> | lowercase identifier
Examples
private int a;
public static final String greeting = "Welcome!";
thus in general fields and methods are named lowercase.
the only types that do not generate objects are the so called primitives:
int
boolean
char
short
long
double
...
these also have Wrapper-Classes providing additional functionality
Int
Double
Boolean
//and so on;)

Related

why I need 'new' for array parameter? [duplicate]

This question already has answers here:
Passing directly an array initializer to a method parameter doesn't work
(3 answers)
Closed 2 years ago.
int add(int[] scores){ ... }
-------------------------------
int result = add({1,2,3}); //wrong
int result = add(new int[] {1,2,3}); //correct
I know I have to code like this but
why we must put 'new int[]' for parameter??
The array initializer syntax ({1, 2, 3}) can only be used in certain circumstances:
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
In other circumstances, you would need to use an array creation expression (e.g. new int[] {1, 2, 3}).
This is just how the language is specified. It could be different, but it's not.
As it has been pointed out, the array initialize can only be used in variable declarations.
You might want to use varargs in you example like that:
int add(int... scores){ ... }
You can call it in two ways:
int result = add(1,2,3);
int result = add(new int[] {1,2,3});

how to store an integer type value or an object type value into a char array in java

I was trying to store an integer type value and an object type value into a char array. I tried to use cast, but it did not work. the compiler throws a castexception. I wonder if there any method like Integer.parseInt() to convert it.
appreciated for your answer.
I am not sure what exactly your question here is but what I understood is that you want integer values to be converted to string and then chop each characters and store them in a char array. If that is your requirement then this is how you are going to solve your problem. Regarding object type value, you can refer to what Samrat Dutta said.
public static void main(String[] args) {
int input = 145689; // Taking an integer
String string = Integer.toString(input); //Converting to string
for(char c: string.toCharArray()) //Putting them inside a character array
System.out.println(c);
}
I hope this helps!
You simply cannot store objects of other classes into a char array. It doesn't work that way. You can only store objects of the same class or subclass in an array. Or, what you can do to store different objects, including numbers and characters in the same array is to use an Object array, as Object is the super class of all other classes in Java. And then cast your objects into Object type, or autobox and cast primitives to Object type and then add them to the array.

How array of primitive types work in Java?

In java, It is said that "every thing instantiated other than primitive type is an object."
I am trying to understand this point using below code (line 4 to be specific).
public class dummy{
public static void main(String[] args){
int[] i = new int[2];
i[0] = new Integer(3); //line 4
i[1] = 3;
System.out.println(int[].class);
System.out.println(i[0]);
}
}
After running
int[] i = new int[4];
Java is creating an object [0,0] of type class [I. The two members within this object [0,0] are primitive data type(but not reference type).
My questions:
Why does Java allow assignment of an object to primitive type member as per below line?
i[0] = new Integer(3); // object of type 'class Integer' getting assigned to i[0]
How do I understand this? In counter, i[0] displays value 3 but not object address.
What is I in class [I? I mean, for class C{}; , C[].class gives class [LC
where [ means "array of" and LC means "instance of 'class C'"
i[0] = new Integer(3);
This involves what's known as auto-unboxing. In the Dark Ages of Java (pre-1.5) we used to have to explicitly box and unbox primitive types. But thankfully the language designers had pity on our poor fingers and added some syntactical sugar. They now let us convert freely between primitives and their wrapper types. Java secretly transforms the above code into this:
i[0] = new Integer(3).intValue();
That's auto-unboxing. Similarly, it will box values for you without your having to ask. If you write:
Integer i = 5;
Java will actually perform:
Integer i = Integer.valueOf(5);
What is I in class [I?
That's I for int.
Java is expecting you to assign an int to an element of the array, but you pass Integer, so it is automatically unboxed as int.
By the way, when you create an Integer[] array, you will also get the same result when doing System.out.println, because Integer.toString just creating the string of it's value, not "object address".
[ means one-dimensional array. I means int.
java/lang/Integer.intValue:()I is being called when you do i[0] = new Integer(3); //line 4 i.e, the compiler is implicitly getting the int value of the Integer and adding it in the array.
For your first question, Java autoboxes primitive types with their wrapper classes (for example, int gets wrapped into the Integer class) and also unboxes wrappers of primitive types.
Here is the documentation: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
the compiler performs the conversion between primitives and their corresponding objects as a convenience for the programmer.

Integer vs int types, which is better? [duplicate]

This question already has answers here:
Which one to use, int or Integer
(11 answers)
When to use wrapper class and primitive type
(11 answers)
Closed 9 years ago.
Why does Java have these Integer, Character types and classes
while they are also adapting C's int, char etc
Sometimes when people are creating arrays, they tend to
use Integer[] i = {......}
rather than int[] i = {....};
what is the difference then?
Integer is an object, while int is a primitive. Whenever we pass an int into a function, we pass it as-is.
Integer wraps an int. In its case it is immutable so editing it via reference isn't going to work, but it can be put into generics. This can be set to null while int does not have a possibility of anything beyond 0 or a special value you interpret as a null condition, such as -1 or Integer.MAX_VALUE.
For instance, ArrayList<int> is completely invalid while ArrayList<Integer> must be used with ints being wrapped.
With autoboxing, however, we can immediately add an int to an ArrayList without manually wrapping it, and if we need a primitive when we get() the entry, it'll automatically unwrap it transparently.
In the end if you're doing calculations with a limited number of distinct variables or a fixed array, you should generally use int. When dealing with sets, lists, or maps, you should declare the collection as FooCollection<Integer> then add( an int directly allowing for autoboxing.
Integer, Character and others like this are Objects while int, char and others like this are primitives.
The biggest difference is that an Object can be null while a primitive value can't.
It's recommended to use primitive values where you can because they use less memory.
The only difference we can tell generally is Wrapper is objective representation of primitive.
Wrapper classes are used to represent primitive values when an Object is required.
In java,
Integer is a wrapper class i.e. it is an object while int is a primitive.
Integer default value is null while for int it is 0
There is a concept of autoboxing and auto-unboxing for these two types.
An integer can be converted to an int and vice versa
Followign program demonstrates this
public class TestClass {
int num;
Integer number;
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.num);
System.out.println(testClass.number);
testClass.autoBoxInt(testClass.num);
}
public void autoBoxInt(Integer number){
System.out.println(number);
}
}
The output is
0
null
0
The statement System.out.println(testCkass,num) prints int default value i.e. 0. System.out.println(testClass.number) prints Integer default value i.e. null. When you pass testClass.num to a method with parameter Integer, int is automatically converted into and Integer object. so the method prints out 0.
The java collections framework uses autoboxing to convert primitives into Wrapper classes because they cannot take primitive values. They help fast retrieval and storing of objects into collections using hashing and hashcodes. Following example demonstrates this
Set<Integer> numbers = new HashSet<Integer>();
numbers.add(new Integer(10));
numbers.add(new Integer(4));
numbers.add(6);
numbers.add(-9);
numbers.add(new Integer(65));
System.out.println(numbers);
This prints out the set
[4, 65, 6, -9, 10]
To know what hashing is and how hashcodes are used, you can look these links
http://www.thejavageek.com/2013/06/27/what-are-hashcodes/
http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/

How can I store an int array into a number array?

Integer extends Number so in that sense Number becomes the superclass of int. I want to store an int array into a Number array..
I have the following code.However, it seems it is not allowed in java.
int[] b = {1,2};
Number[] a = b;
Why java does not allow me to store an int array in number array and how do I store this out ?
You can't do that directly, because an "array-of-primitives" is not an "array-of-objects". Autoboxing does not occur with arrays.
But you can use ArrayUtils.toObject(b) (from commons-lang). This will create a new array of the wrapper type (Integer) and fill it with the values from the primitive array:
int[] a = {1,2};
Number[] n = ArrayUtils.toObject(a);
Because int and Integer are two separate types. The first one is a primitive type, and the second one is an object type. Integer extends Number, but int is not even a class, and it thus can't extend anything.
I would guess this has something to do with Number being an abstract class (API Page), meaning the it cannot be used to represent an item, but allows other classes to share functionality. If you could store items in a Number array, they would lose their type, and become instances of Number, which is impossible as it's abstract.

Categories

Resources