DEV Community

Vigneshwaralingam
Vigneshwaralingam

Posted on

Java Day 6: Return Data Types, Methods, and this Keyword.

Return Data Types in Java

  • Definition: The return data type specifies the type of value a method will return.
  • Types of Return Data Types:
    • void → No return value
    • Primitive types → int, float, char, etc.
    • Non-primitive types → String, Array, Class Object, etc.
  • Example:
 class Example { int add(int a, int b) { // Method returning an int return a + b; } } 
Enter fullscreen mode Exit fullscreen mode

How to Create Methods

Method Definition

  • A method is a block of code designed to perform a task.
  • Syntax:
 returnType methodName(parameters) { // Method body return value; // (if returnType is not void) } 
Enter fullscreen mode Exit fullscreen mode
  • Example:
 class Example { void display() { // Method with no return value System.out.println("Hello World"); } } 
Enter fullscreen mode Exit fullscreen mode

this Keyword in Java

  • Definition: this refers to the current instance of a class.
  • When to Use this?
    • To differentiate between instance variables and parameters with the same name.
    • To call another constructor in the same class.
    • To return the current class instance.
  • Example:
 class Example { int num; Example(int num) { this.num = num; // Using `this` to refer to instance variable } } 
Enter fullscreen mode Exit fullscreen mode
  • When NOT to Use this?
    • In static methods (since static methods belong to the class, not an instance).
    • Outside non-static methods.

Global Elements in Java

Variables

  • Static Variables (shared across all objects, belongs to the class)
 class Example { static int count = 0; } 
Enter fullscreen mode Exit fullscreen mode
  • Non-Static Variables (unique to each object)
 class Example { int id; } 
Enter fullscreen mode Exit fullscreen mode

Methods

  • Static Methods (can be called without an object)
 class Example { static void show() { System.out.println("Static method"); } } 
Enter fullscreen mode Exit fullscreen mode
  • Non-Static Methods (requires an object to be called)
 class Example { void show() { System.out.println("Non-static method"); } } 
Enter fullscreen mode Exit fullscreen mode

Why Do We Need Methods?

  • Code Reusability: Avoid repeating code.
  • Modular Structure: Divides the program into smaller, manageable parts.
  • Readability & Maintainability: Improves program clarity and debugging efficiency.

This covers return data types, method creation, this keyword, global variables/methods, and why methods are essential🚀

Top comments (0)