Java Basics Tutorial: Complete Beginner Guide

Learn Java identifiers, primitive data types, literals, arrays, variables, var-args, main() method and command line arguments with clear examples.

What are Java Identifiers: Rules, Examples, and Best Practices

In Java, an identifier is the name given to program elements such as classes, methods, variables, and labels. Identifiers help developers uniquely recognize and access different parts of a Java program.

What is an Identifier in Java?

An identifier is a user-defined name used for:

  • Class names
  • Method names
  • Variable names
  • Label names

Java Identifier Example

class Test {
    public static void main(String[] args) {
        int x = 10;
    }
}

In the above Java program:

  • Test is a class name
  • main is a method name
  • x is a variable name
  • args is also an identifier used as a parameter name

Rules for Defining Identifiers in Java

While creating identifiers in Java, you must follow these rules:

  1. Java identifiers can contain letters: a-z and A-Z.
  2. They can contain digits from 0-9, but they cannot start with a digit.
  3. The only allowed special characters are underscore _ and dollar sign $.
  4. Java identifiers are case-sensitive. For example, Number, number, and NUMBER are three different identifiers.
  5. Reserved keywords such as class, int, public, static, and void cannot be used as identifiers.
  6. There is no fixed length limit for identifiers, but meaningful and readable names are recommended.

Valid Java Identifiers

int age = 25;
String studentName = "Rahul";
double total_amount = 5000.75;
int $salary = 30000;
int rollNumber1 = 101;

Invalid Java Identifiers

int 1number = 10;     // Invalid: starts with a digit
int total-amount = 50; // Invalid: hyphen is not allowed
int class = 100;       // Invalid: class is a reserved keyword
int @value = 20;       // Invalid: @ is not allowed

Java Identifiers are Case-Sensitive

Java treats uppercase and lowercase letters differently. Therefore, the following identifiers are considered different:

int number = 10;
int Number = 20;
int NUMBER = 30;

Although this is valid, using very similar names can reduce readability and may confuse developers.

Best Practices for Naming Identifiers in Java

  • Use meaningful names such as studentName instead of s.
  • Use camelCase for variables and methods, such as totalMarks and calculateSalary().
  • Use PascalCase for class names, such as StudentDetails.
  • Avoid using $ in normal identifiers because it is mostly used by tools and generated code.
  • Do not use confusing names like a1, b2, or temp unless the context is very clear.

Common Interview Question

Can we use reserved keywords as identifiers in Java?

No, reserved keywords cannot be used as identifiers in Java because they already have predefined meanings in the language.

Quick Summary

Java identifiers are names used for classes, methods, variables, and labels. They can contain letters, digits, underscore, and dollar sign, but they cannot start with a digit. Java identifiers are case-sensitive, and reserved keywords cannot be used.

Java Primitive Data Types: Types, Sizes, and Examples

In Java, primitive data types are the most basic data types available. They are used to store simple values such as numbers, characters, and boolean values. Java provides 8 primitive data types that are predefined by the language.

Types of Primitive Data Types in Java

Java primitive data types are broadly classified into the following categories:

  • Numeric Data Types
    • Integral Types (Whole Numbers): byte, short, int, long
    • Floating-Point Types (Decimal Numbers): float, double
  • Character Type: char (used to store single characters)
  • Boolean Type: boolean (used to store logical values: true or false)

List of All Primitive Data Types

Data Type Size Description Example
byte 1 byte Stores small integer values byte b = 10;
short 2 bytes Stores medium integer values short s = 200;
int 4 bytes Default integer type int x = 1000;
long 8 bytes Stores large integer values long l = 100000L;
float 4 bytes Stores decimal values (less precision) float f = 10.5f;
double 8 bytes Stores decimal values (high precision) double d = 10.5;
char 2 bytes Stores a single Unicode character char ch = 'A';
boolean JVM dependent Stores true or false values boolean flag = true;

Key Points About Primitive Data Types

  • The int data type always occupies 4 bytes, regardless of the system or platform.
  • The long data type occupies 8 bytes, making it suitable for storing large numbers.
  • Java is platform-independent, meaning data type sizes are fixed and do not vary between systems.
  • Fixed sizes ensure portability and reliability of Java programs across different environments.

Example: Using Primitive Data Types in Java

public class DataTypesExample {
    public static void main(String[] args) {
        int age = 25;
        long population = 7800000000L;
        float price = 99.99f;
        double pi = 3.14159;
        char grade = 'A';
        boolean isJavaFun = true;

        System.out.println(age);
        System.out.println(population);
        System.out.println(price);
        System.out.println(pi);
        System.out.println(grade);
        System.out.println(isJavaFun);
    }
}

Best Practices

  • Use int for general integer calculations.
  • Use long when values exceed the range of int.
  • Use double instead of float for better precision.
  • Use boolean for conditions instead of integers like 0 or 1.
  • Use char for single characters and String for text.

Conclusion

Primitive data types in Java are essential for storing basic values efficiently. Understanding their types, sizes, and usage is crucial for writing optimized and platform-independent Java programs.

Java Primitive Data Types: Complete Guide

Java provides 8 primitive data types used to store simple values like numbers, characters, and boolean values. These are the foundation of Java programming.

1. Numeric Data Types

Numeric data types are used to store numbers. They are divided into:

2. Integral Data Types

Used to store whole numbers (without decimals).

byte Data Type

Size: 1 byte. Used for small integer values.

byte b = 10;

short Data Type

Size: 2 bytes. Used for medium-sized integers.

short s = 100;

int Data Type

Size: 4 bytes. Default integer type in Java. Fixed across platforms → ensures reliability.

int x = 1000;

long Data Type

Size: 8 bytes. Used for large integer values.

long l = 100000L;

3. Floating-Point Data Types

Used to store decimal (real) numbers.

float Data Type

Size: 4 bytes. Used for decimal values (less precision).

float f = 10.5f;

double Data Type

Size: 8 bytes. Default for decimal values (high precision).

double d = 99.99;

4. Char Data Type

The char data type stores a single character. It uses Unicode (2 bytes) and supports international characters.

Example

char ch = 'a';
char ch2 = '\u0061'; // Unicode for 'a'

5. Boolean Data Type

The boolean data type stores logical values:

  • true
  • false

Valid Example

boolean flag = true;

Invalid Examples

boolean b = 0;    // ❌ not allowed
boolean b = True; // ❌ case-sensitive

Key Points

  • int size = 4 bytes (fixed across platforms)
  • long size = 8 bytes
  • Java is platform-independent
  • Fixed sizes improve reliability and portability

Summary

Java primitive data types include numeric types (integral and floating), character type (char), and logical type (boolean). Understanding these data types is essential for Java programming, interviews, and SCJP certification.

Java Literals: Types, Examples, and Complete Guide

In Java, a literal is a constant value assigned to a variable. Literals represent fixed values that cannot be changed during program execution.

What is a Literal in Java?

A literal is a fixed value assigned directly to a variable in a Java program.

Example

int x = 10;  // 10 is a literal

1. Integer Literals

Integer literals are used to represent whole numbers (without decimals).

Types of Integer Literals

  • Decimal (Base 10): 10
  • Octal (Base 8): 010
  • Hexadecimal (Base 16): 0x10

Examples

int a = 10;    // Decimal
int b = 010;   // Octal
int c = 0x10;  // Hexadecimal

Default Type

By default, all integer literals are treated as int in Java.

Using Long Literal

To store large integer values, use L or l (recommended: uppercase L).

long l = 10L;

2. Floating-Point Literals

Floating-point literals are used to represent decimal numbers.

Default Type

By default, floating-point literals are of type double.

Examples

double d = 123.45;  // default double
float f = 123.45f;  // float requires 'f' or 'F'

If you assign a decimal number to a float without f, it will cause a compilation error.

3. Char Literals

Char literals represent a single character enclosed in single quotes.

Example

char ch = 'a';

Unicode Representation

Java supports Unicode, so characters can also be represented using Unicode values.

char ch = '\u0061'; // Unicode for 'a'

4. Escape Characters in Java

Escape characters are special sequences used inside character and String literals.

Escape Sequence Description
\n New line
\t Tab space
\' Single quote
\" Double quote
\\ Backslash

Example

char newLine = '\n';
char tab = '\t';

Step-by-Step Understanding

Step 1: Assign a Literal

int x = 10;

Step 2: Choose Type

Use integer literals for whole numbers and floating-point literals for decimals.

Step 3: Use Proper Suffix

  • L for long
  • f for float

Step 4: Use Char Correctly

char ch = 'A';

Summary

Java literals are constant values assigned to variables. They include integer literals, floating-point literals, and character literals. Understanding literals helps in writing correct and efficient Java programs and is important for Java interviews and SCJP exams.

Java Arrays and Length vs length(): Complete Guide

In Java, an array is a collection of elements of the same data type stored in contiguous memory locations. Arrays are widely used to store multiple values in a single variable instead of declaring separate variables.

1. Array Declaration

Array declaration defines the reference variable that can hold the array object.

Syntax

int[] a;
int a[];

Both syntaxes are valid, but int[] a is preferred as per Java coding standards.

2. Array Creation

After declaration, memory must be allocated using the new keyword.

Example

a = new int[3];

This creates an array that can hold 3 integer values. By default:

  • Numeric arrays → initialized to 0
  • Boolean arrays → initialized to false
  • Object arrays → initialized to null

3. Array Initialization

Initialization means assigning values to the array at the time of creation.

Example

int[] a = {10, 20, 30};

This creates and initializes the array in a single step.

4. Key Points About Arrays

  • Arrays are objects in Java.
  • They store elements of the same data type.
  • The size of an array must be specified using integer types: byte, short, int, or char.
  • Array size cannot be changed after creation.
  • Index starts from 0.

5. Difference Between length and length()

In Java, length and length() are different and used in different contexts.

Feature length length()
Type Property (variable) Method (function)
Used For Arrays Strings
Syntax a.length str.length()

Example

int[] a = {10, 20, 30};
System.out.println(a.length);   // 3

String str = "Java";
System.out.println(str.length()); // 4

Important: Forgetting parentheses in length() will cause an error, because it is a method, not a property.

Step-by-Step Understanding

Step 1: Declare Array

int[] a;

Step 2: Create Array

a = new int[3];

Step 3: Initialize Array

a[0] = 10;
a[1] = 20;
a[2] = 30;

Step 4: Access Length

System.out.println(a.length);

Summary

Java arrays are objects used to store multiple values of the same type. They require declaration, creation, and initialization. The length property is used to find the size of arrays, while length() is used for strings. Understanding arrays is essential for Java programming and coding interviews.

Java Variables, Var-args, main() Method & Command Line Arguments

This guide explains types of variables in Java, important rules, var-args methods, main() method, and command line arguments in a simple and SEO-friendly format.

1. Types of Variables in Java

In Java, variables are classified into three types:

2. Instance Variables

Instance variables are declared inside a class but outside any method, constructor, or block.

  • Defined inside class, outside methods
  • Each object has its own copy
  • Default values are provided by JVM

Example

class Student {
    int id;   // instance variable
    String name;

    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(s1.id); // default value: 0
    }
}

3. Static Variables

Static variables are declared using the static keyword. They are shared among all objects of a class.

  • Shared across all objects
  • Created at class loading time
  • Only one copy exists

Example

class Test {
    static int count = 0;

    Test() {
        count++;
        System.out.println(count);
    }

    public static void main(String[] args) {
        new Test();
        new Test();
        new Test();
    }
}

4. Local Variables

Local variables are declared inside methods, constructors, or blocks.

  • Declared inside methods
  • No default values
  • Must be initialized before use

Example

class Test {
    public static void main(String[] args) {
        int x = 10; // local variable
        System.out.println(x);
    }
}

5. Important Note on Local Variables

Local variables must be initialized before use. Otherwise, the compiler will throw an error.

Invalid Example

int x;
System.out.println(x); // ❌ Compile-time error

6. Var-args Methods in Java

Var-args (variable arguments) were introduced in Java 1.5. They allow passing a variable number of arguments to a method.

  • Uses ... (ellipsis)
  • Internally treated as an array

Example

class Test {
    static void sum(int... x) {
        for(int i : x) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        sum(10, 20, 30);
    }
}

7. main() Method in Java

The main() method is the entry point of any Java program. The JVM starts execution from this method.

Standard Signature

public static void main(String[] args)

Valid Variations

The order of modifiers can change, but the method signature must remain valid.

static public void main(String[] args)

8. Command Line Arguments

Command line arguments are passed to the Java program during execution. They are stored in the args array.

Example (Command Line)

java Test 10 20

Accessing Arguments

class Test {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println(args[1]);
    }
}

Output:

10
20

Summary

Java variables are categorized into instance, static, and local variables. Instance variables are object-specific, static variables are shared, and local variables must be initialized manually. Var-args methods allow flexible arguments, while the main() method is the entry point of Java programs. Command line arguments enable passing input during execution.