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

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)

Related

Java Array with the same name as a class name

I really can't find any information about it that's why I'm asking here.
I'm trying to figure out what is it type of Array if it has same name as a class... like:
public class ArrayOne {
int SomeInt;
ArrayOne [] arr;
public ArrayOne(SomeInt){
arr=new ArrayOne[1];
}
}
Maybe someone know where can I read about it. Thanks a lot
If you declare an array like this:
int[] myIntArray = new int[3];
you have an array of int (remember that int in java is not an object)
So if you write:
ArrayOne[] arr;
You will have an array of object from class ArrayOne.
If you are still in doubt, you can check an array type like this:
Class ofArray = o.getClass().getComponentType();
take a look here : http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getComponentType--
public Class getComponentType()
Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.
That would be an array of that classes objects.
Your arr variable will be of Array type, which contains objects of ArrayOne type.
If the question is around naming, then your array is named arr but not after the class which it is typed with.

adding size to private array - java

I'm very new to Java programming and wanted to try my hand at a little bit outside of my classes. I've created a class that will manipulate arrays, so I set up a private array with no size allocated to it. In a public constructor, how do I set the size of this array?
public ClassName()
{
arr = new int[10];
}
Remember that the Constructor is the method called when an object is instantiated. The Constructor must be a method with no return type and the same name as the class. You could even take in parameters if you'd like to(say a size variable), then create a new array based on the size.
For instance, you could do this:
public ClassName(int size)
{
arr = new int[size];
}
Now when in your tester class, you could create a new object using that constructor.
ClassName c = new ClassName(5);
Which creates a new object with an array of size 5 as a class variable. Hope this helped!
Edit: I should add; if you do not specify a constructor, Java will do it for you, but it will do nothing.
Just like in must of the languages.
example:
anArray = new int[10]; //10 - array size, int is the array type
read about JAVA Arrays

Theoretical: about Java recognizing an Array name and its values

I had to make a program which was able to print symbols based off an array with numbers, with the numbers corresponding to the amount of symbols to print.
I got this to work; here is the code:
class printChart {
int[] values;
void barChart(int[] values){
for (int i=0;i<values.length;i++){
int number = values[i];
for (int j=0;j<number;j++){
System.out.print("*");
}
System.out.println();
}
}
void demo(){
barChart(new int[] {2,5,0,4,3});
}
public static void main(String[] args){
new printChart().demo();
}
}
My question is as follows: How does Java know that the {2,5,0,4,3} array should be assigned to the variable values? I'm assuming it's because I set void barChart to pass along int[] values, but I'd like to know more about the inner workings and what's going on exactly.
In Java, everything is pass-by-value and it is also important to know what the value is.
This method
void demo(){
barChart(new int[] {2,5,0,4,3});
}
Do the same as this one
void demo(){
int[] arr = new int[] {2,5,0,4,3};
barChart(arr);
}
In the first one, there is created new array with 2,5,0,4,3 values and its reference is copied to parameter values in barChart method.
In second one, there is created new array with 2,5,0,4,3 values and its reference is copied to variable arr. Then the value of arr (which is reference to array) is copied to parameter values in barChart method.
And this is how it works and why barChart method knows the values.
Also good point by Ɓukasz, the second line does not do anything in your program, therefore you can change this :
class printChart {
int[] values;
void barChart(int[] values){
to this
class printChart {
void barChart(int[] values){
I'm not so sure what your question is, but let me tell you bit what you've done.
You've implemented a method(function) named void barChart(int[] value)
To run this method you must need to pass a one dimensional Array of Integer values to it.
Now comes the interesting part.
You've created a class Variable int[] values; in code line 2.
Also you've have created the lokal variable "value" in the method void barChart(int[] value).
What you've done is called overshadowing. The method "barChart()" only uses the lokal value which is passed to it when it is called.
You never used the class variable once, hence you could delete it.
Now if you want to use the class variable you could either:
a) Change the name of the variable (class or local)
b) In the method "barChart" write a this.value instead of just value. This will ensure that you are using the class variable and not the local one.

Reading from instantiated Java array throwing NullPointerException instead of returning 0

I've made the following class just to make clear what I don't understand, it's not actually going to be used for anything.
public class A
{
private int[] items;
public A()
{
int[] items = new int[7];
}
public int first()
{
return items[0];
}
}
So when we create a new instance of A, the array "items" will become an array with a capacity of 7.
When calling the first() method, it asks for the value of the int-variable in the first position of the array. Since we haven't given this int an actual value, according to http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html the default value that will be stored is "0".
Yet when I actually call the method, instead of returning 0, I receive a nullpointerexception. Why is this?
[Edit]
Can't reply to the comments on my own question for some reason...
But thanks for your help!
If someone else has a similar problem and it's still not quite clear what went wrong:
I've declared but not initialized a variable "items" which can hold an array of integers.
Now, in the constructor, instead of initializing my original variable I've just declared a new variable "items" (which only exists in the constructor and then disappears) and then initialized it to be an array for 7 integers.
Now when calling the "first" method it tries to find what is on the first location of my original "items" array, since that is the only "items" array that currently exists. But I haven't initialized that array, which means there is no array, only a variable. Because of that a nullpointerexception is returned.
This
public A()
{
int[] items = new int[7];
}
should be
public A()
{
this.items = new int[7];
}
otherwise you're declaring and initializing a different variable with the same name as your instance field.
Change
int[] items = new int[7];
as
this.items = new int[7];

"Final" in java and copying 2D arrays

I am having a little trouble understanding the concept of final in Java.
I have a class that follows:
public class MyClass
{
private int[][] myArray; // intended to be changed
private final int[][] MYARRAY_ORIGINAL; // intended to be unchangable
public MyClass(int[][] array)
{
myArray = array;
MYARRAY_ORIGINAL = array;
}
}
I was under the understanding that final would make MYARRAY_ORIGINAL read only. But I have tried editing myArray, and it edits MYARRAY_ORIGINAL as well. My question is, in this context, what exactly does final do? And for extra credit, how can I copy the array passed through the constructor into MYARRAY_ORIGINAL so that I can have 2 arrays, one to edit, and one that will remain preserved?
Your final MYARRAY_ORIGINAL is indeed read only: you can't assign a new value to the MYARRAY_ORIGINAL reference in other side than class constructor or attribute declaration:
public void someMethod() {
//it won't compile
MYARRAY_ORIGINAL = new int[X][];
}
The values inside the array are not final. Those values can change anytime in the code.
public void anotherMethod() {
MYARRAY_ORIGINAL[0][0] = 25;
//later in the code...
MYARRAY_ORIGINAL[0][0] = 30; //it works!
}
If you indeed need a List of final elements, in other words, a List whose elements can't be modified, you can use Collections.unmodifiableList:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
The last piece of code was taken from here: Immutable array in Java
In case of Objects, final makes reference can't be changed, but object state can be changed.
That is the reason why you are able to change values of final MYARRAY_ORIGINAL
MYARRAY_ORIGINAL is indeed read only variable. Your array reference can not be assigned a new value nor for their length of the arrays can be changed. A final variables initialization can be deferred till the constructors is called. If one tries to modify the reference of the final variable, compiler will throw an error message. But what is possible is, one can edit the elements of the MYARRAY_ORIGINAL and of the myArray i.e one can change the state of the object assigned to a final variable. For example
Class A {
final int[] array;
public A() {
array = new int[10] // deferred initialization of a final variable
array[0] = 10;
}
public void method() {
array[0] = 3; // it is allowed
array = new int[20] // not allowed and compiler will throw an error
}
}
To understand more on final please take a look at Java Language Specification on final variable.
Final does not mean 'read-only' per se, but more so "safe publication' for other threads than the one to which it is defined. Another aim of 'final' is that it ensures the latest object available in a multi-thread environment.
Secondly, if you define something as "final", for example:
private final int[][] MYARRAY_ORIGINAL;
The reference is "final", but not the object itself. A much better way to understand it would be this:
public static final List myList = new ArrayList();
Now I can access myList from any other threads - I can modify it (add to it); but I cannot
(a) Declare it again - myList = new ArrayList();
(b) Assign it another list - myList = anotherList;
The context for final I would see best, in a multiple-thread scenario.
Bonus: to answer your question, you cannot make a 'readonly' array, you will have to manage that yourself (as final, only maintains 'read-only' to reference not object)
You can use the method System.arraycopy to make a copy of the array as follows -
int[][] source = {{1,2},{3,4}};
int[][] copy = new int[source.length][];
System.arraycopy(source, 0, copy, 0, source.length);
Also, you some problem with your code regarding what you are trying to do. If you look at the constructor
public MyClass(int[][] array) { //something else passes the array
myArray = array;
MYARRAY_ORIGINAL = array; // you are just keeping a reference to it can be modified from outside
}
If you really want nobody to modify the values in that array MYARRAY_ORIGINAL, you should make a copy of the source array that comes comes from outside.
public MyClass(int[][] array) {
myArray = array; //make a copy here also if you don't want to edit the argument array
MYARRAY_ORIGINAL = new int[array.length][];
System.arraycopy(array, 0, MYARRAY_ORIGINAL, 0, array.length);
}
Now you shouldn't have to worry about the array's being modified from outside.

Categories