Menu Close

Declaring Variable outside main [Java]

Declare a protected static variable outside the main and increment the variable inside a function which is called inside the main and the incremented value returned should be displayed as output.

Input:  699

Output:  700
import java.io.*;
import java.util.*;
public class temp{

  protected static int X;

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    temp obj = new temp();

    System.out.println("Enter a number:  ");
    obj.X = scan.nextInt();

    int Y = obj.variable();
    System.out.println(Y);
  }

  public int variable(){
    return X+1;
  }

}

INPUT_1:
Enter a number:
99

OUTPUT:
100


INPUT_2:
Enter a number:
56

OUTPUT:
57


INPUT_3:
Enter a number:
7

OUTPUT:
8


INPUT_4:
Enter a number:
5

OUTPUT:
6


INPUT_5:
Enter a number:
20

OUTPUT:
21


ILLUSTRATION

Executed using javac Linux Terminal

Leave a Reply

Your email address will not be published. Required fields are marked *