Java is giving me different results for the same process - java

what i mainly want to know is :
in the line public static void val(int[] x) what does the (int[] x) do?
Also: why am i getting the final added up values when i ask
for(int y:i){
System.out.println(y);
}
but not for:
int y=2+i2;
System.out.println(y);
why isnt the vale() method not converting the "i2" value to "x" immediately and then continuing the compilation by using the "x" value for subsequent 'i2" calculations....sorry if my question is vague....i just dont know how else to put it....thanks
complete code:
public static void main(String[] args) {
int[] i = { 25, 22 };
int i2 = 41;
val(i);
for (int y : i) {
System.out.println(y);
}
vale(i2);
int y = 2 + i2;
System.out.println(y);
}
public static void val(int[] x) {
for (int c = 0; c < x.length; c++) {
x[c] *= 2;
}
}
public static void vale(int x) {
x += 23;
}

Java always passes arguments by value, never by reference (not only primitive types, reference types as well). This is why your vale(int x) method doesn't work.
Have a look at this article, it explains everything: http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html

I think you need to read about pass by value and reference in Java. Regarding your questions, both val(i) & vale(i2) are technically pass by value. Since array is an object type, its reference is passed to the method in case of val(i) and hence you could see the modifications when you print the reference. However, vale(i2) takes a primitive integer type as parameter and thus the modifications within the method doesn't affect the original value. To understand this better you can modify your val(int[] x) method as follows:
public static void val(int[] x) {
x = new int[] {35, 57};
for (int c = 0; c < x.length; c++) {
x[c] *= 2;
}
}
I just added x = new int[] {35, 57}; which would make the value of x point to a different reference and not affect the original value. Hope this clarifies!

Your method val(int[] x) accomplishes absolutely nothing in this code. It returns void(nothing) to the main() function and the operations you preform inside val() with your array x are done on a copy of x...
possible fix:
public static int[] val(int[] x){
int[] newarr = new int[x.length];
for (int c=0; c<x.length;c++){
newarr[c] = x[c]*2;
}
return newarr;
}
in main:
int[] i={25,22};
i = val(i); // creates an array with every element doubled and assigns it to i
same story with vale() !

Related

Why this below code is not returning the desired output ? it should return 1,3,2,2,0,0,0 while its returning same array

When I run the below code it's returning same array as output. Can anyone tell me where I am wrong?
public class MoveZeroToend {
public static void main(String[] args) {
int[] arr = { 1, 3, 0, 2, 0, 2, 0 };
Move0Toend(arr);
}
static void Move0Toend(int[] arr) { // Code to move zeroes to end
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
swap(arr[i], arr[count]);
count++;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); // Print the array
}
}
static void swap(int a, int b) { // To swap
a = a + b;
b = a - b;
a = a - b;
}
}
on your swap method, you are not swapping the actual values of the objects you've passed, you are swapping between the values passed to the method but there is no result returned so nothing happens. you need to either do the swap on the actual objects - not in a method, or use another way for this. I would recommend googling "pass by value" and "pass by reference". I would also recommend adding a unit test or at least debug the program so you can validate your code is doing what you want.
Your swap method doesn't return any values, nor does it change the values in the reference of the objects passed. To fix this you can either return two values from your swap method (a and b) or you could do it not in a method, that way it would directly affect the objects.
Just for a little more explanation, the variables a and b in your swap method are local to the swap method, changing these would not affect any other variables, even if they were also named the same, and as your method is a void it can't return anything.
Hope this helps :)
Your swap() method isn't performing any operation on your array, you are just passing two values a and b and swapping them but no operation is being performed on your array.
Instead of passing these two values to your swap() method you can directly swap them inside your for loop as below:
for(int i=0;i<arr.length;i++){
if(arr[i]!=0){
int temp = arr[i];
arr[i] = arr[count];
arr[count] = temp;
count++;
}
}

Accessing a returned list in the main method

So basically I have a static class that returns a newly made list and what I need to do is print each element of said list by using it in the main method. I get the error that cant solve blablabla to a variable which I guess means that the list I am trying to use is not usable yet. Thought it might be a good idea to add the last lines here as well for a visual.
The error code given is "b cannot be resolved to a variable".
public class A5P5 {
public static int[] teine(int arv, int alum, int ylem) {
int [] b = new int[arv];
for (int i = 0; i < arv; i++) {
double k = Math.random() * (ylem-alum) + alum;
int l = (int)k;
b[i] = l;
}
return b;
}
public static void main(String[] args) {
int [] a = new int[10];
for (int i = 0; i < 10; i++) {
double x = Math.random() * (110-50) + 50;
int y = (int)x;
a[i] = y;
}
for (int elem: a) {
System.out.println(elem);
}
System.out.println("----------------------------------------------------");
teine(20, 20, 40);
for (int elem: b) {
System.out.println(elem);
}
}
}
Try:
...<delete teine(20, 20, 40);>...
for (int elem: teine(20, 20, 40)) {...
you have to assign the value returned from the method above so an alternative would be:
int[] b = teine(20, 20, 40);
for (int elem: b) {...
you cannot acces b because it is a local var in your teine method, so that won't work in main:
teine(20, 20, 40);
for (int elem: b) {
System.out.println(elem);
}
but since teine returns your b anyway you can just do this:
for (int elem: teine(20, 20, 40)) {
System.out.println(elem);
}
My bet is that the compilation error is about this line:
for (int elem: b) {
Hints:
Which b do you think that refers to?
The b declared in your tiene method is out of scope at that point. Specifically, the variable b goes out of scope when the call to tiene finishes.
To start that isn't a List it's an Array. They are quite different.
Now about your issue. You are making a new int array in your main but not populating it with anything so (according to the specs) each element has a value of 0.
You need to actually call and assign your array. int[] a = teine(arv, alum, ylem) would be a good place to start moving forward with your program.
I would also agree with #Brian Roach that you may need to brush up on your basics. Also try using more descriptive names for your variables. It will help both people reading your code and yourself when you come back to the code down the line and need to debug or modify it.

Method returning null is manipulating a final int array

Can anybody please explain to me why a method returning null is manipulating a final int [] ?
final int [] vals = {2,3};
int [] vals2 = multiply(vals);
for(int i : vals) System.out.println(i);
int [] multiply(int [] in){
for(int i = 0; i < in.length;i++){
in[i] *= 2;
}
return null;
}
Ouput:
4
6
Edit:
I have noticed this behavior only in methods returning an array. The same method returning an int doesn't change the original integers value...
Full code:
public class Main{
public Main(){
int [] myList = {56, 32, 200};
int [] newList = myList;
bubble_sort(newList);
for(int i : myList){ System.out.println(i); }
System.out.println();
for(int i : newList){ System.out.println(i); }
}
public int [] bubble_sort(int a[]){
int n = a.length;
int [] s = a;
for (int i = 0; i < n ; i++){
for (int j = n - 1; j >= (i+1); j--){
if (s[j - 1] > s[j]){
int t = s[j - 1];
s[j - 1] = s[j];
s[j] = t;
}
}
}
return null;
// return s;
}
public static void main(String [] args){
new Main();
}
}
Edit:
Following code produces following output as expected: 2, 4
int vals = 2;
int vals2 = multiply(vals);
System.out.println(vals);
System.out.println(vals2);
int multiply(int in){ return in*2; }
So my question is, why does a method returning an int does not change the input value, but a method returning an array does change the inputs original value(s).
Here, final means that the vals reference cannot be changed from referring to its initial array. But it says nothing about whether the contents of the array can be changed. As you see, they can be changed.
The final keyword will only stop you from assigning another array to vals, e.g.
vals = anotherArray; // Disallowed; final
A solitary return null; is useless. The multiply method should have been declared as void, returning nothing.
Arrays are mutable in java
the "final" keyword only stops you from reassigning, not from changing the actual value. It literally means that if you were to write "in = someOtherArray" somewhere in your code, you'd get a compile error.
This makes it sound like the "final" keyword is useless, but it works as expected for primitive types, or any immutable object.
If I have: int i = 0; I cannot change the 0 without reassigning a value to i.
Though you see the method returning null, the array contents are still getting modified within the multiply() method.
multiply(vals);
for(int i : vals) System.out.println(i);
Note that you are printing vals which has already been modified by the multiply method. (Java Pass by value)
So when i literally wanna use this method int [] newList = bubble_sort(myList); i mustn't modify the input value but saving each item into a new array int [] s = new int[a.length]; for (int i = 0; i < n ; i++)s[i] = a[i]; and then i can continue to sort the new array and return it. Then the original array(myList) won't be affected.

Initializing a three dimensional array of arraylist in Java

I have a multidimentional array, as:
private static ArrayList [] [] pVTable = new ArrayList [35] [12];
My first try to initialize it was:
for (ArrayList[] x : pVTable) {
for (ArrayList y : x) {
y = new ArrayList<TableValue>();
}
}
which didn't work.
I ended up doing it more manually, as in:
for ( int i = 0; i < pVTable.length; i++) {
for ( int j = 0; j < pVTable[0].length; j++) {
pVTable [i] [j] = new ArrayList<TableValue>();
}
}
which works fine.
Although I have a solution, I was wondering why the first (more elegant) piece of code doesn't do the same job?
In the first snippet, if we strip away the syntactic sugar of the foreach operator (:), the code translates to:
for (int xIndex = 0; xIndex < pVTable.length; xIndex++) {
ArrayList[] x = pVTable[xIndex];
for (int yIndex = 0; yIndex < x.length; yIndex++) {
ArrayList y = x[yIndex];
y = new ArrayList<TableValue>();
}
}
As you can see, nothing is ever assigned to the actual array – only to the temporary y variable.
In the first example your code although modifies y does not change x.
You are mixing ArrayList (part of collections api) with Arrays, which is rather confusing (for me anyway)
I would suggest something like this instead :
List<Point> myShape = new ArrayList<Point>;
Where point contains two ints representing X and Y.
The scope of the first is incorrect. y is just a placeholder variable. Changing that doesn't change the underlying object, just the object that y refers to. You can see the same problem in the following code snippet:
public static int x = 2;
public static void foo(int y) {
y = 3;//does nothing outside of foo
}
public static void main(String[] args) {
System.out.println(x);//prints 2
foo(x);
System.out.println(x);//prints 2, x hasn't changed.
}

Returning an Array

I am new to programming and Java and trying to write a program which takes two arrays as input and reports back their sum. I want to do this by creating a class which takes two arrays as constructor inputs and then creating a method that adds them together and a method which prints out this new sum array.
Here is my class:
public class test1 {
int [] a;
int [] b;
int [] final23;
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[0]);
}
}
}
Here is my main class:
public class main1 {
public static void main(String[] args)
{
int l[] = {4,7,2};
int k[] = {4,6,2};
test1 X = new test1(k,l);
X.sum(k,l);
X.print();
}
}
I keep getting an error when I run this through:
Exception in thread "main" java.lang.NullPointerException
at test2.sum(test2.java:17)
at main1.main(main1.java:8)
I guess what I really want is for my sum method to take a test1 object as input. However, I don't know how to do this.
Your variable final23 is never initialized.
In java you have to initialize an array before using it. Either you do it during the declaration (like you did with k and l) or you have to do it later with a new arrayType[arraySize];
Here are the way an array can be declared/initialized.
int[] iArray = {1, 2, 3}; //Declaration, Initialization, set values
int[] iArray; //Declaration
iArray = new int[3]; //Initialization
iArray[0] = 1; //Set value
int[] iArray; //Declaration
iArray = new Array[3]{1, 2, 3}; // Initialization and set values
You can of course for the two last sample put the initialization on the same line that the declaration.
Try this (cleaned) code :
public class test1 {
int[] final23;
public int[] sum(int[] x, int[] y) {
final23 = new int[Math.min(x.length, y.length)];
for (int i = 0; i < final23.length; i++) {
final23[i] = x[i] + y[i];
}
return final23;
}
public void print() {
for (int aFinal23 : final23) {
System.out.println(aFinal23);
}
}
public static void main(String[] args) {
int l[] = {4, 7, 2};
int k[] = {4, 6, 2};
test1 x = new test1();
x.sum(k, l);
x.print();
}
}
Resources :
Oracle.com - Arrays
JLS - Array Initializers
JLS - Array Creation Expressions
I'm going to take a long shot here
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
As a side comment, I'm guessing that you want to add all of the elements of the vector, not just the first. Change your for-loop body to:
final23 [i]=x[i] + y[i] ;
What's final23? Where is it created?
Try adding this to your constructor
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
this.final23 = new int[Math.min(a.length, b.length)];
}
Now final23 is defined and created, and you can use it in your class.
If you supply test1 with arrays in the ctor, you don't need them in the sum method, just use the ones you have in the class already:
public int [] sum()
{
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [i]=a[i] + b[i] ;
}
return final23;
}
You also had an error in the sumation, you didn't use the iteration variable, you also need to initialize final23 in the ctor.
You have to initialize final23 array before putting elements in it (on line 17).
**final23 = new int[Math.min(x.length, y.length)];**
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
I see a couple of things to point out here.
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
First of all, remember that each test1 object - that is, each instance of your test1 class - has variables named a and b. I'm guessing that in the constructor, you want to take the arrays x and y which were passed as parameters and store them into a and b of the object. To do that, all you have to do is write
a = x;
b = y;
You don't have to write int[] again, not when you just want to access an existing array-type variable. You only write that when you're creating a new array-type variable. In this case, when Java sees that you've written int[] a in the constructor, it thinks you want to create yet another array-type variable named a, separate from the one in the test instance, and that's the one that gets set equal to x. The thing is, that local variable gets lost at the end of the constructor. So you're left with a test1 instance that has variables a and b that still refer to nothing, i.e. they're null.
By the way, since you're going to be using the array final23 later on, you should initialize it. Right now, it refers to null because you never set it to equal anything else. You'll need to create a new array and store it in that variable in order to be able to use it later on. So put this line in your constructor:
final23 = new int[Math.min(a.length, b.length)];
That creates the new array with a length equal to the shorter of the two arrays passed in.
Moving on:
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
In this bit of code, you have the same issue as in the constructor: you create two new array-type variables a and b that get used instead of the ones in the test1 object. I don't think that's what you meant to do. So I'd say get rid of those last two lines entirely.
There's another problem, though: if you think about it, you still have two arrays stored in the test1 object. Assuming you've fixed your constructor, those are the same two arrays that were passed to the constructor. And now you're getting two new arrays under the names x and y. So you have four arrays total. Which ones did you want to sum up? I'm guessing that you meant to sum the two arrays that were passed to the constructor. In that case, your sum method doesn't need to - and shouldn't - accept more arrays as parameters. Get rid of the parameters x and y, so your sum method just looks like
public int [] sum()
{
Now you have to change the rest of that method to use a and b, starting with the for loop. Change its opening line to this:
for (int i = 0; i < Math.min(a.length, b.length); i++)
{
I notice you were wondering how to get your sum method to take an instance of test1. Well, in a way it actually does. There's a special hidden parameter passed to all methods (except static ones) that contains the object the method was called on - in fact, using your main program as an example you could kind of think of X.sum(k,l); as actually calling test1.sum(X,k,l);, where X is the special hidden parameter. You can access it inside the method using the name this (so you could write this.a instead of just a), but Java is generally smart enough to do that for you.
In the body of the for loop, you have another problem. What you want to do is add up corresponding elements of the arrays, i.e. a[0] + b[0] goes into final23[0], a[1] + b[1] goes into final23[1], and so on. But inside the for loop, you only ever add up element 0 of each array. You need to use the loop index variable i, because that runs through all the values from 0 to the length of the shorter array minus 1.
final23 [i] = a[i] + b[i];
}
return final23;
}
So the first time the loop runs, i will be 0, and you'll set final23[0] = a[0] + b[0]. The next time it runs, i will be 1, and you'll set final23[1] = a[1] + b[1]. And so on.
The same problem occurs in your print method. Each time through the loop, you always print out final23[0], when you really should be printing out final23[i] because i changes each time you go through the loop. Change it to
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[i]);
}
}
At this point your program should be working, I think, but there are still some improvements you could make to its design. For one thing, every time you create an object of test1, you know you're immediately going to call sum on it. So why not just put the summing-up code right into the constructor? That way you know that the sum will be computed right when you create the object, and you don't have to call sum explicitly.
Of course, once you do that, you'll have no way to access the array final23 from your main class - except that if you want to print it, you can call the print method. But what if you want to write a main class that, say, adds up two arrays, and then adds the result to a third array? It'd be nice to have a way to get the result from the test1 instance. So you can add an accessor method, possibly named getFinal23, that just returns the sum array final23.
In practice, this operation of adding two arrays would probably be implemented as a static method. So if you want, you could try starting over, and writing it as a static method. (Remember that a static method is one which doesn't receive a special hidden parameter) Inside the static method, you'd have to create the final23 array, go through the loop to compute the sums, and then return the array you created. You'll need to enclose the static method in a class, of course, but that class doesn't have to have a constructor since you never really use it for anything. It'd look something like this:
public class SumClass { // pun intended ;-)
public static int[] sum(int[] x, int[] y) {
// you fill in this part
}
}

Categories