Page 1 of 1
n++ and n[0]++
Posted: Wed May 03, 2023 12:31 pm
by hin1129
Code: Select all
public class TestClass {
public static void main(String args[ ] ) {
int i = 1;
int[] iArr = {1};
incr(i) ;
incr(iArr) ;
System.out.println( "i = " + i + " iArr[0] = " + iArr [ 0 ] ) ;
}
public static void incr(int n ) { n++ ; }
public static void incr(int[ ] n ) { n [0]++ ; }
}
why the answer is 1 and 2?
why int i is unchanged but int[] iArr is changed?
iArr [0] should have a default value of 0, how did it get to 2?
is there anything to do with the static keyword in the methods?
Re: n++ and n[0]++
Posted: Thu May 04, 2023 1:33 am
by admin
Have you read about how method parameters are passed? Have you read about pass by value / pass by reference concept? Once you go through that, it will be clear to you.
Which book are you following?
Re: n++ and n[0]++
Posted: Thu May 04, 2023 8:45 am
by hin1129
OCFA Java Foundations Exam Fundamentals 1Z0-811: Study guide for Oracle Certified Foundations Associate, Java Certification (Kindle Edition)
which topic/page should i go over for this question and the Static and non-static questions?
Re: n++ and n[0]++
Posted: Thu May 04, 2023 9:30 am
by admin
You may go through section 11.3 "Passing object references and primitive values into methods".