Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Analyze the below code and tell what can be printed out on the console. If there

ID: 3578109 • Letter: A

Question

Analyze the below code and tell what can be printed out on the console. If there is any error, please discuss why the below code does not work.

import javafx.beans.property.DoubleProperty;

import javafx.beans.property.SimpleDoubleProperty;

public class BindingDemo { public static void main(String[] args)

{ DoubleProperty d1 = new SimpleDoubleProperty(1);

DoubleProperty d2 = new SimpleDoubleProperty(2);

d1.bind(d2);

d2.setValue(70.2);

d1.setValue(40);

System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); }

}

Explanation / Answer

Please follow the code and comments for description :

CODE :

import javafx.beans.property.DoubleProperty; // required imports
import javafx.beans.property.SimpleDoubleProperty;

public class BindingDemo { // class to run the code

    public static void main(String[] args) { // driver method
        DoubleProperty d1 = new SimpleDoubleProperty(1); // DoubleProperty class to use the code
        DoubleProperty d2 = new SimpleDoubleProperty(2);
        d1.bind(d2); // bind the values
        d2.setValue(70.2); // setting the values
        d1.setValue(40);
        System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue()); // print the data to console
    }
}


OUTPUT :

Exception in thread "main" java.lang.RuntimeException: A bound value cannot be set.
   at javafx.beans.property.DoublePropertyBase.set(DoublePropertyBase.java:143)
   at javafx.beans.property.DoubleProperty.setValue(DoubleProperty.java:75)
   at chegg_1.BindingDemo.main(BindingDemo.java:22)
Java Result: 1


DESCRIPTION :

It is to be noted that the value for the object d2 is binded to the object property of d1. So thus making the values available for the d1 and d2 as the same. So the value that is set to the d2 is available to the object d1. So the value for the d1 again could not be set. This raises the exception as shown above as the output.

NOTE :

Commenting the line (d1.setValue(40);) makes the code run successfully.

Hope this is helpful.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote