1. Access Modifiers

Access modifiers are keywords in Java that control who can access a class, variable, method, or constructor.

Java has four access levels:

The main purpose is to control visibility and access.

For example:

class Student {

    public String name;
    private int age;
}

Here, name can be accessed from outside the class, but age cannot be accessed directly from outside because it is private.


2. public

public means the member is accessible from anywhere, provided the containing class itself is accessible.

class Student {

    public String name;

    public void display() {
        System.out.println(name);
    }
}

From another class:

Student s = new Student();

s.name = "Rahul";
s.display();

Both are accessible because they are public.

Syntax

public dataType variable;

public returnType method() {
}