Attempt to invoke virtual method on a null object reference issue [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am developing an App which uses the following code. It is generating an unexpected error as "Attempt to invoke virtual method on a null object reference". I do not understand the reason why this is happening. The error is thrown as the line containing t[i].setTestname(getData(exams[i]));. Could someone please point out what I am doing wrong. Could use some help over here.
void processTestPerformance()
{
String exams[],rawdata;
rawdata=data.toString();
int numberoftests=getNumbers("tabletitle03",rawdata);
Tests[] t= new Tests[numberoftests];
exams=new String[numberoftests];
rawdata=rawdata+"tabletitle03";
for(int i=0;i<numberoftests;i++)
{
int j=rawdata.indexOf("tabletitle03");
int k=(rawdata.substring(j+1)).indexOf("tabletitle03");
exams[i]=rawdata.substring(j,j+1+k);
t[i].setTestname(getData(exams[i]));
rawdata=rawdata.substring(k);
}
}
The code for class Tests is as follows:
public class Tests
{
public int numberofsubjects;
public String testname;
public Subject s[];
public void setS(Subject[] s)
{
this.s = s;
}
public void setNumberofsubjects(int numberofsubjects)
{
this.numberofsubjects = numberofsubjects;
s=new Subject[numberofsubjects];
}
public void setTestname(String testname)
{
this.testname = testname;
}
}
Thanks in Advance.

You create an empty array of Tests class, of size numberoftests
If you look inside that array you will find a sequence of null. Because you never initialize it.
You just need to populate the array so that t[i] will return an instance of your class.
In your for-cycle you can for example use the default constructor:
t[i] = new Tests();
// now you can manipulate the object inside the array
t[i].etTestname(getData(exams[i]));

for(int i=0;i<numberoftests;i++)
t[i]=new Tests();
That solved my problem.

Related

How to print content of an object [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
How to override toString() properly in Java?
(15 answers)
Closed 2 years ago.
I'm trying to fetch a list from MySQL on android but I'm getting
[com.trycatchsoft.app.Models.KatPojo#7553fa]
as output instead of list.
Here is my pojo file:
package com.trycatchsoft.app.Models;
public class KatPojo {
private Boolean tf;
private String veri;
private String verid;
public Boolean getTf() {
return tf;
}
public void setTf(Boolean tf) {
this.tf = tf;
}
public String getVeri() {
return veri;
}
public void setVeri(String veri) {
this.veri = veri;
}
public String getVerid() {
return verid;
}
public void setVerid(String verid) {
this.verid = verid;
}
}
By default, printing an Object results in a class name and hash code. One can change this result by overriding the toString() method inherited by all children of Object.
When you're working with the Object type, you need to override the toString() method and call this method if you want to get the string representation of this object.
you can also use https://github.com/google/gson
If you are debugging I find it easy to just print the json instead of writing toString. You can pass your object or an array of objects.
Gson GSON = new GsonBuilder().setPrettyPrinting().create();
System.out.println(GSON.toJson(<PASS YOUR OBJECT REFERENCE HERE>));

How null object can still return its property value? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Below is my code. I set the object to null, still my print statement can print the property name correctly. Can anyone tell me what's happening?
public class MyClass {
String name;
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.changeName(obj);
System.out.println("Name = " + obj.getName());
}
public MyClass() {
name = "A";
}
public void changeName(MyClass obj) {
obj.setName("B");
obj = null;
}
}
Output is:
Name = B
obj = null only sets the local variable obj of the method changeName to null. It doesn't affect the object referenced by that variable in any way.
I apologize if this incorrect, I have been working with Kotlin lately and it’s messing with my head.
I would try either
public void changeName(MyClass obj) {
obj.setName("B");
obj.setName(null);
}
Or you might try
public void changeName(MyClass obj) {
obj.setName("B");
obj.setName().empty;
}
I think it has something to do with the fact your passing an object to that method and setting the value of the object and the null must be either nulling the incorrect object or the setName value is still holding its value even though the object itself is null. So you need to set the setName value to null I think.

A final variable points to an instance. Can the instance become null? [duplicate]

This question already has answers here:
What is the difference between a variable, object, and reference? [duplicate]
(5 answers)
Closed 6 years ago.
A final variable points to an instance. I wanted to see what would happen if I changed the reference of the object to null. I am very surprised that there is no exception nor "is null" printed out. It is as if the line of code a = null; has been ignored.
output:
myFoo.name? haha
public class TryJava {
class InnerFoo {
public InnerFoo(String name) {
super();
this.myName = name;
}
String myName;
boolean isStarted;
}
InnerFoo a = new InnerFoo("haha");
final InnerFoo myFoo = a;
void bar() {
a = null; // IGNORED???
System.out.println("myFoo.name? " + (myFoo != null ? myFoo.myName : " is null "));
}
public static void main(String[] args) {
TryJava tj = new TryJava();
tj.bar();
}
}
You changed what a refers to, sure. But myFoo still refers to an instance.
There is no exception because final variable myFoo is still references to InnerFoo("haha") even thought refrence a is point to null.For example:at first variable a is refrencing to InnerFoo("haha').Then variable myFoo is refrence to same Instance InnerFoo('haha') by using refrence 'a'.When refrence 'a' assign null;myFoo is still refrencence to the InnerFoo('haha').please study about how object refrence work.

Non-static method referenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I have two errors both the same and they follow below:
class FBox {//...}
class FBPlayer
{
//Initialized instances
FBox game = new FBox();
**FBPillar pillar = new FBPillar();**
**FBObjects objects = new FBObjects();**
//Lots o Properties...
public boolean get_Alive() { return this.b_PlayerAlive; }
public void set_Alive(boolean alive) { this.b_PlayerAlive = alive; }
//My Error ridden Method
public void checkCollision()
{
if(get_YPos() >= **objects**.get_Ground())
^My Error was incorrect name for my instance
{
set_Alive(false);
}
else if(get_Bounds().intersects(**pillar**.get_Bounds()))
^My Error was incorrect name for my instance
{
set_Alive(false);
}
}
class FBPillar
{
public int get_Bounds() {return 'the variable'; }
}
class FBObjects
{
public int get_Ground() {return 'the variable'; }
}
The error is in the if statement as well as the else if statement
When i run it it returns the error:
FBox.java:178: error: non-static method get_Bounds() cannot be referenced from a static context
else if(get_Bounds().intersects(**FBPillar**.get_Bounds()))
The same error for the if statement but with FBObjects.get_Ground())
^
Whose bounds are you talking about? You probably mean
if (get_Bounds().intersects(pillar.get_Bounds())) {
…
}
I'd also add that
FBPlayer player = new FBPlayer();
means that a player contains a player, which is probably isn't what you intended.

Error: 'void' type not allowed here [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}

Categories