DEV Community

Cover image for Java Basics
Harsh Mishra
Harsh Mishra

Posted on • Updated on

Java Basics

Java

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating Variables

In Java, variables are containers that hold data that can be manipulated within a program. Here's a comprehensive guide on creating and working with variables in Java:

Syntax for Variable Declaration and Initialization

Declaration:

type variableName;
Enter fullscreen mode Exit fullscreen mode
int number;
String name;
Enter fullscreen mode Exit fullscreen mode

Initialization:

variableName = value;
Enter fullscreen mode Exit fullscreen mode
number = 10;
name = "John";
Enter fullscreen mode Exit fullscreen mode

Declaration and Initialization Combined:

type variableName = value;
Enter fullscreen mode Exit fullscreen mode
int age = 25;
double salary = 50000.0;
Enter fullscreen mode Exit fullscreen mode

Rules for Variable Names

  1. Variable names must start with a letter, underscore (_), or dollar sign ($).
  2. Subsequent characters can be letters, digits, underscores, or dollar signs.
  3. Variable names are case-sensitive (myVar and myvar are different).
  4. Variable names cannot be Java reserved keywords (e.g., int, class, void).

Examples:

int age;
String $name;
double _salary;
int year2024;
Enter fullscreen mode Exit fullscreen mode

Variable Scope

The scope of a variable is the part of the program where the variable is accessible. Variables can be:

  • Local Variables: Declared inside a method and accessible only within that method.
  • Instance Variables (Non-static fields): Declared inside a class but outside any method. They are unique to each instance of a class.
  • Class Variables (Static fields): Declared with the static keyword inside a class. They are shared among all instances of a class.

Example:

public class MyClass {
    // Instance variable
    int instanceVar = 10;

    // Class variable
    static int classVar = 20;

    public void myMethod() {
        // Local variable
        int localVar = 30;
        System.out.println(localVar);
    }
}
Enter fullscreen mode Exit fullscreen mode

Constants

Constants are variables whose values cannot be changed once assigned. They are declared using the final keyword.

Example:

final int DAYS_IN_WEEK = 7;
final double PI = 3.14159;
Enter fullscreen mode Exit fullscreen mode

Default Values

Uninitialized variables have default values:

  • Primitive types: Numeric types default to 0, char defaults to '\u0000', and boolean defaults to false.
  • Reference types: Default to null.

Example:

public class MyClass {
    int num;  // default value 0
    boolean bool;  // default value false
    String str;  // default value null
}
Enter fullscreen mode Exit fullscreen mode

Declare Many Variables with or without Values

You can declare multiple variables of the same type in a single line, separating them with commas. You can also initialize them either at the time of declaration or later.

Examples:

// Declaring multiple variables without values
int a, b, c;

// Declaring and initializing some variables
int x = 10, y, z = 30;
Enter fullscreen mode Exit fullscreen mode

One Value to Multiple Variables

You can assign the same value to multiple variables by chaining the assignment operator.

Example:

int m, n, o;
m = n = o = 50;
Enter fullscreen mode Exit fullscreen mode

Creating Comments

Comments in Java are non-executable statements that are used to describe and explain the code. They are essential for making the code more readable and maintainable. Java supports three types of comments:

1. Single-Line Comments

Single-line comments start with two forward slashes (//). Everything following // on that line is considered a comment.

Syntax:

// This is a single-line comment
int x = 10; // x is initialized to 10
Enter fullscreen mode Exit fullscreen mode

2. Multi-Line Comments

Multi-line comments start with /* and end with */. Everything between /* and */ is considered a comment, regardless of how many lines it spans.

Syntax:

/*
 This is a multi-line comment.
 It can span multiple lines.
*/
int y = 20; /* y is initialized to 20 */
Enter fullscreen mode Exit fullscreen mode

Basic Input and Output in Java

Input and output (I/O) operations are fundamental in Java for interacting with users, reading data from files, and displaying results. Here's a comprehensive guide on performing basic I/O operations in Java:

1. Output (Printing to Console)

To display output on the console, Java uses the System.out.println() method from the System class. This method prints the string representation of the given data to the standard output (usually the console) followed by a newline.

Syntax:

System.out.println("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

Example:

int number = 10;
System.out.println("The number is: " + number);
Enter fullscreen mode Exit fullscreen mode

2. Formatting Output

Java provides various ways to format output using printf() method from System.out:

Syntax:

System.out.printf("Formatted string", arguments);
Enter fullscreen mode Exit fullscreen mode

Example:

String name = "Alice";
int age = 30;
System.out.printf("Name: %s, Age: %d%n", name, age);
Enter fullscreen mode Exit fullscreen mode

3. Input (Reading from Console)

To read input from the console, you can use the Scanner class from the java.util package. First, create a Scanner object associated with System.in, then use its methods to read different types of input.

Syntax:

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
Enter fullscreen mode Exit fullscreen mode

Examples:

  • Reading Strings:
  System.out.print("Enter your name: ");
  String name = scanner.nextLine();
Enter fullscreen mode Exit fullscreen mode
  • Reading Integers:
  System.out.print("Enter your age: ");
  int age = scanner.nextInt();
Enter fullscreen mode Exit fullscreen mode
  • Reading Floating-Point Numbers:
  System.out.print("Enter the price: ");
  double price = scanner.nextDouble();
Enter fullscreen mode Exit fullscreen mode

4. Closing Scanner

After finishing input operations, close the Scanner to release the resources associated with it.

Example:

scanner.close();
Enter fullscreen mode Exit fullscreen mode

Certainly! Here's the updated explanation including the example class definition with an object instantiation in Java:

Data Types in Java

Java is a statically-typed language, meaning all variables must be declared before they can be used, and each variable must be declared with a data type. Java provides two categories of data types:

1. Primitive Data Types

Primitive data types are the most basic data types in Java. They are predefined by the language and named by a reserved keyword. There are eight primitive data types categorized into four groups:

Integer Types:
// byte: 8-bit signed integer (-128 to 127)
byte numByte = 10;

// short: 16-bit signed integer (-32,768 to 32,767)
short numShort = 1000;

// int: 32-bit signed integer (-2^31 to 2^31 - 1)
int numInt = 100000;

// long: 64-bit signed integer (-2^63 to 2^63 - 1)
long numLong = 10000000000L;
Enter fullscreen mode Exit fullscreen mode
Floating-Point Types:
// float: 32-bit floating point (6-7 significant decimal digits)
float numFloat = 3.14f;

// double: 64-bit floating point (15 significant decimal digits)
double numDouble = 3.14159;
Enter fullscreen mode Exit fullscreen mode
Character Type:
// char: 16-bit Unicode character (0 to 65,535)
char letter = 'A';
Enter fullscreen mode Exit fullscreen mode
Boolean Type:
// boolean: Represents true or false values
boolean isValid = true;
Enter fullscreen mode Exit fullscreen mode

2. Reference Data Types

Reference data types are created using defined constructors of classes. They include:

  • String: Represents a sequence of characters (not a primitive type, but widely used and treated as such)
  String name = "Java";
Enter fullscreen mode Exit fullscreen mode
  • Arrays: Containers that hold a fixed number of values of a single type.
  int[] numbers = {1, 2, 3, 4, 5};
Enter fullscreen mode Exit fullscreen mode
  • Classes: Custom data types defined by the programmer that can hold both primitive and reference data types.
// Example class definition
class Person {
    String name;
    int age;
}

// Creating an object of the Person class
Person person1 = new Person();
person1.name = "Alice";
person1.age = 30;
Enter fullscreen mode Exit fullscreen mode

Type Casting: Implicit and Explicit

Type casting in Java allows you to convert one data type to another. There are two types of type casting: implicit (widening) and explicit (narrowing).

1. Implicit Type Casting (Widening Conversion)

Implicit type casting, or widening conversion, occurs automatically when a smaller data type is converted to a larger data type. Java handles this conversion seamlessly without requiring any explicit operator.

Widening Sequence (Automatically):

byte -> short -> char -> int -> long -> float -> double
Enter fullscreen mode Exit fullscreen mode

Example:

// Implicit casting from byte to int
byte smallNum = 10;
int largeNum = smallNum; // Automatically converted
Enter fullscreen mode Exit fullscreen mode

In the above example, smallNum (byte) is implicitly cast to largeNum (int) because int can hold larger values than byte.

2. Explicit Type Casting (Narrowing Conversion)

Explicit type casting, or narrowing conversion, requires a manual intervention to convert a larger data type to a smaller data type. This process is initiated by using a cast operator (datatype) before the value to be cast.

Narrowing Sequence (Manually):

double -> float -> long -> int -> char -> short -> byte
Enter fullscreen mode Exit fullscreen mode

Example:

// Explicit casting from double to int
double bigNum = 123.456;
int smallNum = (int) bigNum; // Explicitly cast
Enter fullscreen mode Exit fullscreen mode

In the above example, bigNum (double) is explicitly cast to smallNum (int). Note that this may result in loss of data or precision, as int cannot hold decimal values.

String in Java

In Java, String is a special class that represents a sequence of characters. It is widely used for manipulating text and is immutable, meaning once a String object is created, its value cannot be changed. Here's a comprehensive guide covering everything you need to know about String in Java:

1. Creating Strings

You can create a String in Java using literals or by creating instances of the String class.

Using String Literals:
String str1 = "Hello"; // Using string literal
String str2 = "World";
Enter fullscreen mode Exit fullscreen mode
Using String Constructor:
String str3 = new String(); // Empty string
String str4 = new String("Java"); // Using constructor with initial value
Enter fullscreen mode Exit fullscreen mode

2. String Immutability

In Java, String objects are immutable, which means once created, their values cannot be changed.

Example:

String immutableStr = "Hello";
immutableStr = immutableStr + " World"; // Creates a new String object
System.out.println(immutableStr); // Output: Hello World
Enter fullscreen mode Exit fullscreen mode

3. String Concatenation

You can concatenate strings using the + operator or the concat() method. You can also concatenate numbers with strings.

Example:

String str1 = "Hello";
String str2 = "World";
String concatStr = str1 + " " + str2; // Using +
String concatStr2 = str1.concat(" ").concat(str2); // Using concat() method

int num = 42;
String numConcat = "The answer is " + num; // Concatenating number with string
System.out.println(concatStr); // Output: Hello World
System.out.println(numConcat); // Output: The answer is 42
Enter fullscreen mode Exit fullscreen mode

4. String Length

You can get the length of a String using the length() method.

Example:

String str = "Java";
int length = str.length(); // length is 4
Enter fullscreen mode Exit fullscreen mode

5. String Comparison

You can compare strings using the equals() method for content comparison and compareTo() method for lexicographical comparison.

Example:

String str1 = "Java";
String str2 = "java";
System.out.println(str1.equals(str2)); // false
System.out.println(str1.equalsIgnoreCase(str2)); // true
System.out.println(str1.compareTo(str2)); // returns > 0
Enter fullscreen mode Exit fullscreen mode

6. String Interning

String interning allows strings with the same content to share memory, which can improve performance and memory utilization.

Example:

String str1 = "Java";
String str2 = "Java";
System.out.println(str1 == str2); // true (same memory reference)
Enter fullscreen mode Exit fullscreen mode

7. Escape Sequences

Java supports escape sequences within strings, such as \n for newline and \t for tab.

Example:

String escapeStr = "Hello\tWorld\nJava";
System.out.println(escapeStr);
// Output:
// Hello   World
// Java
Enter fullscreen mode Exit fullscreen mode

8. String Formatting

Java provides the String.format() method and printf() method (from System.out) for formatted string output.

Example using String.format() for integers:

int age = 30;
String formattedStr = String.format("I am %d years old.", age);
System.out.println(formattedStr);
// Output: I am 30 years old.
Enter fullscreen mode Exit fullscreen mode

Example using String.format() for floating point numbers:

double price = 19.95;
String formattedPrice = String.format("The price is %.2f dollars.", price);
System.out.println(formattedPrice);
// Output: The price is 19.95 dollars.
Enter fullscreen mode Exit fullscreen mode

Operators in Java

Operators in Java are symbols used to perform operations on variables and values. They are classified into several categories based on their functionality.

Arithmetic Operators

Arithmetic operators are used for basic mathematical operations. They also include increment and decrement operators.

Operator Name Description Example
+ Addition Adds two operands x + y
- Subtraction Subtracts the right operand from the left x - y
* Multiplication Multiplies two operands x * y
/ Division Divides the left operand by the right operand x / y
% Modulus Returns the remainder of the division x % y
++ Increment Increases the value of operand by 1 x++ or ++x
-- Decrement Decreases the value of operand by 1 x-- or --x
int a = 10;
int b = 3;
System.out.println(a + b);   // Output: 13
System.out.println(a / b);   // Output: 3
System.out.println(a % b);   // Output: 1

int x = 5;
x++;
System.out.println(x);       // Output: 6

int y = 8;
y--;
System.out.println(y);       // Output: 7
Enter fullscreen mode Exit fullscreen mode

Assignment Operators

Assignment operators are used to assign values to variables and perform operations.

Operator Name Description Example
= Assignment Assigns the value on the right to the variable on the left x = 5
+= Addition Adds right operand to the left operand and assigns the result to the left x += 3
-= Subtraction Subtracts right operand from the left operand and assigns the result to the left x -= 3
*= Multiplication Multiplies right operand with the left operand and assigns the result to the left x *= 3
/= Division Divides left operand by right operand and assigns the result to the left x /= 3
%= Modulus Computes modulus of left operand with right operand and assigns the result to the left x %= 3
int x = 10;
x += 5;
System.out.println(x);   // Output: 15
Enter fullscreen mode Exit fullscreen mode

Comparison Operators

Comparison operators evaluate conditions and return Boolean values.
Comparison operators are used to compare values.

Operator Name Description Example
== Equal Checks if two operands are equal x == y
!= Not Equal Checks if two operands are not equal x != y
> Greater Than Checks if left operand is greater than right x > y
< Less Than Checks if left operand is less than right x < y
>= Greater Than or Equal Checks if left operand is greater than or equal to right x >= y
<= Less Than or Equal Checks if left operand is less than or equal to right x <= y
int a = 5;
int b = 10;
System.out.println(a == b);   // Output: false
System.out.println(a < b);    // Output: true
Enter fullscreen mode Exit fullscreen mode

Logical Operators

Logical operators combine Boolean expressions and return Boolean values.
Logical operators are used to combine conditional statements.

Operator Description Example
&& Logical AND x < 5 && x < 10
|| Logical OR x < 5 || x < 4
! Logical NOT !(x < 5 && x < 10)
int x = 3;
System.out.println(x < 5 && x < 10);   // Output: true
System.out.println(x < 5 || x < 2);    // Output: true
Enter fullscreen mode Exit fullscreen mode

Bitwise Operators

Bitwise operators are used to perform bitwise operations on integers.

Operator Name Description Example
& AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Left Shift Shifts bits to the left x << 2
>> Right Shift Shifts bits to the right x >> 2
int x = 5;
int y = 3;
System.out.println(x & y);   // Output: 1
System.out.println(x | y);   // Output: 7
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

The ternary operator ? : provides a shorthand for conditional expressions.

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);   // Output: Adult
Enter fullscreen mode Exit fullscreen mode

Conditions

Conditions are statements that evaluate whether a given expression is true or false. They control the flow of a program by executing specific blocks of code based on whether certain criteria are met. Using conditional statements like if, else if, and else, along with logical operators, Java programs can dynamically make decisions based on runtime data and user input.

If-Else Statements in Java

In Java, if statements are used for conditional execution based on the evaluation of an expression known as a "condition". A condition in Java must explicitly evaluate to either true or false, determining which block of code to execute. Optionally, else and else if can be used to specify alternative blocks of code based on different conditions.

Syntax and Usage

The basic syntax of an if statement in Java is:

if (condition) {
    // Executes if the condition is true
    statement(s);
}
Enter fullscreen mode Exit fullscreen mode

If there's a need for alternative execution when the condition is false, you can use else:

if (condition) {
    // Executes if the condition is true
    statement(s);
} else {
    // Executes if the condition is false
    statement(s);
}
Enter fullscreen mode Exit fullscreen mode

To handle multiple conditions, you can use else if:

if (condition1) {
    // Executes if condition1 is true
    statement(s);
} else if (condition2) {
    // Executes if condition1 is false and condition2 is true
    statement(s);
} else {
    // Executes if both condition1 and condition2 are false
    statement(s);
}
Enter fullscreen mode Exit fullscreen mode

Examples

  1. Simple if statement:
int x = 10;

if (x > 5) {
    System.out.println("x is greater than 5");  // Output: x is greater than 5
}
Enter fullscreen mode Exit fullscreen mode
  1. if-else statement:
int x = 3;

if (x % 2 == 0) {
    System.out.println("x is even");
} else {
    System.out.println("x is odd");  // Output: x is odd
}
Enter fullscreen mode Exit fullscreen mode
  1. if-else if-else statement:
int x = 20;

if (x > 50) {
    System.out.println("x is greater than 50");
} else if (x > 30) {
    System.out.println("x is greater than 30 but less than or equal to 50");
} else {
    System.out.println("x is 30 or less");  // Output: x is 30 or less
}
Enter fullscreen mode Exit fullscreen mode

Note:

In Java, unlike some other programming languages (e.g., Python), literals (such as integers, strings, etc.) do not inherently evaluate to true or false in conditional statements. Conditions must explicitly use comparison or logical operators to produce a true or false result for proper evaluation in if statements.

Loops in Java

Loops in Java are used to execute a block of code repeatedly as long as a specified condition is met. There are three main types of loops in Java: for, while, and do-while. Each type of loop is suited to different situations, and choosing the right loop for a particular task can help make your code more readable and efficient.

1. For Loop

A for loop is typically used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and update.

Syntax:
for (initialization; condition; update) {
    // Code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}
Enter fullscreen mode Exit fullscreen mode

2. Enhanced For Loop (For-Each Loop)

The enhanced for loop, also known as the for-each loop, is used to iterate over arrays or collections. It is a simplified version of the for loop.

Syntax:
for (type element : array) {
    // Code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}
Enter fullscreen mode Exit fullscreen mode

3. While Loop

A while loop is used when the number of iterations is not known beforehand and the loop should continue until a certain condition is met.

Syntax:
while (condition) {
    // Code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
int i = 0;
while (i < 5) {
    System.out.println("Iteration: " + i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

4. Do-While Loop

A do-while loop is similar to a while loop, but it guarantees that the code block will be executed at least once since the condition is evaluated after the loop body.

Syntax:
do {
    // Code to be executed
} while (condition);
Enter fullscreen mode Exit fullscreen mode
Example:
int i = 0;
do {
    System.out.println("Iteration: " + i);
    i++;
} while (i < 5);
Enter fullscreen mode Exit fullscreen mode

5. Nested Loops

Loops can be nested within other loops. This is useful for performing complex iterations such as iterating over multi-dimensional arrays.

Example:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println("i: " + i + ", j: " + j);
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Break and Continue

break and continue statements are used to alter the flow of loops.

  • break exits the loop immediately.
  • continue skips the current iteration and proceeds to the next iteration.
Example of break:
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break;
    }
    System.out.println("Iteration: " + i);
}
Enter fullscreen mode Exit fullscreen mode
Example of continue:
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println("Iteration: " + i);
}
Enter fullscreen mode Exit fullscreen mode

Functions in Java

Functions in Java, also known as methods, are blocks of code that perform a specific task. Methods allow you to write reusable code and organize your programs into modular pieces. Here is a comprehensive guide to understanding and using functions in Java, all within a single class.

1. Method Definition and Syntax

A method in Java is defined with the following syntax:

returnType methodName(parameters) {
    // Method body
    // Code to be executed
}
Enter fullscreen mode Exit fullscreen mode
  • returnType: The data type of the value the method returns. Use void if the method does not return a value.
  • methodName: The name of the method.
  • parameters: A comma-separated list of input parameters, each with a type and a name. If there are no parameters, leave the parentheses empty.
Example:
public class Main {
    // Method that returns a greeting message
    public String getGreeting() {
        return "Hello, World!";
    }

    public static void main(String[] args) {

    }
}
Enter fullscreen mode Exit fullscreen mode

2. Calling Methods

To execute a method, you need to call it. Methods can be called from within other methods or from another class.

Example:
public class Main {
    // Method that returns a greeting message
    public String getGreeting() {
        return "Hello, World!";
    }

    public static void main(String[] args) {
        Main main = new Main();
        String message = main.getGreeting();
        System.out.println(message);  // Output: Hello, World!
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Method Parameters

Methods can take parameters, which are used to pass values to the method.

Example:
public class Main {
    public int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        Main main = new Main();
        int result = main.add(5, 3);
        System.out.println("Sum: " + result);  // Output: Sum: 8
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Return Values

A method can return a value using the return statement. The return type of the method must match the type of the value returned.

Example:
public class Main {
    public int multiply(int a, int b) {
        return a * b;
    }

    public static void main(String[] args) {
        Main main = new Main();
        int result = main.multiply(4, 7);
        System.out.println("Product: " + result);  // Output: Product: 28
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameter lists.

Example:
public class Main {
    public void print(int num) {
        System.out.println("Integer: " + num);
    }

    public void print(String str) {
        System.out.println("String: " + str);
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.print(10);          // Output: Integer: 10
        main.print("Hello");     // Output: String: Hello
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Recursion

A method can call itself, which is known as recursion. Recursion is useful for solving problems that can be broken down into smaller, repetitive tasks.

Example:
public class Main {
    public int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        int result = main.factorial(5);
        System.out.println("Factorial: " + result);  // Output: Factorial: 120
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Static Methods

Static methods belong to the class rather than any instance of the class. They can be called without creating an object of the class.

Example:
public class Main {
    public static int square(int x) {
        return x * x;
    }

    public static void main(String[] args) {
        int result = square(6);
        System.out.println("Square: " + result);  // Output: Square: 36
    }
}
Enter fullscreen mode Exit fullscreen mode

Note: Static methods can be called directly without ClassName.methodName(), just using methodName().

Method Parameters in Java

1. Syntax for Defining Method Parameters

In Java, method parameters are defined within parentheses following the method name. Each parameter is declared with its data type and name.

public void methodName(DataType parameter1, DataType parameter2, ...) {
    // Method body
}
Enter fullscreen mode Exit fullscreen mode

2. Passing Arguments

When invoking a method, you pass arguments to match the parameters defined in the method signature. Arguments must be compatible with the parameter types.

public class Example {

    public void printDetails(String name, int age) {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        Example obj = new Example();
        obj.printDetails("John", 30); // Passing arguments "John" and 30
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Pass by Value

Java passes all primitive data types (e.g., int, float) by value. This means a copy of the actual value is passed to the method. Changes made to the parameter inside the method do not affect the original value.

public void modifyValue(int num) {
    num = num + 10; // Changes made to num inside the method
}

public static void main(String[] args) {
    Example obj = new Example();
    int x = 5;
    obj.modifyValue(x);
    System.out.println(x); // Output: 5 (unchanged)
}
Enter fullscreen mode Exit fullscreen mode

4. Pass by Reference

In Java, objects are passed by reference. However, the reference itself is passed by value. This means changes made to the object's state inside the method are reflected in the original object.

public void modifyObject(MyClass obj) {
    obj.value = obj.value + 10; // Modifying obj inside the method
}

public static void main(String[] args) {
    Example obj = new Example();
    MyClass myObject = new MyClass();
    myObject.value = 5;
    obj.modifyObject(myObject);
    System.out.println(myObject.value); // Output: 15 (modified)
}

class MyClass {
    int value;
}
Enter fullscreen mode Exit fullscreen mode

5. Variable Arguments (Varargs)

Java allows you to pass a variable number of arguments to a method using varargs. Varargs must be the last parameter in the method's parameter list, and they are treated as an array inside the method.

public void printValues(String... values) {
    for (String value : values) {
        System.out.println(value);
    }
}

public static void main(String[] args) {
    Example obj = new Example();
    obj.printValues("Apple", "Banana", "Orange"); // Output: Apple, Banana, Orange
}
Enter fullscreen mode Exit fullscreen mode

6. Default Parameter Values

Java does not support default parameter values directly in method signatures like some other languages (e.g., Python). You can achieve similar behavior using method overloading.

public void printMessage(String message) {
    System.out.println(message);
}

public void printMessage() {
    printMessage("Default message");
}

public static void main(String[] args) {
    Example obj = new Example();
    obj.printMessage("Hello"); // Output: Hello
    obj.printMessage();        // Output: Default message
}
Enter fullscreen mode Exit fullscreen mode

Note: Java does not support default parameter values directly; method overloading is used instead.

7. Final Parameters

You can declare method parameters as final, which means the parameter cannot be modified within the method.

public void process(final int num) {
    // num = num + 10; // Compilation error: cannot assign a value to final variable 'num'
    System.out.println(num);
}

public static void main(String[] args) {
    Example obj = new Example();
    obj.process(5); // Output: 5
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)