One dimensional array in Java - java

When I run this code on cmd prompt with statement :
java Test A
output is
a
b
c
Wasn't it suppose to result in an error since dimension of args is 1 whereas dimension of x is 3 (args=x).
class Test
{
public static void main(String args[])
{
String[] x={"a","b","c"};
args=x;
for(String i: x)
{
System.out.println(i);
}
}
}

well, the array variable in java is only a reference, so if you give it another reference for a String array it will accept it, so the range of values the array variable(args) accepts is the references to String arrays at memory, it's like changing the value of an integer from 1 to 3, it's ok because they're both valid, and in the range that the integer accepts.

It will not result in an error because your object is not final and you are not changing the array object.
here
double[] data = new double[5]{2, 4, 5, 6, 8} // data can change but the instance of the class cant change
double[] data = new double[7] // here you are changing the data but not the object i.e the created instance of the object does not change but the instance the data(the variable) is holding changes
I hope you got your answer

Related

Why is the following Output the right one? [duplicate]

This question already has answers here:
Assigning Array to new variable, changing original changes the new one
(4 answers)
Problem with assigning an array to other array in Java
(4 answers)
How can an integer array be a reference type?
(2 answers)
Closed last month.
public class Alle {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int [] y = arr;
y[0] = 15;
System.out.println(Arrays.toString(arr));
}
}
The Output is 15,2,3,4 but why? I never changed "arr".
In Java, arrays are objects, not primitive types. When you are assigning link to arr to the new variable, y still points to arr, so you are actually changing arr. Thats it. But if you want to copy the array, you can use this method: Arrays.copyOf(int[] original, int newLength)
Let's assume you have a son, named jackson.
You introduce him to your friend, "Hey Friend, meet my son Jackson".
The friend says, "Hi Jackson, I'll call you jake."
Later that friend calls him and says, "Hey Jake, here take a handful of candies".
your son Jackson comes to you, and you see he has a handful of candies.
But how ? You never gave jackson candies. But your friend gave to jake.
Makes sense ?
In your code, the arr, and the y are exactly the same entity, not equal, not copy, but the exact same Object. So you make changes at one place, it'll show at the other one as well.
When you initialized the integer array viz arr in your case, it allocated a space in the heap to your reference variable arr when you executed the following code:
int[] arr = {1,2,3,4};
This arr is referring to an integer array in heap as arrays are objects in java.
Now when you performed the following code:
int [] y = arr;
This created one more reference variable y which is referring to the same object in the heap that your reference variable arr was referring to, that is why whatever changes you make through your reference variable y or reference variable arr will reflect the changes of the object created in the heap as they are referring to the same object.
If you want a new object allocated to your reference variable y that resembles the elements of your arr array then you can clone it. The following code represents it:
public class Alle {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int [] y = arr.clone(); //change here
y[0] = 15;
System.out.println(Arrays.toString(arr));
}
}
This gives an output:
[1, 2, 3, 4]
Hence your arr array is not affected this time.

How to enter one dimensional array filled with unknown values of variable

I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)

Varargs method modifies caller's array instead of its own copy?

I have this simple varargs method which divides each item in the list:
import java.util.*;
class A {
static long f(long... xs) {
Arrays.sort(xs);
long y = 100000000;
for (int i = xs.length - 1; i >= 0; i--)
y /= xs[i];
return y;
}
static {
System.out.println(f(5,2,6,3,9,3,13,4,5));
long[] xs = new long[]{5,2,6,3,9,3,13,4,5};
System.out.println(Arrays.toString(xs));
System.out.println(f(xs));
System.out.println(Arrays.toString(xs));
}
}
I'd expect it to pass a copy of the array, but apparently it's somehow modifying the array I pass in, instead of its own local copy:
$ javac A.java && java A
79
[5, 2, 6, 3, 9, 3, 13, 4, 5]
79
[2, 3, 3, 4, 5, 5, 6, 9, 13]
So I wrote this simple test program:
class B {
static void f(Object... os) {
System.out.println(os);
}
static {
Object os = new Object[]{1,2,3};
System.out.println(os);
f(os);
}
}
And it does what I expect, it clones the object array before passing it into f (hence different object identifiers):
$ javac B.java && java B
[Ljava.lang.Object;#1242719c
[Ljava.lang.Object;#4830c221
So how then is f in A modifying the caller's array instead of its own copy?
It looks like you've tricked yourself here:
Object os = new Object[]{1,2,3};
System.out.println(os);
f(os);
Since os is typed as Object, it gets interpreted as the first element of the varargs array. What gets passed into the method is actually a new Object[] whose single element is your Object[].
If you do the following, it will print the same instance:
Object[] os = new Object[]{1,2,3};
System.out.println(os);
f(os);
The f method will need make a defensive copy of the array itself in order to guarantee that an array passed in by the caller isn't modified. As arshajii points out, varargs are foremost array parameters, with the "bonus" behavior of creating a new array when given an argument list.
Anyway you can use Arrays.copyOf to make the copy, which delegates to (the less type-safe) System.arraycopy.
varargs is an array type, but with syntactic sugar to allow an on-the-fly array creation if elements are passed separately as parameters.
That is, these two signatures are identical:
static long f(long... xs) {
static long f(long[] xs) {
Except that the varargs may be called with separate elements instead of an array
Of course the array will get modified if you bypass the on-the-fly creation and create an array yourself to pass in.
So how then is f in A modifying the caller's array instead of its own copy?
It doesn't have its own copy. It has a reference to the caller's array.
In the end, an array is an object, so you don't modify the array reference itself instead its contents which is allowed.

please explain this output that using explicit cast to Object

class VarArgs {
public static void printArray(Object... args) {
for (Object obj : args)
System.out.print(obj + " ");
System.out.println();
}
public static void main(String[] args) {
printArray( new Integer[] { 1, 2, 3 });
}
}
The console's output is:
[Ljava.lang.Integer;#1888759
just want to know what is this output. The supposed castiing was via Object[] and that gives 1,2,3 as output, but when I use Object for casting I get this output
You can use
Arrays.toString(new Integer[]{1,2,3});
to view the actual contents of the array.
Or cast new Integer[]{1,2,3} to Object[] instead of Object, i.e:
printArray((Object[])new Integer[]{1,2,3});
Explanation of what is happening in your code:
When you are calling the printArray method you are casting your array to an Object so in fact you are passing just one object (not an array).
The foreach loop in the printArray method iterates only once as only one argument has been passed to the printArray method - the Integer[] {1,2,3} array.
Therefore When your code is calling toString, the toString from the Array class is called, not the toString from the Integer class as you might expect.
Finally the result you got: [Ljava.lang.Integer;#1888759 is caused by the lack of the implementation of the toString method in the array classes in Java.
To fix the issue in your code:
Replace:
printArray((Object)new Integer[]{1,2,3});
with:
printArray((Object[])new Integer[]{1,2,3});
To print the content of an array call:
Arrays.toString(new Integer[]{1,2,3});
As Marco said, this uses the default toString method of an Object, which is its (virtual) memory address.
I would recommend using the Arrays.toString method here
With regards to your use of variable arguments - try disassembling the class file by running
javap -verbose VarArgs
to see what this compiles down into - you should see that your integer array is being passed as the single element of an array.
That is not the same as passing an array! That is the same as passing a variable length of parameters, so the method treats the array as one object, not an array of objects, hence the printout.
public static void printArray(Object[] args) {
for (Object o : args) {
System.out.println(o);
}
}
Object[] objects = new Integer[] { 1, 2, 3, 4 };
printArray(objects);
Notice that you need to use the wrapper for int, primitive types are not subclasses of object.

Java Reflection - Editing Array Length

I was wondering if it is possible to change to change the length of a class's integer array using the Java Reflection API. If so, how?
Nope; an array is created with a fixed length.
What you can do is get close by modifying the value of the field with a copy in larger array (using Arrays.copyOf), so long as you know modifying like this won't cause any inconsistency.
/* desired length */
final int desired = ...;
/* the instance of the object containing the int[] field */
final Object inst = ...;
/* the handle to the int[] field */
final Field field = ...;
field.set(inst, Arrays.copyOf((int[]) field.get(inst), desired));
I don't think it's possible to change array length even with Reflection.
This is a reference from java tutorial.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An array is a fixed length data structure, so there is no way that it's length will be modified. Nevertheless, one can create a new array with a new fixed length in such way it can accommodate new members using
System.arrayCopy()
It is like you have an array of type T with the size of 2,
T[] t1 = new T[2]
and it is length is fixed with 2. So it can not store any more than 2 elements. But by creating new array with a new fixed length, say 5,
T[] t2 = new T[5]
So it can accommodate 5 elements now. Now copy the contents of the t1 to t2 using
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int
length)
in this case of the example,
System.arraycopy(t1, 0, t2, 0, t1.length)
Now in the new array, you have position
from t1.length to t2.length-1
is available for you to use.
I guess java will not allow you to change array length but yes you can set value at index using reflection.
import java.lang.reflect.*;
public class array1 {
public static void main(String args[])
{
try {
Class cls = Class.forName(
"java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String)Array.get(arr, 5);
System.out.println(s);
}
catch (Throwable e) {
System.err.println(e);
}
}
}

Categories