bearste1n
bearste1n

Reputation: 23

How do I make a Public Integer Variable in Java?

I'm a beginner in java, and this code to create a public int variable isn't working:

import java.awt.*;
public class Variable_Practice {
    public static void main (String [] args){
       public int number;

It gives me an error on the word number, and it says illegal parameter for modified number; only final is permitted.

There's probably a really simple answer, but I'm a beginner, so sorry if this is a bad question.

Upvotes: 2

Views: 20987

Answers (4)

Binalfew
Binalfew

Reputation: 1

if a variable is declared inside a method, it doesn't require an access specifier. The variable inside a method is called a local variable and you just declare it like int x, double y... As part of your question, if you want to make your variable public, declare it inside your class, but outside the main method.

public class Variable_Practice {
public int number=2;   // this is the place you decelare public variables 
public static void main (String [] args){

   System.out.println(number);
}

Upvotes: 0

user1804599
user1804599

Reputation:

Local variables cannot have access modifiers (how would they even make sense?).

There are a few different approaches. Which one you need depends on what you want to do.

If you want a single global variable

public class VariablePractice {
    public static int number;

    public static void main(String[] args) {
    }
}

If you want a variable for each instance of VariablePractice

public class VariablePractice {
    public int number;

    public static void main(String[] args) {
    }
}

If you want a variable for each invocation of main

public class VariablePractice {
    public static void main(String[] args) {
        int number;
    }
}

Upvotes: 5

user943716
user943716

Reputation:

You can't make Data Types public inside a method since they run locally inside the method they belong to.

To make the int public you must define it inside your class like so;

 import java.awt.*;
 public class Variable_Practice {
 public int number;

 public static void main (String [] args){

  }
 }

Upvotes: 0

SMA
SMA

Reputation: 37023

public/private/protected is meant at object level and not at method level. You could only use final instead of public in method declaration.

import java.awt.*;
public class Variable_Practice {
public static void main (String [] args){
   final int number = 2;//or something on these lines
   System.out.println(number);
}

Upvotes: 0

Related Questions