Final variable may already have been assigned - java

I am writing a program that has two final variables that I wish to use, I need these to be set at the time that I actually run the class because they are likely to be different each instance.
I have the initialization the same as any other class variable I wish to use where I initialize a name and type but not a value.
public final String filename, filepath;
In the Constructor I set the values as follows
public myClass(String value) {
this.filename = value;
this.filepath = anotherPartOfValue;
}
When I do this, I get a warning that "The final field [x] may have already been assigned"
Is there a way to avoid this warning and still keep the final state and set the value in the constructor?
I am using eclipse btw.
Edit:
This is the exact code that gives me the error
import java.io.*;
public class Dirt {
private String[] tables;
private int numTables;
private final String filename, filepath;
public Dirt(String file) {
this.tables = new String[0];
this.numTables = 0;
for (int i = file.length(); i < 0; i--) {
if (file.charAt(i) == '/') {
this.filename = file.substring(i);
this.filepath = file.substring(1, i-1);
}
}
}
}

The problem is that you are assigning to the final variables in a loop. There's nothing to prevent the loop from looping more than once and the if condition being satisfied more than once. (What happens if there are two '/' characters in file? Or none?)
One way around this is to use temporary String variables in the constructor and then assign them to filename and filepath at the end:
public Dirt(String file) {
this.tables = new String[0];
this.numTables = 0;
String name = null;
String path = null;
for (int i = file.length(); i < 0; i--) {
if (file.charAt(i) == '/') {
name = file.substring(i);
path = file.substring(1, i-1);
// need a break here?
}
}
this.filename = name;
this.filepath = path;
}
It's ugly, but it's a straightforward way to know for sure that filename and filepath will definitely be assigned and definitely be assigned only once.

Completely compileable and runnable:
public static void main(String[] args) {
Foo f = new Foo("abc");
System.out.println(f.filename);
System.out.println(f.filepath);
}
static class Foo {
public final String filename, filepath;
public Foo(String value) {
this.filename = value;
this.filepath = value.substring(1);
}
}
And the "warning" you mention isn't just a warning. It's an error. But it's not coming from here.
Edit: Your newly posted code has the assignments in a loop. By definition, statements in a loop can execute multiple times, and therefore you have the potential for assigning the final variables multiple times.

Related

How to create two object reference variables in seperate classes in java

I have a class called AgendaFunctions, a class called Main, and a class called ReadFiles. Main has a reference variable for Agenda Functions and ReadFiles. AgendaFunctions has an array of reference variables. I have code to instantiate the array, but i need to instantiate it from ReadFiles. If I instantiate it from main, it works fine. But if i call the method from ReadFiles, it doesn't work. I get a java.lang.NullPointerException error.
Here is the code for Main:
public class Main {
public static void main(String[] args) throws Exception {
ReadFiles fw = new ReadFiles(); fw.read();
agendafunctions link = new agendafunctions();
AgendaFunctions:
public class agendafunctions {
int amount = 20;
public void setamount(int data) {
}
static String input = "true";
agendaitem item[] = new agendaitem[amount];
int counter = 0;
public void instantiate() {
item[1] = new agendaitem();
item[2] = new agendaitem();
item[3] = new agendaitem();
}
public void createobject(String name, Boolean complete, String Comments) {
item[counter].name = name;
item[counter].complete = complete;
item[counter].comments = Comments;
counter++;
}
ReadFiles:
public class ReadFiles {
public void read() throws IOException {
agendafunctions af = new agendafunctions(); af.instantiate();
int readitem = 1;
BufferedReader data = new BufferedReader(new FileReader("C:/Agenda Dev Docs/data.txt"));
int filestoread = Integer.parseInt(data.readLine());
while (readitem <= filestoread) {
String name;
String complete;
String comments = null;
String line;
Boolean bc = null;
BufferedReader read = new BufferedReader(new FileReader("C:/Agenda Dev Docs/"+readitem+".txt"));
readitem++;
name = read.readLine();
complete = read.readLine();
comments = "";
while((line = read.readLine()) != null) {
comments = comments + line;
}
if(complete.equals("Complete")) {
bc = true;
} else if(complete.equals("Incomplete")) {
bc = false;
}
af.createobject(name, bc, comments);
}
}
If I call the method instantiate from ReadFiles, i get a NullPointerException. If I call it from Main, everything works. But further development requires me to call the method from ReadFiles. How would i fix this? Thanks.
You have this
int counter = 0;
public void instantiate() {
item[1] = new agendaitem();
item[2] = new agendaitem();
item[3] = new agendaitem();
}
public void createobject(String name, Boolean complete, String Comments) {
item[counter].name = name;
item[counter].complete = complete;
item[counter].comments = Comments;
counter++;
}
where item is an array with 20 indices, ie 20 elements, but your instantiate method only initializes elements at indices 1 through 3, missing 0 and 4 through 19.
In your ReadFiles#read() method, you do
agendafunctions af = new agendafunctions(); af.instantiate();
which instantiates one agendafunctions object and calls instantiate() which initializes elements at indices 1, 2, and 3 in your item array.
You then loop in the while and call
af.createobject(name, bc, comments);
a bunch of times on the same object.
The reason it fails the first time is because you haven't initialized the element in item at index 0. Arrays always start at 0, not 1.
Another cause for error (which you'll see if you fix the above problem), is that if your while loop loops more than 3 times, you'll again get a bunch of NullPointerExceptions because counter keeps growing, but you aren't initializing the elements that you'll then try to access at counter index.
item[counter].name = name; // if counter is 4, you'll get NullPointerException because
// the element there hasn't been initialized as 'new agendaitem();'
#SotiriosDelimanolis explained why you are getting NPE, to fix that you just can get rid of the instantiate() method and add item[counter] = new agendaitem(); as first line in your createobject method. Also you have to make sure your while loop does not exceed amount. To avoid these worries better use an ArrayList for agendaitem

java,returning null value from method

I need to return finalString value for input operator name.
where,internalPrestring is fixed for specific operator,internalDigit would be retrieved from getting operator name.then all of'em would be added to finalString.
but it is giving null, i can't understand the problem
import java.io.*;
import java.lang.*;
class CallManager
{
public static final String postString = "#";
StringBuilder stringBuilder;
String internalPreString;
String preString;
String middleString;
String finalString;
String operatorName;
int internalDigit;
//needs to set oprator name
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
//afeter having operator name need to set inrernal digit for each operator
public void setOperatorBasedInternalDigit(int getIntegerForOperator)
{
internalDigit = getIntegerForOperator;
System.out.println("I got it too " + internalDigit);
}
//it needs to get string from ocr
public void setString( String getMeFromOCR )
{
middleString = getMeFromOCR;
}
//preString creator for differnet operator
public String getOperatorBasedPreString(String operatorName)
{
if(operatorName.equals("Airtel"))
internalPreString = "787";
else if(operatorName.equals("Banglalink"))
internalPreString = "123";
else if(operatorName.equals("Grameen"))
internalPreString = "555";
else if(operatorName.equals("Robi"))
internalPreString = "111";
else if(operatorName.equals("TeleTalk"))
internalPreString = "151";
stringBuilder.append("*").append(internalPreString).append("*");
preString = stringBuilder.toString();
return preString;
}
//get operator name and retrive midlle string's digit size from it
public int getOperatorBasedInternalDigit( String operatorName)
{
if(operatorName.matches("^Airtel | Grameen | Robi$"))
internalDigit = 16;
else if(operatorName.matches("^Banglalink$"))
internalDigit = 14;
else if(operatorName.matches("^TeleTalk$"))
internalDigit = 13;
return internalDigit;
}
//check operator-based digit number with input middle string as a number then retrive final string
public String getString( String toBeInserted, int inetrnalDigit)
{
if(toBeInserted.length() == internalDigit)
{
int counter = 0;
char [] insertHere = new char[internalDigit];
for(int verifier = 0; verifier < internalDigit; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
break;
counter ++;
}
if(counter == internalDigit)
{
stringBuilder.append(preString).append(toBeInserted).append(postString);
finalString = stringBuilder.toString();
//to see what i've got finally as input for using this call manager method.it would be removed too
System.out.println(finalString);
return finalString;
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
else
{
//this printing could be used in main program
System.out.println("number is less or more than desired ..... INVALID SCAN");
System.out.println(middleString);
//here i will call the method for scan the card again
//
//
return middleString;
}
}
}
//tester class that CallManager works rightly or not
class CallManagerDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name of Operator");
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
}
}
You are having only four lines that deals with your CallManager class:
CallManager clm = new CallManager();
clm.setOperatorName("Banglalink");
System.out.println(clm.internalPreString);
System.out.println(clm.preString);
The reason why you are getting null :
You are using a default constructor right and there processing is
done in it. So this is not a problem
Now on next line you call setOperator method which has this code:
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
Now here you are only setting thw variable operatorName and nothing else. So all other variables are null as you not doing any processing or something that will initialize them to something.
So when you print clm.internalPreString and clm.preString you get null as they are not initialized. But try printing clm.operatorName and it will print the operator name that you passed and was initialzed inside your method setOperatorName.
So as you have defined so many method inside your class, use them so that all the variables are set as per your logic
UPDATE
public void setOperatorName( String getMeFromPreferences)
{
operatorName = getMeFromPreferences;
//call any methods for example and use the values returned from the method by storing it inside a variable
String mystring = getOperatorBasedPreString(String operatorName)
}
You have never set the values for the variables for those you are getting the NULL value.The terms get/set must be used where an attribute is accessed directly.Read Java Programming Style GuideLines For more clarity.Use appropriate getters and setter for getting and setting the value like you have done for operatorName.
Don't you think that you should call any of the function instead of the string variables using object.
You are just calling one function that is
public void setOperatorName(String getMeFromPreferences) {
operatorName = getMeFromPreferences;
System.out.println("I got it " + operatorName);
}
You are calling default constructor with out any variable setting there,
You had not initialized any String you are calling form object.
I think you should call any of the function e-g
public int getOperatorBasedInternalDigit(String operatorName)
OR
public String getString(String toBeInserted, int inetrnalDigit)
Then you will get some string as you are expecting ...
Hope this will help you.

Behavior of return statement in catch and finally

public class J {
public Integer method(Integer x)
{
Integer val = x;
try
{
return val;
}
finally
{
val = x + x;
}
}
public static void main(String[] args)
{
J littleFuzzy = new J();
System.out.println(littleFuzzy.method(new Integer(10)));
}
}
It will return "10".
Now I just replace Return type Integer to StringBuilder and Output was changed.
public class I {
public StringBuilder method(StringBuilder x)
{
StringBuilder val = x;
try
{
return val;
}
finally
{
val = x.append("aaa");
}
}
public static void main(String[] args)
{
I littleFuzzy = new I();
System.out.println(littleFuzzy.method(new StringBuilder("abc")));
}
}
OutPut is "abcaaa"
So, Anybody can explain me in detail.?
what are the differences.?
Just because integer in immutable so after method returns even if value is changed in method it does not reflect, and does reflect in StringBuilder Object
EDIT:
public class J {
public String method(String x) {
String val = x;
try {
return val;
} finally {
val = x + x;
}
}
public static void main(String[] args) {
J littleFuzzy = new J();
System.out.println(littleFuzzy.method("abc"));
}
}
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".
In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
In above method, finally block is calling everytime.
When an object is passed, the copy of its reference gets passed and you can change the contents if it is mutable.

Java HashMap sometimes returning wrong value in some threads

Update: It was a static buried deep in some code where it was used for just a couple of instructions. Thank you all for the suggestions.
We are not using one HashMap across threads (yes that is bad for many reasons). Each thread has its own HashMap.
We have a class that extends from Thread. In Thread.run() we create a HashMap, set a key/value pair in it, and pass that HashMap to a method. That method retrieves the value from the HashMap, inserts it into a string, and returns the string.
Sometimes the returned string has a different value (still in Thread.run()). This only occurs on hardware with 3+ physical cores. And it has only happened twice (before we added logging to help us find exactly what is going on of course).
Any idea why this would occur.
Update: here's the full code. The ProcessTxt is what pulls the value from the HashMap and puts it in the string.
import java.io.*;
import java.util.HashMap;
import junit.framework.TestCase;
import net.windward.datasource.dom4j.Dom4jDataSource;
import net.windward.xmlreport.ProcessReport;
import net.windward.xmlreport.ProcessTxt;
/**
* Test calling from multiple threads
*/
public class TestThreads extends TestCase {
private static String path = ".";
// JUnit stuff
public TestThreads(String name) {
super(name);
}
// Get logging going - called before any tests run
protected void setUp() throws Exception {
ProcessReport.init();
}
// this is not necessary - called after any tests are run
protected void tearDown() {
}
private static final int NUM_THREADS = 100;
private boolean hadWithVarError = false;
/**
* Test that each thread has unique variables.
*/
public void testRunReportsWithVariables() throws Exception {
// run 10 threads
ReportThreadWithVariables[] th = new ReportThreadWithVariables[NUM_THREADS];
for (int ind = 0; ind < NUM_THREADS; ind++) {
th[ind] = new ReportThreadWithVariables(this, ind);
th[ind].setName("Run " + ind);
}
for (int ind = 0; ind < NUM_THREADS; ind++)
th[ind].start();
boolean allDone = false;
while (!allDone) {
Thread.sleep(100);
allDone = true;
for (int ind = 0; ind < NUM_THREADS; ind++)
if (th[ind].isAlive())
allDone = false;
}
assertTrue(!hadWithVarError);
}
public static class ReportThreadWithVariables extends Thread {
private TestThreads obj;
private int num;
public ReportThreadWithVariables(TestThreads tt, int num) {
obj = tt;
this.num = num;
}
public void run() {
try{
System.out.println("starting " + num);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ProcessTxt pt = new ProcessTxt(new FileInputStream(new File(path, "Thread_Test.docx")), out);
pt.processSetup();
// don't use order1.xml, but need a datasource.
Dom4jDataSource datasource = new Dom4jDataSource(new FileInputStream(new File(path, "order1.xml")));
HashMap map = new HashMap();
map.put("num", new Integer(num));
datasource.setMap(map);
pt.processData(datasource, "");
pt.processComplete();
String result = out.toString().trim();
System.out.println("complete " + num + ", result = " + result);
String expected = "Number: " + num;
if (!result.equals( expected ))
obj.hadWithVarError = true;
assertEquals(expected, result);
} catch (Throwable e) {
obj.hadWithVarError = true;
e.printStackTrace();
}
}
}
}
(edit to format code)
Given the lack of code and based solely on what has been written I am going to hypothesize that something is static. That is, somewhere along the line a static member is being stored to/written from.
num is not mutable and the other variables (string, map) are local so ReportThreadWithVariables looks thread safe. It seems to me that the problem is in the calls to external objects rather than what you posted.
Are the classes you use documented as Thread Safe?
For exampel, the javadoc of the processData method states that it should not be called multiple times for the same datasource which you seem to be doing (same file name).
ps: (not related) you could use a CountDownLatch instead of the while loop.

How to avoid code repetition initializing final properties?

public class Code{
//many properties
//...
final String NEWLINE;// ohh a final property!
void creation() //this method is for avoid repetition of code
{
//final initialization can't be put here =(
Source= new StringBuffer();
//many other commons new's ..
//...
}
Code()
{
NEWLINE = System.getProperty("line.separator");
creation();
}
Code(String name, int numberr)
{
NEWLINE = System.getProperty("line.separator");
creation();
name=new Someting(name);
number = new Magic(number);
}
}
Here is your code with 4 different ways of initializing final variables.
inline
anonymous initializer block
initialized in the constructor
calling the default constructor explicitly
The resulting output is shown below.
public class Code {
// many properties
private String name;
private String number;
// ...
// 1.
final String NEWLINE_1 = "1" + System.getProperty("line.separator");
final String NEWLINE_2;
final String NEWLINE_3;
// 2.
{
System.out.println("initializer block invoked before Constructor");
NEWLINE_2 = "2" + System.getProperty("line.separator");
// final initialization CAN be put here =(
// Source = new StringBuffer();
// many other commons new's ..
// ...
}
Code() {
System.out.println("default constructor");
// NEWLINE_1 = "error"; can't do this
// NEWLINE_2 = "error"; can't do this
// 3.
NEWLINE_3 = "3" + System.getProperty("line.separator");
}
Code(String name, int number) {
// 4.
this();
System.out.println("constructor(name, number)");
name = new String("Someting(name)");
this.number = new String("Magic(number)");
}
public static void main(String[] args) {
Code code_1 = new Code();
System.out.println(code_1.NEWLINE_1 + ":" + code_1.NEWLINE_2 + ":" + code_1.NEWLINE_3);
Code code_2 = new Code("crowne", 2);
System.out.println(code_2.NEWLINE_1 + ":" + code_2.NEWLINE_2 + ":" + code_2.NEWLINE_3);
}
}
initializer block invoked before Constructor
default constructor
1
:2
:3
initializer block invoked before Constructor
default constructor
constructor(name, number)
1
:2
:3
All initializers are added by the compiler to the beginning of each constructor. This includes:
instance variable initialization
initialization blocks { .. }
So you don't have to include this everywhere just place it either as an instance-variable initialization:
private final String NEWLINE = System.getProperty("line.separator");
or in initialization block:
{
NEWLINE = System.getProperty("line.separator");
}
Of course, in this precise example, you should make the field static.
Just do:
final String NEWLINE = System.getProperty("line.separator");
See: JLS 8.3.2. Initialization of Fields.
See also: JLS 12.5 Creation of New Class Instances for execution order.
If they are being initialized the same way every time, you can put the code outside of the constructors. Java allows you to do:
final String NEWLINE = System.getProperty("line.separator");
You can also have all constructors other than the no-argument one call the no-argument constructor. For example:
Code(String name, int number)
{
this();
name=new Someting(name);
number = new Magic(number);
}
One more, if the initialization is complex and you must do it during construction, provide a static method the returns the result, as in:
Code()
{
NEWLINE = newLineValue();
creation();
}
Code(String name, int number)
{
NEWLINE = newLineValue();
creation();
name = new Something(name);
number = new Magic(number);
}
private static String newLineValue()
{
return System.getProperty("line.separator");
}
In this case, newLineValue() is trivial so I wouldn't use it here, but if this actually had a significant amount of work then it could be useful. You can also pass in parameters from the constructor.

Categories