The Wayback Machine - https://web.archive.org/web/20240708003459/https://www.geeksforgeeks.org/dot-operator-in-java/
Open In App

dot(.) Operator in Java

Last Updated : 13 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The dot (.) operator is one of the most frequently used operators in Java. It is essential for accessing members of classes and objects, such as methods, fields, and inner classes. This article provides an in-depth look at the dot operator, its uses, and its importance in Java programming.

Dot(.) Operator in Java

The dot operator is used to access members of a class or an object. It allows us to:

  • Access fields (variables) of a class or an object.
  • Invoke methods of a class or an object.
  • Access inner classes and interfaces.
  • The chain method calls for fluent APIs.

1. Accessing Fields using Dot Operator

The dot operator is used to access the fields (variables) of a class or an object.

Example:

Java
// Java Program to demonstrate dot operator
// Used for Accessing Fields 
class Person {
    String name; 
    int age; 
}

// Driver Class
public class Main {
      // Main Function
    public static void main(String[] args) {
          // Initiate Object
        Person person = new Person(); 
        person.name = "John"; 
        person.age = 30; 
      
          // Using Dot Operator
        System.out.println("Name: " + person.name); 
        System.out.println("Age: " + person.age); 
    }
}

Output
Name: John
Age: 30

2. Invoking Methods using Dot Operator

The dot operator is used to invoke methods of a class or an object.

Example:

Java
// Java Program to demonstrate dot operator
// Used for Invoking Methods
class Person {
    String name;
    int age;

    void introduce() {
        System.out.println("Hello, my name is " + name +
                           " and I am " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
          
          // Using dot operator 
        person.name = "John";
        person.age = 30;
        person.introduce();
    }
}

Output
Hello, my name is John and I am 30 years old.

3. Accessing Inner Classes and Interfaces using Dot Operator

The dot operator can be used to access inner classes and interfaces within a class.

Example:

Java
// Java Program to implement dot operator
// Used for Accessing Inner Classes and Interfaces
class OuterClass {
    class InnerClass {
        void display() {
            System.out.println("This is an inner class.");
        }
    }
}

// Driver Class
public class Main {
      // Main Function
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
      
          // Using dot Operator
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.display();
    }
}

Output
This is an inner class.

4. Chaining Method Calls using Dot Operator

The dot operator allows method chaining, which is a technique used in fluent APIs to call multiple methods in a single statement.

Example:

Java
// Java Program to implement dot operator
// Used for Chaining Method Calls
class Builder {
    private String result = "";

    Builder append(String str) {
        result += str;
        return this;
    }

    String build() {
        return result;
    }
}

// Driver Class
public class Main {
      // Main Function
    public static void main(String[] args) {
        Builder builder = new Builder();
      
          // Using dot Operator
        String result = builder.append("Hello, ").append("world!").build();
        System.out.println(result);
    }
}

Output
Hello, world!

Best Practices and Tips

  • Always initialize objects before accessing their fields or methods to avoid NullPointerException.
  • Use method chaining judiciously to improve code readability and maintainability.
  • Prefer meaningful and descriptive names for fields and methods to enhance code clarity.
  • Encapsulate fields with private access modifiers and provide public getter and setter methods for controlled access.

Conclusion

The dot (.) operator is fundamental to Java programming, enabling access to the members of classes and objects. This article covered various uses of the dot operator, including accessing fields, invoking methods, working with inner classes, and chaining method calls. Understanding and effectively using the dot operator is crucial for writing clean and efficient Java code.

Frequently Asked Questions

1. Can the dot operator be used with primitive types?

No, the dot operator is used only with objects and classes. Primitive types do not have fields or methods.

2. What is method chaining?

Method chaining is a technique where multiple methods are called in a single statement, allowing for a more fluent and readable coding style.

3. How can I avoid NullPointerException when using the dot operator?

Ensure that objects are properly initialized before accessing their fields or methods to avoid NullPointerException.



Previous Article
Next Article

Similar Reads

Double colon (::) operator in Java
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate t
4 min read
Difference between concat() and + operator in Java
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-
6 min read
&& operator in Java with Examples
&& is a type of Logical Operator and is read as "AND AND" or "Logical AND". This operator is used to perform "logical AND" operation, i.e. the function similar to AND gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensiv
1 min read
|| operator in Java
|| is a type of Logical Operator and is read as "OR OR" or "Logical OR". This operator is used to perform "logical OR" operation, i.e. the function similar to OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test fo
1 min read
& Operator in Java with Examples
The & operator in Java has two definite functions: As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false. However, there is a slight difference between them, which h
2 min read
Diamond operator for Anonymous Inner Class with Examples in Java
Prerequisite: Anonymous Inner Class Diamond Operator: Diamond operator was introduced in Java 7 as a new feature.The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable. The diamond operator could not be used with Anonymous inn
2 min read
Shift Operator in Java
Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, >>, <<. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, we will mainly focus on the Shift Operators in Java
4 min read
Left Shift Operator in Java
The decimal representation of a number is a base-10 number system having only ten states 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. For example, 4, 10, 16, etc. The Binary representation of a number is a base-2 number system having only two states 0 and 1. For example, the binary representation of 4, a base-9 decimal number system is given by 100, 10 as 101
4 min read
Addition and Concatenation Using + Operator in Java
Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves the same way as it was supposed to because the decimal system was getting added up deep down at binary level and the resultant binary number is thrown up at console in the generic decimal system. But geeks even wondered what if we play this + ope
2 min read
new Operator vs newInstance() Method in Java
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.In general, the new operator is u
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg