I have been given a piece of code (the class QuestionTwo).
I am asked to state the values of a, b, and c after method mQ2 is invoked on a newly created object of class Q2.
My main.java file
package openuniversity;
public class Main
{
public static void main(String[] args)
{
QuestionTwo qt = new QuestionTwo();
qt.mQ2();
}
}
My QuestionTwo.java class file:
package openuniversity;
public class QuestionTwo
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
}
a++;
}
}
I arrived at:
a: 1
b: 1
c: 3
Note I can also select 'undefined' as an answer?
So would it be 1, 1, undefined as c does not exist outside of the codeblock?
The question:
Study the following code and then select the options from the drop-down lists below that are correct about the values of a, b and c after the method mQ2 is invoked once on a newly created object of class Q2. Note that the answers you choose for a, b and c may or may not be different from each other.
public class Q2
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
System.out.println("c: " + c); //correct place?
}
a++;
}
System.out.println("a: " + a + "b: " + b); // correct place?
}
Since this is homework, I'll restrict my answer to a couple of pointers.
You can verify your solution by printing out the variables after calling mQ2() (hint: you could use System.println() for that).
This is either a trick question or is partially ill-defined (hint: think about which a, b and especially c you're being asked about).
I'd suggest you first print out all the values using System.out.println() after calling mQ2, then step through the code in your mind to try to work out why the values are what they are. Remember that any variable declared is only visible within the scope ({...}s for simplicity), but these variables can have the same name as other variables so they might look like the same even if they're not.
I'd like to particularly point out that c does not exist outside that method.
Related
So this is basically my code
abstract class B
{
int x = 3;
B()
{
x+=2;
System.out.print("-x" + x + "\n"); // print -x5
x++; // 5 then 6
}
abstract int calculate();
abstract int calculate(int i);
}
class A extends B
{
int x = 2;
A()
{
System.out.print("-x" + calculate(2)+"\n");
}
#Override
int calculate()
{
return x;
}
#Override
int calculate(int i)
{
return(calculate()+i);
}
}
public class Test2 extends A
{
Test2()
{
x+=3;
}
#Override
int calculate()
{
return x + 6;
}
public static void main(String[] args) {
Test2 sub = new Test2();
System.out.print("-x" + sub.calculate()+"\n");
}
}
My problem here is after digging up about variable hiding I learned that if a instance variable is of the same name in both parent class and child class then the childclass hides the instance variable of the parent class. Also I have the prior knowledge that variables cannot be overridden when child class inherits parent class.
So now coming to the problem, in the code when A extends to B, why does the print statement inside constructor A() gives a value -x10? shouldn't it be -x8?? I dont understand how the variable is being changed here. I am new to java so any kind of knowledge will be greatly appreciated. :)
Ok so I have done some debugging and found that the calculate(void) method in class A returns 8. But how is that possible shouldn't it return 6? Please help!
The reason it prints -x10 is because A::calculate(2) calls the Test2::calculate(), which uses A::x to do the calculation.
The sequence of calls that happens is the following:
Test2() {
A()
B() {
B::x = 3
B::x += 2
System.out.print("-x" + x + "\n"); // print -x5
B::x++ // B::x is now 6
}
A::x = 2
System.out.print("-x" + calculate(2)+"\n")
A::calculate(2) {
return(calculate()+2);
Test2::calculate() {
return A::x + 6; // A::x is 2 here, so returns 8
}
} // returns calculate()+2, so returns 10
}
A::x += 3
}
I hope this is just code to test things out, because you should never allow this to happen in real code. You should never allow a method of a subclass to be called from the constructor of a base class, because the subclass is not initialised at that time. The Java compiler does its best to prevent that, but sometimes it does not detect it.
It is returning 8 because:
The line you called System.out.print("-x" + sub.calculate()+"\n"); in class A calls
#Override
int calculate()
{
return x + 6;
}
in class A still, which is incrementing the instance variable int x = 2 in class A . this variable overwrote the one in class B
Hence 2+6 = 8
This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 5 years ago.
I'm learning inheritance in java. While writing small code where I'm learning we cannot access private members of superclass in subclass.
Here is my code:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
When I create a new class in eclipse, am not able to create an object of sublcass B in class A.
class mainclass{
public static void main(String args[]){
B object = new B(); ----error
}
}
}
Error says class B needs to be created.
May I know why is happening ..? Its happening not a problem but I want to solve and understand the logic why it was happened.
Thanks
That's because class B is present inside class A, it needs to be created outside of A, e.g.:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
With this code, class B (and A) will be accessible from all the classes from inside the package. If you want these classes to be accessible from outside the current package then you need to create these classes in separate files and mark them as public.
Here's more on access modifiers for classes.
Upate
If you want to define class B as an inner class in A then you will need the instance of enclosing class (A in our case) to access B, e.g.:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
}
Now, to instantiate B, you need to do the following:
A a = new A();
B b = a.new B();
And of course, same rules as access modifier will apply to inner class instance (except the fact that inner class will be able to access private members of enclosing class),
This is because an instance of class B must relate to an instance of class A. So you must first create an instance of class A, then the instance of class B:
A a = new A();
a.setij(1,2);
B b = a.new B();
b.setij(3,4);
b.sum();
System.out.println(b.b);
(the result is 5 in case you were wondering)
I am new to Java so I need help.
How can I access the variables of the method method1 and compare them with the variable int c? What should I return?
public static void main (String [] args){
int c = 30;
// I want to compare c with a, for example:
if (c > a)
{
System.out.println(c + " is greater than " + a);
}
}
I want to do the above comparison without touching method1()
public double method1(){
int a = 10; int b = 20;
if (a > b)
{
System.out.println(a + " is greater than " + b);
}
else if (a < b)
{
System.out.println(b + " is greater than " + a);
}
//What should I return?
return ????;
}
if you are writing "int c = 30;" directly below main then it becomes global variable.
Global Variable means: "c" can be accessed inside methods(anywhere in same class).
if you are writing "int c = 30;" inside particular method than you cannot access outside that particular method.
Following is example of global variable.
public static void main (String [] args){
int c = 30;
public double method1(){
int a = 10;
if (a > c)
{
System.out.println(a + " is greater than " + c);
return a;
}
else if (a < c)
{
System.out.println(c + " is greater than " + a);
return b;
}
}
I hope it works for you.
How can I access the variables of the method "method1" [...] without touching the method1()?
You can't.
Local variables in a method are only accessible inside that method. And if that method doesn't give you a way to see them, then without modifying the method, you can't see them.
Since a is always 10, you could do if (c > 10) instead.
import java.util.*;
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int kvadratek, a, b;
a = sc.nextInt();
b = sc.nextInt();
--a;
--b;
if(a>b) {
kvadratek=b;
b=a;
a=kvadratek;
System.out.println((a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b));
}
else {
System.out.println(a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
}
}
i am new to java coding and i have a question if i can write this part
kvadratek=b;
b=a;
a=kvadratek;
differently so that it will give me the same result as the else part. Is it possible to do it with if, while sentences? I actually don't need the else part of the code if I insert
kvadratek=b;
b=a;
a=kvadratek;
but is there a way to change that part?
First thing, to avoid repeating code, is to extract it to a method:
private static int compute(int a, int b) {
return (a*(a+1)*(2*a+1)/6-((a+1)*a/2)*(a+b)+(a+1)*a*b);
}
Now you want b to be the biggest of the two numbers, and a to be the other one. Instead of swapping them, you could use Math.max and Math.min:
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
System.out.println(compute(Math.min(a, b), Math.max(a, b));
You can use this:
int k = Math.max(a, b)
a = Math.min(a, b);
b = k
After this piece of code, b will be the greater between the original a and b, while a will be the smaller, thus removing the need for the if/else.
Possible Duplicate : Is Java “pass-by-reference” or “pass-by-value”?
i am trying to do initialization of an array in this way -
class Main {
public static void main(String[] args) {
int n = 4;
int[] s = null;
int[] f = null;
init(n, s, f);
System.out.println(s.length);
}
public static void init(int n, int[] s, int[] f) {
s = new int[n];
f = new int[n];
}
}
but i am getting NullPointerException for the s.length. so this clear passing the parameter to another method is pass by value. therefor objects are not initialize.
but when i do swap in to value in a different method then this is working. like -
class Main {
public static void main(String[] args) {
int n = 4;
int[] s = new int[n];
int[] f = new int[n];
s[0] = 10;
f[0] = 20;
System.out.println(s[0] + " " + f[0]);
swap(s, f);
System.out.println(s[0] + " " + f[0]);
}
public static void swap(int[] s, int[] f) {
int t = s[0];
s[0] = f[0];
f[0] = t;
}
}
on the other hand this isn't swap values.
class Main {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
swap(a , b);
System.out.println(a + " " + b);
}
public static void swap(Integer a, Integer b) {
int t = a;
a = b;
b = t;
}
}
therefor i need some explanation whether java “pass-by-reference” or “pass-by-value”? this explanation could help me to understand why it is not possible to create object in another method.
sorry for my bad English. thanks in advance.
This won't work because Java has pass by value, not pass by reference.
When you declare
int[] s = null;
then you have a (null) reference to an int[]. But when you pass s to another method, what happens is that a new variable (let's call it x) is created, and the reference s is copied into it. Any changes to what x references will also change what s references, because they're the same thing; but changes to x itself won't change s, because x and s are two different references to the same thing.
Think of it like this. Your s is an entry on a clipboard, and the clipboard entry tells you the number of the box to look in to find the int[]. When you pass s to a method, you get a new entry x on the clipboard, with the same box number as was under the s reference. That means that any operation that looks in the box and changes its contents will affect what you get when you look at what s refers to: they both look at the same box number. But if you change the entry on the clipboard for x, it won't change the entry on the clipboard for s, because they're two different entries.
As another example, think of s and x as being road signs pointing to the same town. If you change the town that x points to, e.g. by introducing a one way system in the town centre, then of course what s points to will also have changed. But if you change the road sign x, and write a different town's name on it, that won't automatically change the road sign s too. They're different signs, but signifying the same thing.