Java, what is the point of creating new objects? - java

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.

Related

How to work with arrays with an unknown number of dimensions in Java? [duplicate]

I need to be able to have an n-dimensional field where n is based on an input to the constructor. But I'm not even sure if that's possible. Is it?
Quick solution: you could approximate it with a non-generic ArrayList of ArrayList of ... going as deep as you need to. However, this may get awkward to use pretty fast.
An alternative requiring more work could be to implement your own type using an underlying flat array representation where you calculate the indexing internally, and providing accessor methods with vararg parameters. I am not sure if it is fully workable, but may be worth a try...
Rough example (not tested, no overflow checking, error handling etc. but hopefully communicates the basic idea):
class NDimensionalArray {
private Object[] array; // internal representation of the N-dimensional array
private int[] dimensions; // dimensions of the array
private int[] multipliers; // used to calculate the index in the internal array
NDimensionalArray(int... dimensions) {
int arraySize = 1;
multipliers = new int[dimensions.length];
for (int idx = dimensions.length - 1; idx >= 0; idx--) {
multipliers[idx] = arraySize;
arraySize *= dimensions[idx];
}
array = new Object[arraySize];
this.dimensions = dimensions;
}
...
public Object get(int... indices) {
assert indices.length == dimensions.length;
int internalIndex = 0;
for (int idx = 0; idx < indices.length; idx++) {
internalIndex += indices[idx] * multipliers[idx];
}
return array[internalIndex];
}
...
}
Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array also contains another newInstance method to create multi-dimensional arrays. For example:
int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings
Since the number of dimensions is not known until runtime, you can only handle the array as an Object and you must use the get and set methods of the Array class to manipulate the elements of the array.
Try this:
https://github.com/adamierymenko/hyperdrive

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 does Java throw NullPointerException here?

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

What does it mean to return a reference to an array?

I was doing some exercises on arrays, and I was prompted to return a reference to an array after copying it element by element. What does this exactly mean?
My code is the following:
public static int[] cloneArray(int array[])
{
int[] arraycopy = new int[array.length];
for(int i = 0; i < array.length; i++)
{
arraycopy[i] = array[i];
}
return arraycopy;
}
I don't know what I should be returning though as a "reference": should I return an array of ints or an int? Whenever I try to print the array, I get a weird combination of characters and numbers (unless I invoke Arrays.toString()).
"Return a reference to an array" just means "return an array".
Java only returns values, which are either primitives or object references (ie for objects, the value is a reference).
Although Java is based on C, it doesn't sully itself with pointers etc like C does.
In Java, arrays and objects do not act like primitive types such as int. Consider the following code:
public class MyClass {
public static int method1(int ar[]) {
int x = ar[1];
ar[1] = 3;
return x;
}
}
Now suppose that somewhere else, the follow code is executed:
int abcd[] = new int[3];
abcd[0] = 0;
abcd[1] = 1;
abcd[2] = 2;
int d = MyClass.method1(abcd);
System.out.println(abcd[1]);
What would be printed? It's not 1, but 3. This is because the method was not given the data in the array, it was told the location of the array. In other words, it was passed a reference. Because it was using a reference, changing the value of an array index changed its value in the code that called it. This would not have happened if method1 had taken an int as an argument.
Basically, in Java, methods do not accept arrays as arguments or return arrays. They only use references to arrays. The same goes for objects (except for Strings, which are passed by value).
In Java, Objects are only accessed by reference. Just return the Array object.

Java N-Dimensional Arrays

I need to be able to have an n-dimensional field where n is based on an input to the constructor. But I'm not even sure if that's possible. Is it?
Quick solution: you could approximate it with a non-generic ArrayList of ArrayList of ... going as deep as you need to. However, this may get awkward to use pretty fast.
An alternative requiring more work could be to implement your own type using an underlying flat array representation where you calculate the indexing internally, and providing accessor methods with vararg parameters. I am not sure if it is fully workable, but may be worth a try...
Rough example (not tested, no overflow checking, error handling etc. but hopefully communicates the basic idea):
class NDimensionalArray {
private Object[] array; // internal representation of the N-dimensional array
private int[] dimensions; // dimensions of the array
private int[] multipliers; // used to calculate the index in the internal array
NDimensionalArray(int... dimensions) {
int arraySize = 1;
multipliers = new int[dimensions.length];
for (int idx = dimensions.length - 1; idx >= 0; idx--) {
multipliers[idx] = arraySize;
arraySize *= dimensions[idx];
}
array = new Object[arraySize];
this.dimensions = dimensions;
}
...
public Object get(int... indices) {
assert indices.length == dimensions.length;
int internalIndex = 0;
for (int idx = 0; idx < indices.length; idx++) {
internalIndex += indices[idx] * multipliers[idx];
}
return array[internalIndex];
}
...
}
Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array also contains another newInstance method to create multi-dimensional arrays. For example:
int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings
Since the number of dimensions is not known until runtime, you can only handle the array as an Object and you must use the get and set methods of the Array class to manipulate the elements of the array.
Try this:
https://github.com/adamierymenko/hyperdrive

Categories