Search code examples
javadatestatic-variables

Change the value of static variable


I want to set the variable of the monthBtn, and by calling a function it will change the variable of the month.

private static String monthBtn;

    public static String getCurrentMonth() {
        int month = Calendar.getInstance().get(Calendar.MONTH);
        String monthBtn= "//*[@text='"+month+"']";
        System.out.println(yearBtn);
        return monthBtn;
    }
    public static void main(String[] args) {
        getCurrentMonth();
        System.out.println("Xpath Year ="+monthBtn);
    }

When I ran this code the value of variable monthBtn return null value, but my expect condition is //*[@text='07']


Solution

  • I see 3 problems with your code.

    1. the "month" that Calendar.get(MONTH) returns is not the numeric month, but one of the constants defined in Calendar class. For example, for the month of JULY it returns 6. You should ideally migrate to using the modern classes defined in java.time, such as LocalDate, that don't behave in surprising ways.
    2. Formatting. An int does not have leading zeros. But you can use String.format to zero-pad it.
    3. Variable visibility. You are declaring a local monthBtn variable that hides the static variable with the same name.

    You can get around these problems by changing the code in your method to:

        int month = LocalDate.now().getMonthValue();
        monthBtn = String.format("//*[@text='%02d']", month);