Beginner Java methods [duplicate] - java

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.

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.

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

Why is this void method not working as I would expect? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
Assuming that the Given array is instantiated as follows:
int[] given = {1, 2, 3, 4, 5};
These methods should change the array and show the print results.
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
whatIsGoingOn(given); //make changes
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public void whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
}
I BELIVE THE PROBLEM to be with the void method, overriding the original values of the int[] given but the new initialization and declarations never make it out.
I Would expect the array to be:
{200, 0, 0, 0, 0};
But Java prints out:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
But in the case where I returned a newly changed array in the whatIsGoingOnMethod, I get my wanted results:
{1, 2, 3, 4, 5}
{200, 0, 0, 0, 0}
If the void method just does something and its not really being "applied" as I would like to expect. I'd appreciate an illuminating explanation for this.
This Question is ALREADY ANSWERED THANKS!!!
I need to freeze it.
With given = new int[5]; you are changing what the local variable given points to, not the object that it used to point to. The local is later out of scope. The array is never modified.
Youre creating a whole new array, and assigning the variable that used to refer to the original to the new array. Youre modifying the new array, and never touching the old one.
The appropriate fix would be similar to what follows:
public static void main(String[] args)
{
int[] original = new int[5];//already allocating memory, initializing to default value, etc.
setFirstTo20(original);
System.out.println(original[0]);//still 20!
}
public static void setFirstTo20(int[] given)
{
for (int i : given)
System.out.println(i);//for debugging, before change
given[0] = 20;
for (int i : given)
System.out.println(i);//after change
//heres whats happening to you
given = new int[5];
given[0] = 40;
for (int i : given)
System.out.println(i);//show new changes to NEW array
}
Obviously you should get rid of the extraneous code if you intend for this or similar methods to be used in actual classes.
Because the argument given of function whatIsGoingOn is passed by value.
To change it in a void function, you have to wrap it in an object like this:
class ArrayRef {
public int[] array;
}
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
ArrayRef ref = new ArrayRef();
ref.array = given; //set a reference to the given array
whatIsGoingOn(ref); //make changes
given = ref.array; //get the changed array
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public void whatIsGoingOn(ArrayRef ref) {
ref.array = new int[5];
ref.array[0] = 200;
}
Arrays such as int[] are reference types. This means that when you do the assignment given = new int[5], you are chainging the array referenced within whatIsGoingOn() and not affecting the array referenced within change().
To do what you want it to, you need to loop though the array and change the individual elements within the array.
for(int i = 0; i < given.length; i++) {
given[i] = 0;
}
given[0] = 200;
change following lines of whatIsGoingOn method from
given = new int[5];
given[0] = 200;
to
Arrays.fill(given,0);
given[0] = 200;
It still holds reference to original array .No need to return anything.
Void quite simply will return nothing. Replace void with int[] to achieve your expected results. Also replace
public void whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
}
with
public int[] whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
return given;
}
the final result should be
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
given = whatIsGoingOn(given); //make changes
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public int[] whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
return given;
}

Java, what is the point of creating new objects?

I am fairly new to Java and was wondering what the difference between the two is. For this example I used arrays:
class testpile {
public static void main(String[] args)
{
int[] a = {1,2,3,4,5,6}; //First array
int[] b = new int[5]; //Second Array
b[0] = 7;
b[1] = 8;
b[2] = 9;
b[3] = 10;
b[4] = 11;
print(a);
print(b);
}
public static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
I understand that using "new" creates a unique object but what are the advantages of using one over the other?
In your example there's no real difference between the two. The first is mostly just "syntactic sugar" for the latter. In both cases the array is allocated on the heap.
Both of the code creating a int array of size 5/6
In the first case the array is initialized with vale at the time of creation
In second case the value is assigned latter
that's the difference
I understand that using "new" creates a unique object but what are the advantages of using one over the other?
Both constructs do exactly the same thing (with different data, though): Creating an array and filling it with data. In particular, both these arrays are "unique objects".
You'd use the "less literal" one when you do not know the size and the initial values for the element at compile-time.
int[] a = {1,2,3,4,5,6}; //First array
int[] b = new int[5]; //Second Array
They are just two different ways of creating an array. There isn't really any OOP involved here.
The first one is better when you know the values before hand, otherwise the second is better.
The first statement is called array initialization where six int variables are created and each variable is assigned. In second statement, the new keyword create 5 int variables whose initial value is zero.
Using new keyword, you may instantiate an array whenever you require.
int []a=new int[5];
for(int i:a)
System.out.println(i);
a=new int[]{11,22,33};
for(int i:a)
System.out.println(i);
I think the result is same.
But when you create a array with "new" clause, You should assign a specify length of the array.
e.g int[] b = new int[**5**];
And in this sample, you can also assign the value for b[5]. there shouldn't produce compilation error.But the error should occur in the runtime.
In regard to the another method, the length of the array don't need specify. It depend on the element count of array.

Modify an array passed as a method-parameter

Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1
}
public static void method(int[] n)
{
n = new int[]{2};
}
while I can modify it:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 2
}
public static void method(int[] n)
{
n[0] = 2;
}
Then, I tried to assign an arbitrary array to the array passed as parameter using clone():
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1 ?!
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
n = temp.clone();
}
Now, I wonder why it prints 1 in last example while I'm just copying the array with clone() which it's just copying the value not the reference. Could you please explain that for me?
EDIT: Is there a way to copy an array to object without changing the reference? I mean to make last example printing 2.
Your examples 1 and 3 are virtually the same in context of the question - you are trying to assign a new value to n (which is a reference to an array passed by value).
The fact that you cloned temp array doesn't matter - all it did was create a copy of temp and then assign it to n.
In order to copy values into array passed into your method method you might want to look at:System.arraycopy
It all, of course, depends on the sizes of your n array and the one you create inside method method.
Assuming they both have the same length, for example, you would do it like that:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]);
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
System.arraycopy(temp, 0, n, 0, n.length);
// or System.arraycopy(temp, 0, n, 0, temp.length) -
// since we assumed that n and temp are of the same length
}
In your method
public static void method(int[] n)
n is another name for the array that way passed in. It points to the same place in memory as the original, which is an array of ints. If you change one of the values stored in that array, all names that point to it will see the change.
However, in the actual method
public static void method(int[] n) {
int[] temp = new int[]{2};
n = temp.clone();
}
You're creating a new array and then saying "the name 'n' now points at this, other array, not the one that was passed in". In effect, the name 'n' is no longer a name for the array that was passed in.
As you correctly note, you cannot assign to the array reference passed as a parameter. (Or more precisely, the assignment won't have any effect in the caller.)
This is about the best that you can do:
public static void method(int[] n) {
int[] temp = new int[]{2};
for (int i = 0; i < temp.length; i++) {
n[i] = temp[i];
}
// ... or the equivalent using System.arraycopy(...) or some such
}
Of course, this only works properly if the size of the input array is the same as the size of the array you are copying to it. (How you should deal with this will be application specific ...)
For the record Java passes the array reference by value. It doesn't pass the array contents by value. And clone won't help to solve this problem. (At least, not with the method signature as declared.)
In your method method, nothing that you assign to n will ever change the value of the object passed in and assigned to n. At the beginning of method, n points to an array. When you assign n to equal another array, you've simply re-pointed which array n points to, and haven't changed anything about temp_array from the main method.

Categories