Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/navs/documentation.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ export const documentationNav = {
pages['continue-statement'],
],
'Java Arrays': [pages['arrays'], pages['multidimensional-arrays']],
'Java OOPS(I)': [pages['class-objects'], pages['methods'], pages['method-overloading'], pages['static-keyword']],
'Java OOPS(I)': [pages['class-objects'], pages['methods'], pages['method-overloading'], pages['static-keyword'], pages['this-keyword']],
}
10 changes: 8 additions & 2 deletions src/pages/docs/method-overloading.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ title: Java Method Overloading
description: In this tutorial, we will learn how to implements methods overloading or function overloading in Java.
---

## Java Method Overloading
import { TipInfo } from "@/components/Tip";

## What is Method Overloading in Java?
In Java, method overloading allows multiple methods with the same name but different parameter lists to coexist in the same class. This can involve variations in the number or types of parameters, or both. Overloaded methods provide flexibility by offering different ways to call a method, depending on the parameters passed.

### Example:
Expand Down Expand Up @@ -114,4 +116,8 @@ class HelperService {
- Overloading is achieved by varying either the number or type of parameters.
- Changing only the return type does not constitute overloading; there must be a parameter difference.

**Tip:** *Constructor overloading in Java works similarly to method overloading.*
<TipInfo>

**Tip:** *Constructor overloading in Java works similarly to method overloading.*

</TipInfo>
60 changes: 35 additions & 25 deletions src/pages/docs/methods.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ title: Java Methods
description: In this tutorial, we will learn how to implements methods or functions in Java.
---

## What is a method in Java?
import { TipInfo } from "@/components/Tip";

## What is a Method in Java?

In Java, a method is a collection of statements designed to perform specific tasks and, optionally, return a result to the caller. A Java method can also execute a task without returning any value. Methods enable code reuse by eliminating the need to retype code. Importantly, in Java, every method must belong to a class.

### Types of Methods in Java
## Types of Methods in Java

- `User-defined Methods`: Custom methods created by the programmer based on specific requirements.
- `Standard Library Methods`: Built-in methods provided by Java, ready for immediate use.

### Declaring a Java Method
## Declaring a Java Method

The basic syntax for a method declaration is:

Expand All @@ -25,7 +27,7 @@ returnType methodName() {
2. **methodName:** The identifier used to call the method.
3. **method body:** Code inside `{ }` that defines the task to be performed.

#### Example 1:
### Example 1:

```java
int addNumbers() {
Expand All @@ -34,7 +36,7 @@ int addNumbers() {
```
In this example, `addNumbers()` is the method name, and its return type is `int`.

#### For a more detailed declaration:
### For a more detailed declaration:

```java
modifier static returnType methodName(parameter1, parameter2, ...) {
Expand All @@ -45,13 +47,13 @@ modifier static returnType methodName(parameter1, parameter2, ...) {
2. **static:** If included, the method can be called without creating an object.
3. **parameter1, parameter2, ...parameterN:** Values passed to the method.

#### Example 2:
### Example 2:
The `sqrt()` method in the Math class is static, so it can be accessed as `Math.sqrt()` without creating an instance of Math.

### Calling a Method in Java
## Calling a Method in Java
To use a method, call it by name followed by parentheses.

#### Java Method Call Example
### Java Method Call Example

```java
class Main {
Expand All @@ -68,26 +70,26 @@ class Main {
}
```

#### Output
### Output

```bash
Sum is: 40
```

Here, the `addNumbers()` method takes two parameters and returns their sum. Since it's not static, it requires an object to be called.

### Method Return Types
## Method Return Types
A method may or may not return a value. The return statement is used to return a value.

#### Example 1: Method returns integer value
### Example 1: Method returns integer value

```java
public static int square(int num) {
return num * num;
}
```

#### Example 2: Method does not return any value
### Example 2: Method does not return any value

```java
// void keyword is used as function does not return any value
Expand All @@ -96,16 +98,16 @@ public void printSquare(int num) {
}
```

### Method Parameters
## Method Parameters
Methods can accept parameters, which are values passed to the method.

#### Examples
### Examples
- **With Parameters:** `int addNumbers(int a, int b)`
- **Without Parameters:** `int addNumbers()`

When calling a method with parameters, you must provide values for each parameter.

#### Example of Method Parameters
### Example of Method Parameters
```java
class Main {
public void display1() {
Expand All @@ -123,32 +125,39 @@ class Main {
}
}
```
#### Output
### Output

```bash
Method without parameter
Method with a single parameter: 24
```
**Note:** Java requires that argument types match the parameter types.

### Standard Library Methods
Java includes built-in methods available in the Java Class Library (JCL), which comes with the JVM and JRE.
<TipInfo>

**Note:** *Java requires that argument types match the parameter types.*

</TipInfo>

#### Example
## Standard Library Methods
Java includes built-in methods available in the Java Class Library (JCL), which comes with the [JVM and JRE](/docs/jvm-jre-jdk).

### Example
```java
public class Main {
public static void main(String[] args) {
System.out.println("Square root of 4 is: " + Math.sqrt(4));
}
}
```
#### Output
### Output
```bash
Square root of 4 is: 2.0
```

### Advantages of Using Methods
**Code Reusability:** Define once, use multiple times.
## Advantages of Using Methods
### 1. Code Reusability
Define once, use multiple times.

```java
private static int getSquare(int x) {
return x * x;
Expand All @@ -159,7 +168,7 @@ public static void main(String[] args) {
}
}
```
#### Output:
### Output:

```bash
Square of 1 is: 1
Expand All @@ -169,4 +178,5 @@ Square of 4 is: 16
Square of 5 is: 25
```

**Improved Readability:** Grouping code into methods makes it easier to read and debug.
### 2. Improved Readability
Grouping code into methods makes it easier to read and debug.
176 changes: 176 additions & 0 deletions src/pages/docs/this-keyword.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
---
title: Java this keyword
description: In this tutorial, we will learn the use of 'this' keyword in Java.
---

## What is 'this' keyword in Java?
In Java, the `this` keyword is used within a class to refer to the current instance (object) of that class. It’s commonly used in methods or constructors to reference the current object’s properties or to call other constructors within the same class.

### Example
```java
class Main {
int instVar;

Main(int instVar) {
this.instVar = instVar;
System.out.println("this reference = " + this);
}

public static void main(String[] args) {
Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}
```
### Output
```bash
this reference = Main@23fc625e
object reference = Main@23fc625e
```
In this example, `this` refers to the `obj` instance of Main. Both `this` and `obj` share the same memory reference, indicating that this represents the current object.

## Common Uses of the this Keyword

### 1. Resolving Variable Name Conflicts

When instance variables and parameters have the same name, using `this` helps to avoid ambiguity:

```java
class MyClass {
int age;

MyClass(int age) {
this.age = age; // Uses `this` to differentiate instance variable from parameter
}
}
```
Without `this`:

```java
class Main {
int age;
Main(int age) {
age = age; // No `this`, so no assignment to the instance variable
}

public static void main(String[] args) {
Main obj = new Main(8);
System.out.println("obj.age = " + obj.age); // Output: obj.age = 0
}
}
```
### 2. Using this with Getters and Setters

`this` is often used in setter methods to differentiate between instance variables and parameters:

```java
class Main {
String name;

void setName(String name) {
this.name = name;
}

String getName() {
return this.name;
}

public static void main(String[] args) {
Main obj = new Main();
obj.setName("Toshiba");
System.out.println("obj.name: " + obj.getName());
}
}
```
### Output
```bash
obj.name: Toshiba
```

### 3. Constructor Overloading with this()
In constructor overloading, `this()` can be used to call another constructor within the same class, reducing code duplication:

```java
class Complex {
private int a, b;

// Constructor with two parameters
Complex(int i, int j) {
this.a = i;
this.b = j;
}

// Single parameter constructor calls two-parameter constructor
Complex(int i) {
this(i, i);
}

// No-argument constructor calls single-parameter constructor
Complex() {
this(0);
}

@Override
public String toString() {
return this.a + " + " + this.b + "i";
}

public static void main(String[] args) {
Complex c1 = new Complex(2, 3);
Complex c2 = new Complex(3);
Complex c3 = new Complex();

System.out.println(c1); // Output: 2 + 3i
System.out.println(c2); // Output: 3 + 3i
System.out.println(c3); // Output: 0 + 0i
}
}
```
Here, `this()` helps to manage multiple constructors, improving readability and reducing code duplication. However, it should be used carefully, as excessive use can slow down the program.

### 4. Passing this as an Argument
You can use `this` to pass the current object as an argument to other methods:

```java
class ThisExample {
int x;
int y;

ThisExample(int x, int y) {
this.x = x;
this.y = y;

System.out.println("Before passing this:");
System.out.println("x = " + this.x + ", y = " + this.y);

add(this);

System.out.println("After passing this:");
System.out.println("x = " + this.x + ", y = " + this.y);
}

void add(ThisExample obj) {
obj.x += 2;
obj.y += 2;
}

public static void main(String[] args) {
ThisExample obj = new ThisExample(1, -2);
}
}
```
### Output

```bash
Before passing this:
x = 1, y = -2
After passing this:
x = 3, y = 0
```
In this example, `this` allows the `add()` method to modify the current instance variables directly.

## Key Points
- **Variable Disambiguation:** `this` resolves conflicts when instance variables and parameters share the same name.
- **Getters and Setters:** `this` is often used in setters to distinguish instance variables.
- **Constructor Overloading:** `this()` can call other constructors within the same class, helping to reduce code redundancy.
- **Passing Current Object:** `this` allows you to pass the current object as a method argument, enabling modifications on the current instance.