Question

import javax.swing.JoptionPane;

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

      String fn = JOptionPane.showInputDialog("Enter first number");
      String sn = JOptionPane.showInputDialog("Enter second number");

      int num1 = Integer.parseInt(fn);

      int num2 = Integer.parseInt(sn);

      int sum = num1 + num2;

      JOptionPane.showMessageDialog(null,"The answer is " +sum,"the title");
   }
}

Why is it not necessary to create an object in order to use showInputDialog method from the JOptionPane class? Why is null used in showMessageDialog method?

Was it helpful?

Solution

The showMessageDialog method is static and therefore exists on the class not on an instance. Here is a little more explanation about static methods

The first parameter is the parent which specifise relative to which other Frame the OptionPane belongs. If it is null, the OptionPane is independent of any other Frame. See the documentation

> parentComponent - determines the Frame in which the dialog is
> displayed; if null, or if the parentComponent has no Frame, a default
> Frame is used

OTHER TIPS

Because showInputdialog is a static method. It is not logically attached to an object. It is rather a functionality exposed by the class itself.

All methods/variables used in that method are either method scoped or static. JOptionPane.showMessageDialog() for example is static, while num1/num2 are all method scoped.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top