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

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.

Related

I keep getting NullPointerException when referencing an array index for my Deque [duplicate]

public class Test {
public int [] x;
public Test(int N)
{
int[] x = new int [N];
for (int i=0;i<x.length;i++)
{
x[i]=i;
StdOut.println(x[i]);
}
}
public static void main(String[] args) {
String path = "/Users/alekscooper/Desktop/test.txt";
In reader = new In(path);
int size=reader.readInt();
StdOut.println("Size = "+size);
Test N = new Test(size);
StdOut.println(N.x[3]);
}
/* ADD YOUR CODE HERE */
}
Hello guys. I'm learning Java through reading Robert Sedgwick's book on algorithms and I'm using his libraries such as StdOut, for example. But the question is about Java in general. I don't understand why Java here throws a NullPointerException. I do know what that means in general, but I don't know why it is here because here's what I think I'm doing:
read an integer number from the file - the size of the array
in the class Test. In my test example size=10, so no out-of-bound type of thing happens.
print it.
create the object N of type Test.
In this object I think I create an array of size that I have just
read from the file. For fun I initialize it from 0 to size-1 and
print it. So far so good.
and here where it all begins. Since my class is public and I've run
the constructor I think I have the object N which as an attribute
has the array x with size elements. However, when I'm trying
to address x, for example,
StdOut.println(N.x[3]);
Java throws NullPointerException.
Why so? Please help and thank you very much for your time.
what you did is called shadowing you shadowed your field x with local variable x. so all you need to do is avoiding this:
int[] x = new int [N]; is wrong, if you want your field to initialize instead of a local variable then you could do something like : x = new int [N]; for more information read this
change the first line in constructor from
int[] x = new int [N];
to
x = new int [N];
it should work...
Actually in constructor when you say int[] x, it is creating one more local variable instead setting data to public variable x... if you remove int[] from first line of constructor then it initizes the public variable & you will be able to print them in main() method
Inside public Test(int n):
Change
int[] x = new int [N]; // Creating a local int array x
to
x = new int [N]; // Assigning it to x
Everyone has given the code that would work. But the reason is something called as variable scoping. When you create a variable (by saying int[] x, you are declaring x as an integer array and by saying x = new int[4] you are assigning a new array to x). If you use the same variable name x everywhere and keep assigning things to it, it'll be the same across your class.
But, if you declare int[] x one more time - then you are creating one more variable with the name x - now this can result in duplicate variable error or if you're declaring in a narrower 'scope', you will be overriding your previous declaration of x.
Please read about java variable scopes to understand how scoping works.
int size=reader.readInt(); // size < 3
StdOut.println(N.x[3]); // length of x[] less than 3, so x[3] case NullPointException

One dimensional array in 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

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)

Beginner Java methods [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
public class Test {
int[] a1 = {1, 3, 5, 7, 2};
int[] a2 = new int[a1.length + 10];
public static int[] Array(){
for(int i = 0; i < a1.length; i++){
a2[i] = a1[i];
}
a1 = a2;
}
public static void main(String args[]){
System.out.println(a1.toString);
}
}
I am trying to create a method "Array" that will take in arrays a1 and a2 and add + 10 to the length of a1. My problem is that I don't know how to correctly name the method and how to call it in the main in order to print.
I have tried passing a1 and a2 in the constructor for Array but it doesn't work. I have also tried printing directly in the main() and it doesn't work either. What am I missing?
No idea what are you trying to do but in Java you can't change the size of array once it is declared but if you want to work with array with can change size then you should use arraylist not array and one more thing setting b = awould not work btw here is a code which swaps elements from one array to other but once again you can't change size of array in java: I return b back but you don't need to return an array back because an array variable(name of array) refers to a memory location.
public static int[] extendLength(int [] a, int [] b){
for(int i = 0; i < a.length; i++){
b[i] = a[i];
}
return b;
}
public static void main(String args[]){
int[] a1 = {1, 3, 5, 7, 2};
int[] a2 = new int[a1.length + 10];
int [] res = extendLength(a1,a2);
for(int i = 0; i < a2.length;i++)
System.out.println(a2[i]);
}
Long story short, the way you have your program set up, your variables will also need to be static; otherwise, your static methods will not be able to access them.
Static fields and methods are essentially singular to the class; therefore without a director to which object contains the field, asking a static method to manipulate a non-static field is very ambiguous.
I'm seeing a number of other problems in this program as well; namely, you're treating toString as a field (it's a method), your array method is missing a return statement, and your alignment is all over the place. This probably isn't an appropriate question to bring to Stack Overflow; I would encourage you to look at a tutorial, like the one at Tutorials Point, before bringing your question here.

Arrays and Referencing [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
Consider the following code:
public static void resize(int[] x){
x = new int[x.length*2];
System.out.println(x.length + " ");
}
public static void main(String[] args){
int[] x = {1,2};
resize(x);
System.out.println(x.length);
}
The output is "4 2". The question is: I thought that when we are defining an array in the code of the new length, the other array (the previous one with length 2) would be discarded, as now the value of the array points to the "larger" array. So, why would then print out at the end as length 2? I used Arrays.toString to verify, and indeed, the actual values of the array after the void method are {1,2}. This is confusing, as I thought that the array itself would be changed as the value is a pointer to the memory address (in contrast with using the method on a char/int variable, which would not affect the value of the variable).
When you call resize, you pass an array object to the method. This is the basic flow of your program:
initialize array of size 2
pass that array to resize()
resize has a reference to the value of the array
resize points it's reference to a new array twice the size of the old reference
prints "4"
main() prints the size of the initial array "2"
You don't change the original array in the new method, it merely has an array of the same value.
Because Java passes by value, the array doesn't change after your call to resize. (I'm assuming the output is actually 4 2, not 2 4.)
If you want resize to effect a permanent change, you should have the method return x; as its final statement (or use a global variable):
public static int[] resize(int[] x){
x = new int[x.length*2];
System.out.println(x.length + " ");
return x;
}
public static void main(String[] args){
int[] x = {1,2};
x = resize(x);
System.out.println(x.length);
}
The scope of your x variable in resize
public static void resize(int[] x){
x = new int[x.length*2];
}
is local to that function. It does not affect the x that was passed in. This means that as soon as resize completes, that local copy disappears and is eventually garbage collected.
If you want to resize the original array, return it. For example:
public static int[] getNewArrayOfDoubleLength(int orig_length){
return new int[orig_length * 2];
}
And call it with
x = getNewArrayOfDoubleLength(x.length);
Since arrays are immutable, this is a new array. The original one still exists (although it's inaccessible) until it's garbage collected.

Categories