copy constructor clarification needed - java

public class CopyConstructorEx
{
String web, webb;
CopyConstructorEx(String w){
web = w; }
CopyConstructorEx(CopyConstructorEx je){
webb = je.web; }
void disp(){
System.out.println("Website: "+web); }
public static void main(String args[]){
CopyConstructorEx obj1 = new CopyConstructorEx("BeginnersBook");
CopyConstructorEx obj2 = new CopyConstructorEx(obj1);
obj1.disp();
obj2.disp();
}
}
output:
Website: BeginnersBook
Website: null
Can anyone explain why second output is null?

web being a string type variable is null by default. In your copy constructor, you aren't assigning anything to it, so there's no reason for it to change.

Related

Static class fields in construction

// package and import things..
public class A {
public int x;
public static A ob;
A() {
A.ob.x = 5;
}
public static void main(String args[) {
A.ob = new A();
System.out.println(ob.x);
}
}
Why this code is give NullPointerException ? If i change "A.ob.x" to "this.x", it's done. But already A.ob = this in this code?
A.ob = new A();
This first creates an A by executing the constructor, and then, assigns the created A to A.ob. It's basically equivalent to
A tmp = new A();
A.ob = tmp;
So, at the time the constructor is called, A.ob is still null. So you get a NullPointerException.

Why is this snippet not giving a run time error as stated in the Java Tutorials documentation?

public class Box {
private Object object;
public void set(Object object) { this.object = object; }
public Object get() { return object; }
}
With reference to this text from the official Java tutorials docs and the above snippet, I tried to reproduce the runtime error. What is wrong with my code since it is not producing any runtime error?
Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.
The code that I wrote.
public class Box {
private Object obj;
public void set(Object obj) {
this.obj = obj;
}
public Object get() {
return obj;
}
public static void main(String [] args) {
Box g = new Box();
System.out.println(g.get());
g.set("hello again");
System.out.println(g.get());
}
}
public static void main(String[] args) {
Box g = new Box();
g.set("hello again");
Integer i = (Integer) g.get();
System.out.println(i + 1);
}
This code passes in a String, but attempts to retrieve an Integer. The compiler can't detect that this will fail. At runtime it throws a ClassCastException.
You are misunderstanding the example. It is not saying that passing in a String will result in an error. It is saying that passing in an String will result in an error when another part of the program is expecting to get an Integer.
For example:
public static void main(String [] args) {
Box g = new Box();
g.set("hello again");
Integer error = (Integer) g.get();
}
will result in an error.
It wont produce any run time error because, Every String is an Object.
It gives you the error when you try to Assign the object retrieved by get to some other Object of different type.
for ex:
g.set("hello again");
Integer i = (Integer) g.get(); // getting string and trying to cast it to integer.

Unable to create new object

I created these two files in java and they don't compile. This error comes up:
cannot find symbol C02FootprintV1".
Why doesn't the program recognize the object? I am new to this.
How could I fix this problem?
public class CO2FootprintV1 {
private double myGallonsUsed;
private double myTonsCO2;
private double myPoundsCO2;
CO2FootprintV1(double gals) {
myGallonsUsed = gals;
}
public void calcTonsCO2() {
myTonsCO2 = myGallonsUsed * 0.878;
}
public double getTonsCO2() {
return myTonsCO2;
}
public void convertTonsToPoundsCO2() {
myPoundsCO2 = myTonsCO2 * 220462262;
}
public double getPoundsCO2() {
return myPoundsCO2;
}
}
public class CO2FootprintV1Tester {
public static void main(String[] args) {
double gals;
double tonsCO2, poundsCO2;
gals = 1300;
CO2FootprintV1 object = new C02FootprintV1(gals);
object.calcTonsCO2();
tonsCO2 = object.getTonsCO2();
object.convertTonsToPoundsCO2();
poundsCO2 = object.getPoundsCO2();
}
}
On the line
CO2FootprintV1 object = new C02FootprintV1(gals);
you have C02 (see zero two) on the right hand side, you meant for it to be
CO2FootprintV1 object = new CO2FootprintV1(gals);
or CO2 (see oh two). Also, you should consider that the error messages your tools give you might be correct.
Just change:
CO2FootprintV1 object = new C02FootprintV1(gals);
to:
CO2FootprintV1 object = new CO2FootprintV1(gals);
That's why it is important to have good naming practice.
You put a "0" (cero) instead of an "O" (letter):
CO2FootprintV1 object = new C02FootprintV1(gals);
Try this:
CO2FootprintV1 object = new CO2FootprintV1(gals);

Call data from a string array to another class

public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}

Null reference in java

I have a piece of code for which i have to know how memory is allocated
public class Demo {
public void checkNullReference(){
ConsumerName name = null;
addReference(name);
System.out.println(name.getConsumerName());
}
public void addReference(ConsumerName name){
name = new ConsumerName();
name.setConsumerName("KRISHNA");
}
public static void main(String []args){
Demo demo = new Demo();
demo.checkNullReference();
}
}
The code is giving null pointer exception i have given a refrence of object to method and there i am allocating new object to it and setting name if i rewrite the method then every thing is working as expected.
public void checkNullReference(){
ConsumerName name = new ConsumerName();
addReference(name);
System.out.println(name.getConsumerName());
}
You cannot change a reference in a calling method from the called method. Thus, with this code:
public void checkNullReference(){
ConsumerName name = null;
addReference(name);
System.out.println(name.getConsumerName());
}
name will still be null after the call to addReference(name), regardless of what addReference does with its formal argument.
You can redesign addReference to return an instance of ConsumerName. While you're at it, you can delete the argument, since it is ignored. The result could be:
public void checkNullReference(){
ConsumerName name = addReference();
System.out.println(name.getConsumerName());
}
public ConsumerName addReference(){
ConsumerName name = new ConsumerName();
name.setConsumerName("KRISHNA");
return name;
}
You are calling addReference() method with a null as input so .. there is no pass by reference happening and ConsumerName is newly getting allocated with in addReference() its scope will remain with in the method only. So you modify your code to return the new instance of ConsumerName .
public class Demo {
public void checkNullReference(){
ConsumerName name = null;
name = addReference(name);
System.out.println(name.getConsumerName());
}
public ConsumerName addReference(ConsumerName name){
name = new ConsumerName();
name.setConsumerName("KRISHNA");
return name ;
}
public static void main(String []args){
Demo demo = new Demo();
demo.checkNullReference();
}
}
Always remember, java uses pass-by-value. When you do
name = new ConsumerName();
name.setConsumerName("KRISHNA");
it just simply creates a new local object which locate inside addReference function stack. So, as soon as the function returned, you lost that object. In another word, your ConsumerName object inside checkNullReference is not the same as the ConsumerName object inside AddReference.

Categories