java


Could anyone explain how its work? [duplicate]


I'm trying to understand the following Java exercise. Even running the debugger I don't understand the details of the second and third printout:
1, 2, 3, 4
1, 2, 4, 4
1, 2, 4, 8
I understand that the first print is the array as it is, second line prints [2] element of the array and third line [3] element. Here is the code:
public class TR1
{
public static void main(String[] args)
{
int[] v = {1, 2, 3, 4 };
print(v);
x(v, v[2] - 1);
print(v);
x(v, v[3] - 1);
print(v);
}
public static void x(int array[], int y)
{
array[y] = array[y - 1] * 2;
}
public static void print(int array[])
{
System.out.print(array[0]);
for (int i = 1; i < array.length; i++)
System.out.print(", " + array[i]);
System.out.println();
}
}
Let's see what this method does :
public static void x(int array[], int y)
{
array[y] = array[y - 1] * 2;
}
It takes the value at index y-1, multiplies it by 2, then assigns this result to the index y .
Starting array : {1,2,3,4}
The call with v[2] - 1 takes the value at index 2 (which is 3), and substracts 1, so we have y = 2.
From what we said before, the method takes the value at index 1 (y-1) which is 2, multiplies it by 2 so we get 4, and assigns that to the index 2 (y) .
Current array : {1,2,4,4}
The call with v[3] - 1 takes the value at index 3 (which is 4), and substracts 1, so we have y = 3.
From what we said before, the method takes the value at index 2 (y-1) which is 4, multiplies it by 2 so we get 8, and assigns that to the index 3 (y) .
Current array : {1,2,4,8}
Lets briefly walk you through the first things that happen. You start with this array:
1 2 3 4
No surprise when printing that.
Then you run:
x(v, v[2] -1 ) ... evaluates to
x(v, 3 - 1) ... evaluates to
x(v, 2)
Which changes the array based on:
array[y] = array[y - 1] * 2;
Lets insert y as 2 (see above):
array[2] = array[1] * 2;
array[2] = 2 * 2;
leading to:
1, 2, 4, 4
So, the real answer is: you don't even need a debugger. A piece of paper, a pen and a bit of thinking is even more efficient to uncover the "secrets" here.
print always prints the entire array. x and y are making changes to the array in between.
Keep in mind that v[x] is just an integer. For example, v[2] is initialy just 3, so v[2] - 1 = 2. Hence it modifies v[2] between the first and second call to print.

Related Links

JDBC Clob and NClob
java.lang.NullPointerException in signup with google throws null
NumberOpsDriver.java:35: error: no suitable method found for add(int)
comparing the content of two HashMaps with set<> value
Not able to load Application Context in Spring Boot app
How to use the apache HttpClient without manager?
How to create JDBC Connection pool? [closed]
Spring Scheduled tasks Doesnt kick with #ComponentScan
How Do I clean up a json string from multiple escape characters?
Use flexmark-java to clean markdown
java.lang.NullPointerException: Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.a' on a null object reference [duplicate]
How to differentiate between two lines in an image [closed]
Accessing a secure EJB as anonymous user on Wildfly 9
NumberFormatException while converting large textual numbers to BigInteger
Tower Of Hanoi game input not working as intended
calling AsyncTask inside if/else statement?- android

Categories

HOME
osgi
variables
bluetooth
atom-editor
pycharm
rubygems
baqend
python-unittest
floating-action-button
imacros
saxon
pythonanywhere
text-rendering
django-cms
ml
abi
restful-authentication
claims-based-identity
numerical-methods
microsoft-sync-framework
javacv
info.plist
msys2
facebook-apps
libuv
libssl
delicious-api
nameservers
.net-4.0
pdb
phpfreechat
serve
android-browser
tasker
mesos-chronos
firebase-admin
midl
turbogears
http-redirect
websphere-mq-fte
angular2-meteor
btrace
scorm
babel-core
wso2carbon
network-flow
komodoedit
aurelia-validation
epson
bind9
synchronous
root-framework
ableton-live
deadbolt-2
rotativa
bonobo
url-masking
plottable.js
gridview-sorting
simplewebrtc
blackberry-10
ubuntu-10.04
qgraphicsview
pickadate
ipconfig
design-by-contract
pyke
intel-fortran
sdhc
ruby-2.2
jqgrid-formatter
wyam
ionic
php-ci
iiviewdeckcontroller
apache-commons-net
nsmutabledictionary
sorl-thumbnail
ng-animate
qpainter
preferences
elliptic-curve
seaside
transcoding
java.nio.file
page-layout
dir
hungarian-algorithm
pushbackinputstream
plasma
dice
ocx
getmessage
asyncfileupload
.nettiers
icanhaz.js
preference
nsviewanimation
vc90
iweb
swing-app-framework
scripting-languages
post-build

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App