user2443943
user2443943

Reputation: 112

What is the purpose of Java DOT operator?

Can somebody tell me what Java DOT operator actually does?

For example:

public class {
    int value;
    public void great() {};
    ... 
}
public static void main(String[] args) {

    Person p = new Person();

    Person.great(); // <--- here

    Person.value; // <--- here

I want to know what is . operator doing in above code when I do Person.great() or Person.value?

Upvotes: 4

Views: 37451

Answers (3)

Anatolii
Anatolii

Reputation: 11

Simply the dot operator acts as an access provider for objects and classes. The usage of the above operator is as below.

It separates a function and variable from an instance variable. It allows accessing sub-packages and classes from a package. It leads to access to the member of a class or a package.

public class DotOperatorExample1 {
        
void display() { 
        double d = 67.54;    
        int i = (int)d;  
        System.out.println(i);  
    }  
public static void main(String args[]) {  
        DotOperatorExample1 doe = new DotOperatorExample1();   
        doe.display();
    }  
}  

Upvotes: 1

Karthik Reddy V V
Karthik Reddy V V

Reputation: 82

The dot operator, also known as separator or period used to separate a variable or method from a reference variable.

Only static variables or methods can be accessed using class name.

Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name as in

objectReference.fieldName

We use the object reference to invoke an object's method. Append the method's simple name to the object reference, with an intervening dot operator (.) as in

objectReference.methodName(argumentList);

In the above mentioned code, p.great() can be used to invoke the method great() on object p and p.value is used to access the instance variable value.

Ref: https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html

The Complete Reference, Book by Herbert Schildt

Upvotes: 5

Johannes H.
Johannes H.

Reputation: 6167

. is not an operator. Therefore, it "does" nothing.

It is just a syntactic element that denotes the seperation of, in this case, a variable name holding an object and the object's property. The same character is used to seperate package names and Classes.

Upvotes: 1

Related Questions