The public keyword in Java programming language

The public keyword in Java programming language

In this tutorial, we will learn about The public keyword in java programming language

public is a  keyword and an access modifier In the Java programming language. It is used for member’s to access as public. This keyword can be used to define a class, a method or a variable.

when a class is marked as public, it can be accessed from out side classes.

 

Public class

Syntax

the syntax of the public keyword in java when defining the class

<access modifier> <class> <class_name>{

}

Example

public class student{

}

 

when a method is marked as public, it can be executed from anywhere. Execution is possible from the own class and other classes.

Public method

Syntax

the syntax of the public keyword in java when defining the method

<access modifier> <Variable_type> <method_name>();

Example

public int run();

// this is the public method. It can be invoked from within the class and other classes.

 

When a variable is marked as public, it can be used and accessed from enclosing class and outside classes.

public variable

Syntax

syntax of public keyword in java when define variable

<access modifier> <Variable_type> <variable_name>;

 

Example

public String stu_name;

//   this is public variable. It can be invoked from witin class and other classes.

The following code example shows a public class patient which has a public method move () and public variable disease.

 

public class Patient{  //public class

public string disease;  //public variable

public void move(){     //public method

}

}

Example

class pub_key{
public void message(){
System.out.println("Welcome to java");
}

}
//save by pub_key.java
public class pub_use{
public static void main(String args[]){
pub_key obj=new pub_key();
obj.message();

}

}

When this code is executed, it produced the following result

welcome to Java

 

There are other Java language keywords that are similar to this keyword

 byte  in Java Language

 int  in Java Language

long  in Java Language

 float  in Java Language

char  in Java Language

 void  in Java Language

try  in Java Language

Catch in Java Language

implements  in java Language

public  in Java Language

static  in Java language

Volatile  in Java Language

Package  in Java Language

class  in Java Language

boolean  in Java Language

break in Java Language

do  in Java Language

double  in Java Language

This  in Java Language

final  in Java Language

switch  in Java Language

interface  in Java Language

extends  in Java language

 

Suggested for you

 Java language Keywords

C language Keywords

 Python language Keywords

keywords in C language

Finally  in Java language

 

The break keyword in Java programming language
The private keyword in Java programming language
keyword in Java