trying to reassign value to class instance variables - java

I am being beginner trying to learn java basics and here in the this program I am confused why
we can't reassign the value of class instance variable.
this is error in this program. Please guys help me out to figure it out. thanks
class AddInsideClassVar{
int a = 3;
int c;
c = a + a;
public static void main(String args[]){
System.out.println();
}
}

You may define fields within a class, but you are not allowed to put calculation statements outside of a method definition. A field declaration is of the form type; or type = value;
For example (from your code);
class AddInsideClassVar{
static int a = 3; // ok this is a declaration for a field (variable)
static int c; // ok, this is too
//c = a + a; // this is a statement and not a declaration. A field may be
// declared only once
static int d = a + a; // this will work since it is part of a declaration.
public static void main(String args[]){
System.out.println("a=" + a + ", c=" + c + ", d=" + d);
}
}

You cannot execute c = a + a in that section. If anything you'd need to do
int a = 3;
int c = a + a;
If you make these variables static then you could do
private static int a = 3;
private static int c;
static {
c = a + a;
}

You can try this (just an example of workaround):
class AddInsideClassVar{
static {
int a = 3;
int c;
c = a + a;
System.out.println(c);
}
public static void main(String args[]){
}
}

You may be mixing your statics with instance variables. Here's how I would write this to not confuse myself:
public class AddInsideClassVar{
int a;
int c;
public void doStuff() {
a = 3;
c = a + a;
}
public static void main(String args[]){
AddInsideClassVar instance = new AddInsideClassVar();
instance.doStuff();
System.out.println(c);
}
}
a and c are instance variables. They are manipulated by a non-static method which requires an instance of the class to operate on. So, I create the instance in main(), then call the function to manipulate instance variables.

Explanation : int c = a + a is a declaration whereas " c = a + a ; " ( alone ) is a statement ; You have a point, it does not make much sense ;
class MyClass {
int a = 3;
int c = a + a; // Correct
}
or
class MyClass {
int a = 3;
int c;
public void addition () {
c = a + a; // Correct
}
}
but not
class MyClass {
int a = 3;
int c;
c = a + a; // Incorrect
}
NOTE : On the other, the Scala programming language ( compiles to JVM ) allows you to do the following :
scala> class MyClass { val a:Int = 3;
var c:Int = _;
c = a + a ; // Correct
}
defined class MyClass

Related

Inner class' instance not able to access Outer class' data member

The documentation says "An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance." This means with the instance of inner class, I can access the members of the outer class. But I am not able to do so.
public class TopLevel {
private int length;
private int breadth;
public class NonstaticNested{
private static final int var1 = 2;
public int nonStaticNestedMethod(){
System.out.println(var1);
length = 2;
breadth = 2;
return length * breadth;
}
}
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
NonstaticNested nonStaticNested = topLevel.new NonstaticNested();
// Trying to access the length variable on 'nonStaticNested' instance, but not able to do so.
}
}
I hope the comments within the main are self speaking.
public class A {
int a = 1;
public static void main(String[] args) {
B b = new B();
// Works as "a" is defined in "A"
System.out.println(b.a);
// Works as "b" is defined in "B"
System.out.println(b.b);
C c = new C();
C.D d = c.new D();
// Works as "c" is defined in "c"
System.out.println(c.c);
// Works as "d" is defined in "D"
System.out.println(d.d);
// Error here as there is no "c" defined within "D", it´s part of "C" and here´s your
// logical mistake mixing it somewhat with what inheritance provides (just my guess).
System.out.println(d.c);
}
}
class B extends A {
int b = 1;
}
class C {
int c = 1;
class D {
int d = 2;
public D() {
// Has access to "c" defined in C, but is not the owner.
c = 2;
}
}
}

How to transform this class to immutable?

I am in process of learning immutability but I am not able to exactly digest how this works. So in order for me to understand immutability, I created a test program.
The funtion getArray(Box b) will make an ArrayList of Box objects.
Expected output: Actual output:
Output Output
a is 5 a is 5
b is 10 b is 10
Output Output
a is 0 a is 4
b is 0 b is 40
Output Output
a is 1 a is 4
b is 10 b is 40
Output Output
a is 2 a is 4
b is 20 b is 40
Output Output
a is 3 a is 4
b is 30 b is 40
Output Output
a is 4 a is 4
b is 40 b is 40
Logic:
public class Box {
static int a;
static int b;
public Box() {
a = 5;
b = 10;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
public void setB(int x) {
b = x;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Main Class
import java.util.ArrayList;
public class Check {
public static void main(String[] args) {
Box b = new Box();
b.display();
ArrayList<Box> arr2 = new ArrayList<Box>();
arr2 = getArray(b);
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box>();
for (int i = 0; i < 5; i++) {
b.setA(i);
b.setB(i * 10);
arr.add(b);
}
return arr;
}
}
How do I change the logic in such a way that I get the desired output? How do we decide how and where to edit the code to ensure immutability?
This would be an immutable:
public final class Box {
final int a;
final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
}
And then your array method would be:
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box> ();
for(int i =0 ;i <5; i++) {
arr.add(new Box(i, i*10));
}
return arr;
}
The data members are declared final because they're immutable, and so getters are pointless and setters just make no sense.
The class is declared final so you cannot subclass it.
In short, an immutable object is an object whose state cannot be modified after it's created. Your immutable Box object would look like this:
public final class Box {
private final int a;
private final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Notice that the variables a and b are assigned exactly once, during the construction of the Box instance. There are no setters, because Box's immutability means that its state (including variables a and b) will not change over its lifetime.
The final keyword in front of a and b means that you must assign them exactly once. It's actually considered good practice to make all your variables final unless you specifically need them not to be; but for an immutable object it's essential.
You were using the static keyword. Static has nothing to do with immutability. It means the variable is shared among all instances of the Box class. In my example, each Box instance has its own copies of a and b, because I didn't make them static.
To wrap this up, I'll give an example of your main class which has the desired output:
public class Check {
public static void main(String[] args) {
final List<Box> arr2 = getArray();
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray() {
final ArrayList<Box> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final Box box = new Box(i, i * 10);
arr.add(box);
}
return arr;
}
}
Note that a new instance of box is created at every iteration of the loop.

Java - Using the output from one class in another

I'm trying to write a program that takes the output of adding two numbers in one class together and adds it to a different number. Here is the first class:
public class Add{
public static void main(String[] args) {
int a = 5;
int b = 5;
int c = a + b;
System.out.println(c);
}
}
And the second:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add();
int b = 5;
int c = a.value+b;
System.out.println(c);
}
}
How do I get this to work? Thanks.
Suggestions:
You need to give the Add class a public add(...) method,
have this method accept an int parameter,
have it add a constant int to the int passed in,
and then have it return the sum.
If you want it to add two numbers, rather than a number and a constant, then give the method two int parameters, and add them together in the method.
Then create another class,
In this other class you can create an Add instance,
call the add(myInt) method,
and print the result returned.
You could try
public class Add{
public int c; // public variable
public Add() { // This is a constructor
// It will run every time you type "new Add()"
int a = 5;
int b = 5;
c = a + b;
}
}
Then, you can do this:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add(); // Here, the constructor is run
int b = 5;
int c = a.c + b; // Access "a.c" because "c" is a public variable now
System.out.println(c);
}
}
Read more about constructors here.

Will there any issues in initializing non-static member variables this way?

I have initialized the variables as follows in the code below. Is it okay to initialize like this ?
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
public static int getInt() {
int ret = 10;
System.out.println("ret- " + ret);
return ret;
}
public static int processInt(int toProcess) {
int toRet = toProcess / 2;
System.out.println("toRet- " + toRet);
return toRet;
}
public static void main(String[] args) {
StaticInit sit = new StaticInit();
}
}
You can initialise with the variable declaration or in the constructor. Some will argue that one or the other is better but either works. I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases.
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
}
or
public class StaticInit {
int x;
String z;
public StaticInit() {
x = 10;
z = x / 2;
}
}
For this case in particular though, I would definitely recommend using the constructor since z relies on x. Plus the constructor is much nicer than using static methods.
Personally, instead of having the getInt(), I would just initialise it in the constructor.
Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value.

How do I call a private method with arguments

I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.
main class:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
//this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for(int n = 1; n <= max; n++)
{
for(a = n; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
String last = a + "" + b + c;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = output + this.greatestCommonFactor( ) + " \n";
return output;
}
}
and for cross-referencing my runner class:
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples triple = new Triples(big);
//call the toString method to print the triangle
out.println( triple );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
as they are only required within the scope of the method.
Well, yeah. You're not passing anything to greatestCommonFactor. I'm not sure what you expected to happen in your toString() method when you didn't pass enough arguments to a method.
you need to pass them like
output = output + this.greatestCommonFactor(1,2,3) + " \n";
the thing is, unless you are passing parameters to toString, without this, this code seems very limited. Alternatively you need to set some fields on the class with what will be passed into your function.

Categories