Java null pointer exception while calling method in another class - java

I have something similar to:
public class A{
public static B[] bObj;
public A(){
bObj = new B[2]; // create array of objects of class B
}
public static void main(String[] args){
A aObj = new A();
for(i=0;i<2;i++){
bObj[i].testprint();
}
}
}
class B{
public testprint(){
System.out.println("Inside testprint()");
}
}
When I run this, I get NullPointer exception at bObj[i].testprint(). I did do new B() in the constructor of A. But I don't know why it isn't working.

Understand that initializing an array of reference, doesn't really initializes the references inside it. They are still null. You need to initialize them by iterating over the array.
public A(){
bObj = new B[2];
for (int i = 0; i < bObj.length; ++i) { bObj[i] = new B(); }
}

Related

How do I change a variable in one java class from another, then access that changed variable from a third java class?

So say I have 3 java classes, A, B, and C. Class A has an int variable named num that equals 3. I want to be able to change num from class B to another number (for example, 45), then access that variable from class C so that it equals 45. How would I do this?
//First Class
public class A
{
public int num;
public A() {
num = 3;
}
public void setNum(int newNum) {
num = newNum;
}
public int getNum() {
return num;
}
}
//Second Class
public class B
{
public static void main(String[] args) {
A a = new A();
C c = new C();
System.out.println(a.getNum());
a.setNum(45);
System.out.println(a.getNum());
c.printStuff();
}
}
//Third Class
public class C
{
public void printStuff() {
A a = new A();
System.out.println(a.getNum());
}
}
The first two print statements output the expected 3 and 45, but the print statement in the C class still outputs a 3, even though I changed num's value to 45 in class B.
The reason you cann't get the result you want, is that you have created a new instance of class A in class C, and it has its own value, which is 3. Changing the value of the instance of class A which is defined in class B will not effect this new instance.
Note that you called the new method on class A two times so you have two seperate instances.
You can try this code to get the result you want:
//First Class
class A
{
public int num;
public A() {
num = 3;
}
public void setNum(int newNum) {
num = newNum;
}
public int getNum() {
return num;
}
}
//Second Class
public class B
{
public static void main(String[] args) {
A a = new A();
C c = new C();
System.out.println(a.getNum());
a.setNum(45);
System.out.println(a.getNum());
c.printStuff(a);
}
}
//Third Class
class C
{
public void printStuff(A a) {
//A a = new A();
System.out.println(a.getNum());
}
}
Thats happens because in C class you are creating a new instance of A again. So the value would be 3. You can change your constructor and call it like this,
public A(int value) {
num = value;
}
new Post(45);
By this when you create a instance you can assign a value to num as you wish from any class.

Return value to an Object reference

I'm new to Selenium java and currently learning object reference and returns
I was trying to code this logic wherein I declare a non static variable in main class, declare an object for it, use that object in another class and return it to main class
My problem is when i return it back to main class it outputs 0. Is this scenario possible? or am I doing something wrong
package ReturnType;
public class Class1 {
public int Mul(int i, int j) {
Class2 cc = new Class2();
cc.c=i*j;
return cc.c;
}
}
Here is my main class
package ReturnType;
public class Class2 {
public int c;
public static void main(String[] args) {
Class1 xp = new Class1();
Class2 cc = new Class2();
xp.Mul(2,3);
System.out.println(cc.c);
}
}
Almost got the result... the return of the method is getting lost, you have to assign it to something
public class Class2 {
public int c;
public static void main(String[] args) {
Class1 xp = new Class1();
Class2 cc = new Class2();
cc.c = xp.Mul(2,3); //here assign it
System.out.println(cc.c);
}
}

Java : Can I use the thread created on an instance of one class in another class?

I want to use the the thread created on (say) instance x of class A in another class B.
I've stated my problems in better way in the form of comments below.
I have something like this:
Class A implements Runnable{
public static int num;
public void setNum(int i) { num = i; }
public int getNum() { return num; }
public void run(){
while(true){} //I want to keep this thread running continuously
}
}
Class B{
A a;
//I will call this method in class C to use the same instance of class A
public A getInstanceOfA() { return a; }
public static void main(String[] args){
a = new A();
Thread t = new Thread(a);
t.start();
a.setNum(5);
System.out.println(a.getNum()); //getting output as 5. Okay as Expected.
}
}
class C{
A a;
public static void main(String[] args){
a = getInstanceOfA();
System.out.println(a.getNum());
//Here I'm getting output 0 not 5 why? As Thread created on instance a is
//already running, and also I am using the same instance of class A
//so I should get the updated value 5, but getting 0. Why it is re-initializing num?
}
}
Please Help. Thanks.
I am not giving you the exact code but you should do it something like this.
Class B{
A a;
public B(){
initialize();
}
//I will call this method in class C to use the same instance of class A
public A getInstanceOfA() { return a; }
// this method should not be main
public void initialize{
a = new A();
Thread t = new Thread(a);
t.start();
a.setNum(5);
System.out.println(a.getNum()); //getting output as 5. Okay as Expected.
}
}
class C{
A a;
public static void main(String[] args){
B b = new B();
a = b.getInstanceOfA();
System.out.println(a.getNum());
//Here I'm getting output 0 not 5 why? As Thread created on instance a is
//already running, and also I am using the same instance of class A
//so I should get the updated value 5, but getting 0. Why it is re-initializing num?
}
}
You can also use Singleton
http://en.wikipedia.org/wiki/Singleton_pattern

Accessing variable from an inner class - getting null pointer exception

i want to access the arr variable from inside the inner class method MyMethod. When i try to print it from there i end up getting a null pointer exception.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
my = new MyClass();
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
my.arr=n;
}
}
You can use just arr. However until you set it to something it will be null
BTW: Your my = new MyClass() will blow up as it will create objects until it stack overflows.
You haven't initialized it yet, so the reference is null. Initialize it in your constructor for example, and you will have access to the variable via your inner class.
public class MyClass {
String[] arr;
public MyClass (String[] a_arr) {
arr = a_arr;
}
public class MyInner {
public void MyMethod () {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main (String[] args) {
String[] n= {"ddd","f"};
MyClass myClass = new MyClass (n);
}
}
Well, for starters in your main method you never create an instance of your class.
Also, MyClass has a reference to a MyClass object. In the constructor of MyClass, it initializes that reference by calling it's own constructor. That's an endless loop.
Do the following. Your way of initialization is wrong.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
MyClass my=new MyClass();
String[] b = new String[2];
System.arraycopy( n, 0, b, 0, n.length );
}
}
In case of more than 2 strings, simply do String[] b = new String[n.length];

Two questions on inner classes in Java (class A { class B { } })

Sorry for the bad title, but I couldn't think of a better one.
I'm having a class A and a class B which is kind of a sub class of A, like so:
(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
B b = a.new B();
A c = ??? b ??? // get "a" back
}
}
From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.
Second one:
class A {
void print() {
System.out.println("This is class A.");
}
class B {
void print() {
// <--- How to access print() of class A (like this.A.print() or smth)?
System.out.println("This is class B.");
}
}
}
You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.
Thanks in advance. :)
There doesn't seem to be a way to access the outer class from outside. But you can do it like this:
class A {
int i = 0;
class B {
final A outer = A.this;
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = b.outer // get "a" back
}
}
ClassName.this will be the instance of the outerclass associated with the instance of an inner class.
You can access it with the ParentClass.this syntax from within the inner class.
e.g.
public class Outter
{
class Inner {
public Outter getOutter()
{
return Outter.this;
}
}
public Inner getInner(){
return new Inner();
}
}
class Runner{
public static void main(String[] args){
Outter out = new Outter();
Outter.Inner inner = out.getInner();
System.out.println(inner.getOutter().toString());
}
}
[Edit: My answer is appropriate for C# programmers, but I can't guarantee that its applicable to Java.]
B is an inner class, not a subclass of A. Additionally, B does not hold an instance of A, so your code as is cannot return any instance of A.
You need to restructure your classes as follows:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
}
Now your B class has a field 'Parent' which returns its parent. You can use these classes as follows (this is C# syntax, because I don't know if Java has a different syntax for instantiating inner classes):
public static void Main(String[] args)
{
A parent = new A();
A.B child = new A.B(child);
A backToParent = child.Parent;
}
Of course, creating your B class in this way seems little funny: technically, you can pass in any parent. It would probably be better to rewrite your A class with a method which returns a B:
class A
{
public class B
{
public A Parent;
public B(A parent)
{
this.Parent = parent;
}
}
public B getChild()
{
return new B(this);
}
}
public static void Main(String[] args)
{
A parent = new A();
A.B child = A.getChild();
A backToParent = child.Parent;
}
this seemed to work for me
class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = (A)b.getClass().getDeclaredField("this$0").get(b);
}
}

Categories

Resources