Referencing between class Object initialized with null [duplicate] - java

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.
private class Source {
String str;
String getStringValue() {
return str;
}
void setStringValue(String str) {
this.str = str;
}
}
private class UserSource {
Source src;
UserSource(Source src) {
this.src = src;
}
String getValue() {
return src.getStringValue();
}
void setValue(String str) {
src.setStringValue(str);
}
}
Now how I'm using.
Source srcW = new Source();
UserSource userSourceW = new UserSource(srcW);
srcW.setStringValue("Second Value");
System.out.println("From UserSource:" + userSourceW.getValue());
userSourceW.setValue("Is not Second");
System.out.println("From Source:" + srcW.getStringValue());
The output:
From UserSource:Second Value
From Source:Is not Second
But, want to know if is possible to use like:
Source srcN = null; // YES I want to assign Not initialized!
UserSource userSourceN = new UserSource(srcN);
srcN = new Source();
srcN.setStringValue("First Value");
System.out.println("From UserSource:" + userSourceN.getValue());
Of course the output is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Is there an alternative?

Unfortunately, it's not possible to do so. When the value is initially null, then you're passing the null reference. Later you initialize it with srcN = new Source();, but then you're rewriting the source.
You could work around it with a Reference<Source>. But that would only make the code more cumbersome. Moreover, the Source class is a perfect candidate to pass it as an empty source, and then initialize it later with setString().
Am I missing something? What's your problem with the code as is?

Related

Printing ArrayList to an output file [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 2 years ago.
I am trying to print the content of a PriorityQueue to an output file by converting it to an ArrayList.
(NOTE: I'm not printing to the console!)
Besides I declared a toString method, I am still getting the outputs like this: I#7c3df479
Converting the queue to ArrayList:
private PriorityQueue<GameState> unexpanded = new PriorityQueue<>(Comparator.comparing(GameState::getF_n));
...
public ArrayList<GameState> getUnexpanded()
{
ArrayList<GameState> unExpanded = new ArrayList<>(unexpanded);
return unExpanded;
}
Getting the ArrayList and trying it to print:
private void printSolution() throws IOException
{
FileWriter outFile = new FileWriter("output.txt");
PrintWriter output = new PrintWriter(outFile);
ArrayList<GameState> unexpanded = game.getUnexpanded();
for (int i = 0; i < unexpanded.size(); i++)
{
output.printf(unexpanded.get(i).toString() + "\n");
}
output.close();
}
toString method:
public class GameState
{
private int[][] grid;
...
#Override
public String toString()
{
return "{" + grid + "}";
}
}
Everything is working fine but the program print the contents like: I#7c3df479
Can anybody please help me with this?
Many thanks for the answers and comments in advance.
'grid' is declared as a 2D array which isn't a primitive in java. As such, when you try to print it, it still prints out the memory address / reference.
Try replacing it with Arrays.deepToString(grid) instead.

Instantiating a Java Object to the passed Object Reference [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
this is the test code I am using to understand how java handles object memory.
public class TestCode {
public static void main(String[] args) {
TestCode obj = new TestCode();
CustomClass cs1 = new CustomClass(5);
obj.updateExistingObj(cs1);
System.out.println(cs1.val);
CustomClass cs2 = new CustomClass(5);
obj.instantiateExistingObj(cs2);
System.out.println(cs2.val);
CustomClass cs3 = null;
obj.updateNullObj(cs3);
System.out.println(cs3.val);
}
void updateExistingObj(CustomClass cs1) {
cs1.val = 9;
}
void instantiateExistingObj(CustomClass cs2) {
cs2 = new CustomClass(9);
}
void updateNullObj(CustomClass cs3) {
cs3 = new CustomClass(9);
}
}
class CustomClass {
int val;
CustomClass next;
CustomClass(int x) { val = x; }
}
The output of the first syso where I am printing cs1.val I am getting expected value which is 9.
The output of the second syso where I am printing cs2.val I am getting 5 as output instead of 9.
The output of the third syso where I am printing cs3.val I am getting a null pointer exception.
Can anybody help me understand what is happening here under the hood? How exactly java handles the memory location when we pass an object as a function parameter? Thanks for helping!!
cs2 and cs3 are local variable, assigning a new value to them have no effect outside of the methods where they are declared.

Traced reason behind Nullpointerexception. But how do I solve it? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a NullPointerException, I have debugged the code and was able to trace the problem but how do I solve it?
Minimal test case:
ExecutorService theExecutor = Executors.newFixedThreadPool(10000); //Skapar nya Threads, samt begränsar antalet.
ServerSocket quizSocket = new ServerSocket(serverPort);
try {
while (true) { //Skriver ut While True
Socket connection = quizSocket.accept();
theExecutor.execute(new Broadcaster(connection));
}
} finally {
quizSocket.close();
}
}
Broadcaster class. where the problem occurs:
public static class Broadcaster extends Thread {
String quizFile = "src/qa.txt"; // Format of text: Vad heter äventyrets hjälte?/Frodo
private Socket connection;
private PrintStream write;
private String qString;
private String answer;
private String question; // (Debug message) question: null
int points = 0;
public Broadcaster(Socket connection) {
this.connection = connection;
}
#Override
public void run() {
try {
write = new PrintStream(connection.getOutputStream());
//Skriva till klienten.
List<String> questionsList = new ArrayList<>();
try (Stream<String> questionsStream = Files.lines(Paths.get(quizFile))) { //Reading from text file
questionsList = questionsStream
.parallel()
.collect(Collectors.toList());
Collections.shuffle(questionsList); //Randomizing the Strings.
while (true) {
for (String qString : questionsList) {
String[] questions = qString.split("/"); //Splitting to question[0] and [1]
write.println(questions[0]); //Printing out [0]. Has a valid value
question = questions[1].toLowerCase(); //question = null. question[1] "Sam"
The string question is still null, even though question[1] is not. The NullPointerException is a fact! Which means that this variable sets a null value to the getter later on:
public void setQuestion(String question) {
this.question = question;
I want to declare a variable, with the value of question[1].toLowerCasewithout causing a NullPointerException. Then I want to generate a setter with this variable. But how do I do this? In a previous post, I received a duplicate warning and was suggested to follow this tutorial. Now I have done that, and this is what I came up with. Still need advice how to solve the actual problem! Where do I go from here?
For more information, visit this post!
toLowerCase() requires localization information because upper-case to lower-case transformation is locale specific. The parameterlesstoLowerCase() converts to lower case using the rules of the default locale. When there is a problem with the default locale a NullPointerException may be raised.
Use an explicit locale parameter to solve the problem: toLowerCase(Locale.ENGLISH)

What is the meaning of return only in JAVA? [duplicate]

This question already has answers here:
how to explain return statement within constructor?
(6 answers)
Closed 7 years ago.
I don't know what is the usage return;. What does it mean ? Does it return something ? I think return keyword use to put back some value but I am not sure because if constructors return only instance of class below code should be invalid.
public class Test {
public Test() {
return;
}
}
Any suggestions ?
It does not returns anything.
It means the end of any method which returns void, so in this case, it means the end of the constructor. See the example below:
class Test {
private int sum;
public Test(Object otherObj) {
if (otherObj != null){
sum = 42;
return;
}
sum = 0;
}
public static void main(String[] args) {
Test testZero = new Test(null);
Test testNonZero = new Test(testZero);
System.out.println(testZero.sum); // 0
System.out.println(testNonZero.sum); // 42
}
}
if the otherObj is not null, the sum'll be 42, and the constructor will stop running.
You can use the same strategy, if you have a public void someFunction() method, to exit at some point.

Passing a list by reference in Java [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I have a very basic doubt in Java.
Here is a code I have written. From a method in class A in package A, I try to instantiate an object of class b of a different package and call its method, to which I pass a list.
parseObjectList = new ArrayList<ParseObject>();
pullAllService.pullAllData(queryType,parseObjectList);
and in the function I do some manipulation:
public void pullAllData(String queryType,List<ParseObject> parseObjectList)
{
ParseQuery<ParseObject> query = null;
List<ParseObject> parseObjects = parseObjectList;
if(queryType.equals("a"))
{
query = new ParseQuery<ParseObject>("a");
}
else if(queryType.equals("b"))
{
query = new ParseQuery<ParseObject>("b");
}
try {
parseObjects = query.find(); //I get the list
/* final List<ParseObject> finalParseObjectList = parseObjectList;
curActivity.runOnUiThread(new Runnable() {
public void run() {
ToastMessageHelper.displayLongToast(curActivity, "Objects found : ");
for (int i = 0; i < finalParseObjectList.size(); i++) {
ToastMessageHelper.displayLongToast(curActivity, finalParseObjectList.get(i).get("Name").toString());
System.out.println();
}
}
});
*/
} catch (ParseException e) {
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
after which if I try to print the list in class A's method. I get an empty list.
But if I do this,
parseObjectList = new ArrayList<ParseObject>();
parseObjectList = pullAllService.pullAllData(queryType,parseObjectList);
and make it return the list from pullAllData() (by changing the return type and returning the list) , I get the list with the expected data.
I thought that just by passing the parseObjectList into the function, the passed parameter would behave as a reference and automatically be assigned the intended data. What's wrong here?
Java is a pass by value language. Passing a List reference to a method allows the method to mutate the List referenced by the reference, but it can't change the value of the List reference that was passed to it.
You can do something like this to add the elements to the list that was passed to your method :
parseObjectList.addAll(query.find());

Categories

Resources