error: cannot assign a value to final variable (int) - java

Ok I'm sure this is simple, but I'm having issues and my mind is blank. =(
I know 'final' makes it so the variable can't change but that's pretty much all I can figure out about it right now.
And the code...
If I take out the 'final' the error comes up as "error: missing return statement
}" for the first two methods.
EDIT: Thank you all for the help, surprising how fast I got help!
So I just took out 'final' and added 'void' to the first two methods. I'm sure it'll take some time to fully understand everything, but it definitely helps.
There is a part two and here is the part that I have no clue on what to do...
The second part you just have to test this first program. Am I supposed to make a separate file with the same code?
If anyone can help great, but if not thats fine I'll work on it later.

You declare your function as
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
The emphasis here is the public static int, telling the compiler that your function is supposed to return an integer. You do however not return anything in that function body, so the compiler complains rightfully. Either return something, or declare the return value as void.

Maybe you're missing the return statement for the first two methods. Or you may want to change the return type to void if you don't need to return anything.
Doing these will remove your error but it might differ from what you need.
public static void addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static void removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Hope this helps.

A variable declared with static and final keywords behaves like a constant. But what does that mean ?
It means you can't change their values. In simpler terms if variable is a primitive then you can't change its value but if its a reference variable then you can't change the reference to some other address.
So in your code, declaring numberInRoom and totalNumber variables as static and final is wrong
public static int numberInRoom=3;
public static int totalNumber=30;
public static int addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Are you sure that you want these variables to be declared as static because such variables shall be shared by all instances of the concerned class. Please have a look at what does declaring variables as static and final means

Related

Why Does (a) print (0)?

i am trying to grasp the idea of ObjectOriented programing can someone explain why the local variable (a) prints zero instead of the set int that is placed in the getter and setter.
These are the objects in the AppClass
Symptoms obj = new Symptoms();
test obj2 = new test();
actionPerformed... i think this is all you need from the AppClass
#Override
public void actionPerformed(ActionEvent e) {
int x = Integer.parseInt((field.getText()));
obj.setSleep(x);
writeSleep();
frame.setVisible(false);
obj2.tester();
readSleep();
initialize2();
}
This is the Symptoms class that i hope to add more symptoms if i can get this to work
public class Symptoms {
private int sleep;
public int getSleep() {
return sleep;
}
public void setSleep(int sleep) {
this.sleep = sleep;
}
}
this is the tester class where i hope to print out the value of (a)
public class test {
public void tester(){
Symptoms get = new Symptoms();
int a;
a = get.getSleep();
System.out.println(a);
}
}
It seems as tho the test class isnt getting the "message" but if i run the same code in the AppClass, given i modify the code a little bit, then (a) will print.
Because the JLS says so, see chapter 4.12.5. Initial Values of Variables:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
For type int, the default value is zero, that is, 0.
Now after you saw it's confusing, I recommend you to explicitly set it to zero in the future, it's clearer.
In test.tester(), an instance of Symptoms is created and the method setSleep() is never called with it, so getSleep returns the default value of a, which is 0.
You only ever call setSleep in obj.setSleep(x);, where obj is an entirely different instance from get. But since x is not static, calling obj.setSleep doesn't change the value of get.x -- only the value of obj.x.
here is a better version of the question and the answer. It has nothing to do with setting int to zero.
How to set and get with three Classes?

How can i call a variable from another method

I need to know how to call a variable from one method to another
Can anyone help me?
public static void number(){
number = 1;
}
public static void callNumber(){
/*How can I call number to this method???
*/
}
Actually, "call a variable from an other method" is not very explicit, since a variable in a method is either global (used in the method but naturally available in the entire program), or a local variable of the method.
And in this last situation it is impossible to get this value.
Then either you declare your variable externally and it is trivial, or you specifiy a type value to your method "number()":
public static int number() {
int number = ...;
return number;
}
and you call it:
public static void callNumber() {
int numberReturned = number();
// other things...
}
Note: your code number = 1; specifies that your variable is global...
The trick is to set "number" available either by the return of the method, or by specifying this variable global.
I don't know if I've answered your question, if not try to be more explicit.
Between static methods, variables can be shared by making them global,
or by sending them as parameters(noas described by #Gaétan Séchaud).
However, if those two methods has a continuos connection between them, and they handle some variables needed to be shared, it smells like a class is needed.

scopes of variables in Java

In Java, you don't have declare a method physically before you use it. The same thing doesn't apply for variables.
Why is this the case? Is it just for "legacy" reason (ie., the Java's creators didn't feel like doing it), or is it just not possible?
Eg.,
public class Test
{
// It is OK for meth1 to invoke meth2
public void meth1() { meth2(); }
public void meth2() { }
// But why is it NOT ok for field1 to reference field2
private int field1 = field2;
private int field2 = 3;
}
If I wanted my Java compiler to support this kind of forward-reference, what is the general idea as to how to do it?
I understand there'd be issue about circular depencies, which we'd need to be careful about. But other than that, I really don't see why it should not be possible.
[Edit]Ok, here's my initial thought as to how to do this.
While analysing the code, the compiler would build a graph of dependencies for the variables in the given scope. And if it sees a loop (ie., int a = b; int b = a), then it would throw an error. If there is no loops, then there must be some optimal way to re-arrange the statements (behind the scence) such that a field will only reference fields declared before it, and so it shouuld try to figure out the order. I haven't worked out the exact algorithm, but I think it is possible. Unless someone can scientifically prove me wrong.
Recap the question:
Say I'm trying to build my own dialect of Java, which supports this sort of scoping. My main question is, could you give me some ideas as to how to do this
Thanks
According to the JLS, Section 12.4.1, initialization of class variables proceeds from top to bottom, in "textual order":
The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
So, if you make your own compiler to recognize forward class variable declarations, then it is violating the Java Language Specification.
I will give you a simple piece of code:
public class Test
{
private int foo = bar;
private int bar = foo;
}
What would you expect this to do?
I presume that designers of Java has done it so because assignment of values to instance variables must be executed in some order. In the case of Java, they are executed downwards (from up to bottom).
EDIT
What about this?
public class Test {
private int foo = quu++;
private int bar = quu++;
private int quu = 1;
}
What values would foo and bar have? Which quu++ statement would be executed first?
My point is, Java designers must have thought that it is counter intuitive to do it as you did describe in your question, i.e. unordered execution with compile time code analysis.
FINAL EDIT
Let's complicate things:
class Test {
private James james = new James(anInt);
private Jesse jesse = new Jesse(anInt);
private IntWrapper anInt = new IntWrapper();
}
class James {
public James(IntWrapper anInt) {
if(--anInt.value != 0) {
new Jesse(anInt);
}
else {
anInt.isJames = true;
}
}
}
class Jesse {
public Jesse(IntWrapper anInt) {
if(--anInt.value != 0) {
new James(anInt);
}
else {
anInt.isJames = false;
}
}
}
class IntWrapper {
public int value = 99;
public boolean isJames;
}
I am not sure what it proves regarding your question because I am not sure about your point.
There is no circular dependency here but value of an instance variable of IntWrapper, isJames, depends on the execution order and it might be difficult to detect this kind of stuff with a lexical/semantic analyzer.
How will field1 know value of field2 before it has been defined and assigned a value?
It has to do with the order of initialization. Fields are initialized top to bottom. In your example, when field1 tries to reference field2 in the initializer, the latter is yet to be initialized itself.
The rule about forward references is aimed at catching the most obvious cases of this problem. It does not catch all; for example, you can still do:
private int field1 = getField2();
private int field2 = 3;
private int getField2() { return field2; }
and get field1 intialized to zero where you might be expecting 3.

Java: design problem with final-value and empty constructor

$ javac InitInt.java
InitInt.java:7: variable right might not have been initialized
InitInt(){}
^
1 error
$ cat InitInt.java
import java.util.*;
import java.io.*;
public class InitInt {
private final int right;
// Design Problem?
// I feel the initialization problem is just due to bad style.
InitInt(){}
InitInt{
// Still the error, "may not be initialized"
// How to initialise it?
if(snippetBuilder.length()>(charwisePos+25)){
right=charwisePos+25;
}else{
right=snippetBuilder.length()-1;
}
}
public static void main(String[] args) {
InitInt test = new InitInt();
System.out.println(test.getRight());
}
public int getRight(){return right;}
}
Partial Solutions and Suggestions
use "this" to access methods in the class, instead of creating empty constructor
change final to non-final
with final field value: initialize all final values in every constructor
remove the empty constructor, keep your code simple and clean
You mean define, not initialize. The problem you're having (after that pretty radical edit) is you're defining a constructor that doesn't initialize a final variable, which Java doesn't allow -- all finals need to be initialized by the time the instance is finished constructing. Either initialize it in your constructor, or make it non-final
Yeah, the problem is that one of your constructors doesn't initialize the final field. In Java final non-static fields have to be initialized at the declaration time, in an initialization block, OR in EVERY constructor! The default constructor in your example doesn't do that.
Remember as well that implementing an empty default constructor makes sense only if you want to use inheritance features. If you don't provide a default constructor, but you will some other one Java won't make a hidden default constructor for you, because the default one is not required. So don't implement things like MyClass() {} with no special purpose - keep your code clean and save!
You can't use new with int. int is a primitive, and new is an object operator. Consider using Integer instead, or just assigning an integer literal to it.
There's nothing wrong with your if-else statement, and nothing wrong with initializing a final variable within a branching statement in a constructor. I just ran a simple constructor like yours to initialize private int right and it worked fine. Make sure that you are declaring your constructor correctly, as InitInt() { ... }.
The error you posted is because you have in your code InitInt(){}, an empty constructor that does not initialize right. You need to initialize final fields in this and all constructors.
Your constructor is absolutely Okey!!!! The problem is that you left the "right" variable uninitialized.
You have to initialize the "right" variable:
private final int right = 0;
If you only try to access the methods in the class, use this, instead of creating empty-constructor for it:
import java.io.*;
import java.util.*;
public class FileDir {
private ArrayList<Integer> lineNumbers;
FileDir(Integer nth){
lineNumbers=new ArrayList<Integer>();
lineNumbers.add(nth);
// You don't need an empty constructor
// to call class methods, use "this"
this.printHello("Davids");
}
public static void main(String[] args) {
FileDir test = new FileDir(7);
ArrayList<Integer> inteTest=test.getLineNumbers();
for (Integer i : inteTest)
System.out.println(i);
}
public void printHello(String name) { System.out.println("Hello "+ name); }
public ArrayList<Integer> getLineNumbers() { return lineNumbers; }
}

Using "this" with methods (in Java)

what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?
The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:
public class Test {
String s;
private String hey() {
return s;
}
public String getS(){
String sm = this.hey();
// here I could just write hey(); without this
return sm;
}
}
Three obvious situations where you need it:
Calling another constructor in the same class as the first part of your constructor
Differentiating between a local variable and an instance variable (whether in the constructor or any other method)
Passing a reference to the current object to another method
Here's an example of all three:
public class Test
{
int x;
public Test(int x)
{
this.x = x;
}
public Test()
{
this(10);
}
public void foo()
{
Helper.doSomethingWith(this);
}
public void setX(int x)
{
this.x = x;
}
}
I believe there are also some weird situations using inner classes where you need super.this.x but they should be avoided as hugely obscure, IMO :)
EDIT: I can't think of any examples why you'd want it for a straight this.foo() method call.
EDIT: saua contributed this on the matter of obscure inner class examples:
I think the obscure case is: OuterClass.this.foo() when accessing foo() of the outer
class from the code in an Inner class that has a foo() method as well.
I use "this" to clarify code, often as a hint that I'm calling an instance method rather than accessing a class-level method or a field.
But no. Unless disambiguation is required due to scope naming collision, you don't actually need "this."
For most general programing, the this keyword is optional and generally used to avoid confusion. However, there are a few places where it is needed.
class Foo {
int val;
public Foo(int val) {
this(val, 0); //this MUST be here to refer to another constructor
}
public Foo(int val, int another) {
val = val; //this will work, but it generally not recommended.
this.val = val; //both are the same, but this is more useful.
method1(); //in a Foo instance, it will refer to this.method1()
this.method1(); //but in a Foo2 instance, you must use this to do the same
}
public void method1() {}
}
class Foo2 extends Foo {
public Foo2(int val) {
this(val); //this will refer to the other Foo2 constructor
}
public Foo2(int val, int another) {
super(val, another);
super.method1(); //this will refer to Foo.method1()
}
#Override
public void method1() {}//overridden method
}
These are not all the cases, but some of the more general ones. I hope this helps you better understand the this and super keywords and how/when to use them.
The only reason to prepend this in front of a method invocation is to indicate that you're calling a non-static method. I can't think of any other valid reason to do this (correct me I'm wrong). I don't recommend this convention as it doesn't add much value. If not applied consistently then it could be misleading (as a this-less method invocation could still be a non-static method). How often does one care if the method being invoked is static or not? Furthermore, most IDEs will highlight static methods differently.
I have heard of conventions where this indicates calling the subclass's method while an absence of this is calling the super class's method. But this is just silly as the convention could be the other way around.
Edit: As mmyers points out (see comment), this works with static methods. With that, I see absolutely no reason to prepend with this as it doesn't make any difference.
The only time it is really required is when you have a parameter to a method with the same name as a member variable. Personally, I try to always use it to make the scope of the variable/method explicit. For example you could have a static method or an instance method. When reading the code it can be helpful to know which is which.
Not an answer (so feel free to vote it down), but I couldn't fit this into a comment where someone was asking.
A lot of people use "this.x" to visually differentiate instance variables from local variables and parameters.
So they would do this:
private int sum;
public int storeSquare (int b) {
int c=b*b;
this.sum+=c; // Makes sum "pop" I guess
return c;
}
Personally I think it's a bad habit: any usable editor will put instance and local variables in a different color for you reliably--it doesn't require any human-fallible patterns.
Doing it with "this." is only 50% safe. Sure the compiler will catch it if you try to put this.x when x is a local variable, but there is nothing that is going to stop you from "Forgetting" to tag an instance variable with this., and if you forget to tag just one (or if someone else works on your code) and you are relying on the pattern, then the pattern may be more damaging than good
Personally I'm fairly sure the pattern stems from programmers (rightful) discomfort with the fact that in this case:
public void setMe(int me) {
this.me=me;
}
the fact that you need "this." in front of the me is determined by the name of the parameter--I agree it just feels sloppy. You want to be consistent--if you need this. in front of the me there, why not always use it?
Although I understand the discomfort, typing this. every single place that an instance variable is used is just pedantic, pointless, ugly and unreliable. If it really bothers you and you absolutely need to use a pattern to solve it, try the habit of putting "p" in front of your parameters. As a side effect, it should even make it more constant because the parameter case will now match the method case..
public void setMe( int pMe)
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
You absolutely need this if your method needs to return the object's instance.
public class StringBuildable {
public StringBuildable append(String text) {
// Code to insert the string -- previously this.internalAppend(text);
return this;
}
}
This allows you to chain methods together in the following fashion:
String string = new StringBuildable()
.append("hello")
.append(' ')
.append.("World")
.toString()
;

Categories