Java: design problem with final-value and empty constructor - java

$ 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; }
}

Related

About declaring and initializing primitive variable in different line outside a method

new to the community, and new to the whole programming world.
While I was studying java, I stumbled on a simple question.
In a main method (or any method), I can declare and initialize a primitive variable on different line just fine. Say,
public static void main (Strin[]args){
int age;
age = 42;
}
will complile just fine.
But if I tried this outside a method, as a class variable or instance variable,
public class test {
int age;
age = 42;
}
the code won't compile. It will only work if the variable is declared and initialized in one line. I was wondering why java doesn't allow this outside a method.
A class body can contain variable declarations and method declarations, but no single statements. When would you expect such a statement to be executed? So your initialization has to be either inline with the declaration (as a shortcut) or in some method, e.g. in the constructor, if you want to initialize the variable when creating a new object.
It is a syntax error! Your code does not comply with the Java syntactic and semantics rules as described in Java Language Specification.
You have to initialise it's value inside the constructor (that's the whole point of a constructor), like
public test() {
age = 42;
}
For static variables it's possible to give them a value:
static int age = 42;
Or use a static block:
static {
age = 43;
}

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.

how to declare a helper method in java, to be used locally being able to reference variables

I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}

Java passing arrays into object issue

In java, how do you pass an array into a class. When ever I do I get a "Can not refrence a non-static variable in a static context". the array has 10 positions. I declared the array as.
edit: is this a clearer example? I should also make note that my teacher completely ignored what is static, and how it is used, claiming it isnt important for the programmer to understand.
edit 2: I managed to get it to work by taking
sorter sort = new sorter();
and turned it into
static sorter sort = new sorter();
what exactly did this do to my program, is this considred a bad fix?
main
public class example {
public static void main(String[] args) {
int[] test = new int[10];
sorter sort = new sorter();
sort.GetArray(test);
}
}
class
public class sorter {
int[] InputAR = new int[10];
public sorter
{
}
public void GetArray(int[] a)
{
}
}
You didn't put enough code, put my guess is :
You declared a non-static field (like int[] test = new int[10] instead of static int ...)
the sort.getArray is in the main or in another static method.
This is not possible, because non static fields need a concrete object to exist.
Its because you are calling sort.GetArray(test) in some static method. You need to make your array variable static so as to access it.
Just read this article and you will understand the issue with your code.
"Can not refrence a non-static varible in a static context"
This error of yours has nothing to do with passing arrays or something.Somewhere in your code,or may be inside public void GetArray(int[] a) you a refering a static member but, with a non-static context.
Make that variable non-static, or the method static, or vice-versa.
Refer This Link for more info.

Reasons for restrictions on assignment of final variables

Why aren't final variables default initialized? Shouldn't the default constructor initialize them to default values if you are happy with the constant be the default value.
Why must you initialized them in the constructor at all? Why can you can't you just initialize them before using them like other variables?
ex.
public class Untitled {
public final int zero;
public static void main(String[] args)
{
final int a; // this works
a = 4; // this works, but using a field doesn't
new Untitled();
}
}
Untitled.java:2: variable a might not have been initialized
Why must you initialize static final variables when they are declared? Why can't you just initialize them before using them in any other method?
ex.
public class Untitled
{
public final static int zero;
public static void main(String[] args)
{
zero = 0;
}
}
Untitled.java:8: cannot assign a value to final variable zero
I'm asking these question because I'm trying to find a logical/conceptual reason why this won't work, why it isn't allowed. Not just because it isn't.
The idea behind a final variable is that it is set once and only once.
For instance final variables, that means they can only be set during initialization, whether at declaration, in a constructor, or an instance initialization block. For the variable to be set anywhere else, that would have to take place in a non-constructor method, which could be called multiple times - that's why this is off limits.
Similarly for static final variables, they can only be set at declaration or in a static initialization block. Anywhere else would, again, have to be in a method which could be called more that once:
public static void main(String[] args)
{
zero = 0;
main(null);
}
As for your first question, I'm assuming it's an error not to explicitly set a final variable in order to avoid mistakes by the programmer.
The Java Language Specification section 8.3.1.2 spells out the rules for final member variables:
A field can be declared final (§4.12.4). Both class and instance variables (static and non-static fields) may be declared final.
It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.
A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.
The JLS doesn't give reasons why the rules are they way they are. However, it might have come from experience in writing Java code, and the above rules are a way to avoid some common coding errors.
The concept of being final means that the variable value cannot change. If you could do as in your second example, then this variable would have been like any other one (i.e. not final)
I don't ave a good rational regarding your first question.
Because, when looking at your code, the Java compiler has no idea whether a given statement will be executed before an other statement. The only exceptions to this rule are code in constructors and implicit constructors, and that's why they're the only place that final fields can be assigned to.

Categories