introduction-to-java-complete-beginners-guide

 

Introduction to Java



What is Java?

Java is a high-level, object-oriented, class-based, and platform-independent programming language used to develop a wide variety of applications, including web applications, desktop software, enterprise systems, mobile applications, and cloud-based services.

Java was designed to be simple, secure, reliable, and easy to learn. One of the most important reasons for Java's popularity is its ability to run on multiple operating systems without modifying the source code.

Today, Java is one of the most widely used programming languages in the software industry and is the foundation of countless enterprise applications worldwide.


Real-World Applications of Java

Java is used in many industries and applications.

Banking Applications

Banks use Java because it is secure and reliable.

Examples:

  • Online Banking
  • ATM Systems
  • Payment Gateways

E-Commerce Platforms

Large shopping websites use Java to handle millions of users.

Examples:

  • Product Management
  • Order Processing
  • Payment Systems

Mobile Applications

Android applications are primarily developed using Java and Kotlin.

Enterprise Applications

Large organizations use Java to build enterprise-level software.

Examples:

  • Employee Management Systems
  • Inventory Systems
  • ERP Applications

Cloud Applications

Java is widely used in cloud-native and microservices-based architectures.

Web Applications

Java frameworks like Spring Boot allow developers to create modern web applications and REST apis.

Features of Java

Java offers features like object-oriented programming, platform independence, security, robustness, multithreading, and high performance.

Features of Java

  • Object-Oriented Programming (OOP): Java supports OOP concepts to create modular and reusable code.
  • Platform Independence: Java programs can run on any operating system with a JVM.
  • Robust and Secure: Java ensures reliability and security through strong memory management and exception handling.
  • Multithreading and Concurrency: Java allows concurrent execution of multiple tasks for efficiency.
  • Rich API and Standard Libraries: Java provides extensive built-in libraries for various programming needs.
  • Frameworks for Enterprise and Web Development: Java supports frameworks that simplify enterprise and web application development.
  • Open-Source Libraries: Java has a wide range of libraries to extend functionality and speed up development.
  • Maintainability and Scalability: Java’s structured design allows easy maintenance and growth of applications.

Understanding Hello World Program

When we learn any programming language, the first step is writing a simple program to display "Hello World". So, here is a simple Java program that displays "Hello World" on the screen.

Public class helloworld {

    Public static void main(String[] args) {

        System.out.println("Hello World!");

    }

}


Output

Hello World!

Structure of a Java Program

The structure of a Java program defines the standard format for writing Java applications and includes essential components required for program execution.

 

 

 

Java Variables: Complete Detailed Guide for Beginners

What is a Variable?

A variable is a named memory location used to store data in a program.

Simply put, a variable is a container that holds information which can be used and modified during program execution.

Real-Life Example

Imagine you have a water bottle.

  • Bottle = Variable
  • Water = Value stored inside
  • Label on Bottle = Variable Name

Similarly in Java:

Int age = 25;

Here:

  • Int = Data Type
  • Age = Variable Name
  • 25 = Value

The variable age stores the value 25.


Why Do We Need Variables?

Without variables:

System.out.println("Nageshwar");

System.out.println("Nageshwar");

System.out.println("Nageshwar");

If the name changes, you must update it everywhere.

Using variables:

String name = "Nageshwar";

 

System.out.println(name);

System.out.println(name);

System.out.println(name);

Now changing one value updates everywhere.

Benefits:

  • Reusability
  • Readability
  • Easy Maintenance
  • Reduced Errors

Memory Representation

Example:

Int age = 25;

Memory View:

Variable Name     Value

 

Age               25

Example:

String name = "Java";

Memory View:

Name  ----->  "Java"

The variable stores a reference to the string object.


Variable Declaration

A variable must be declared before use.

Syntax:

Datatype variablename;

Example:

Int age;

This creates a variable but does not assign a value.


Variable Initialization

Assigning a value to a variable.

Example:

Int age = 25;

Here:

  • Declaration → int age
  • Initialization → = 25

Variable Declaration and Initialization Separately

Int age;

 

Age = 25;

Both approaches are valid.


Types of Variables in Java

Java provides three main types of variables.

Variables

── Local Variable

── Instance Variable

└── Static Variable


1. Local Variable

Declared inside a method, constructor, or block.

Example:

Public class Test {

 

    Public static void main(String[] args) {

 

        Int age = 25;

 

        System.out.println(age);

 

    }

}

Output:

25

Characteristics:

  • Created when method starts
  • Destroyed when method ends
  • Cannot be accessed outside the method

Scope of Local Variable

Example:

Public class Test {

 

    Public static void main(String[] args) {

 

        Int age = 25;

 

    }

 

    Public void display() {

 

        System.out.println(age);

 

    }

 

}

Error occurs because age belongs only to main().


2. Instance Variable

Declared inside a class but outside methods.

Example:

Class Student {

 

    Int id;

 

}

Characteristics:

  • Belongs to an object
  • Every object gets its own copy

Example:

Class Student {

 

    Int id;

 

    Public static void main(String[] args) {

 

        Student s1 = new Student();

        Student s2 = new Student();

 

        S1.id = 101;

        S2.id = 102;

 

        System.out.println(s1.id);

        System.out.println(s2.id);

    }

}

Output:

101

102

Each object has its own value.


3. Static Variable

Declared using static keyword.

Example:

Class Student {

 

    Static String college = "GEC Raichur";

 

}

Characteristics:

  • Shared among all objects
  • Only one copy exists

Example:

Class Student {

 

    Static String college = "GEC";

 

    Public static void main(String[] args) {

 

        Student s1 = new Student();

        Student s2 = new Student();

 

        System.out.println(s1.college);

        System.out.println(s2.college);

    }

}

Output:

GEC

GEC


Difference Between Instance and Static Variables

Feature

Instance Variable

Static Variable

Belongs To

Object

Class

Copies

Multiple

One

Memory

Heap

Method Area

Access

Object

Class Name

Example:

Student.college;

Static variable accessed using class name.


Variable Naming Rules

Valid:

Int age;

String name;

Double salary;

Valid:

Int studentage;

Int employeesalary;

Invalid:

Int 123age;

Cannot start with number.

Invalid:

Int class;

Keyword cannot be used.


Variable Naming Conventions

Use camelcase.

Good:

Studentname

Employeesalary

Accountbalance

Bad:

Student_name

Studentname

STUDENTNAME


Default Values of Variables

For instance variables:

Data Type

Default Value

Byte

0

Short

0

Int

0

Long

0L

Float

0.0f

Double

0.0

Char

'\u0000'

Boolean

False

String

Null

Example:

Class Test {

 

    Int age;

 

    Public static void main(String[] args) {

 

        Test t = new Test();

 

        System.out.println(t.age);

 

    }

}

Output:

0


Variable Lifetime

Local Variable

Lives only during method execution.

Public void display() {

 

    Int age = 25;

 

}

Destroyed after method finishes.

Instance Variable

Lives as long as object exists.

Static Variable

Lives until application stops.


Final Variables

Used to create constants.

Example:

Final double PI = 3.14159;

Cannot change later.

Wrong:

PI = 4.5;

Compilation Error.


Multiple Variable Declaration

Example:

Int a = 10;

Int b = 20;

Int c = 30;

Can also write:

Int a = 10, b = 20, c = 30;


Common Beginner Mistakes

Using Variable Before Initialization

Wrong:

Int age;

 

System.out.println(age);

Error.

Correct:

Int age = 25;

 

System.out.println(age);


Duplicate Variable Name

Wrong:

Int age = 25;

Int age = 30;

Error.


Interview Questions

What is a Variable?

A variable is a named memory location used to store data.

How Many Types of Variables Are There in Java?

Three:

  1. Local Variable
  2. Instance Variable
  3. Static Variable

Difference Between Local and Instance Variable?

Local variables are declared inside methods.

Instance variables are declared inside classes but outside methods.

What is a Static Variable?

A static variable belongs to the class and is shared among all objects.

What is a Final Variable?

A final variable cannot be modified after initialization.


Summary

In this chapter, you learned:

What is a Variable

Variable Declaration

Variable Initialization

Memory Representation

Local Variables

Instance Variables

Static Variables

Variable Scope

Variable Lifetime

Final Variables

Naming Rules

Naming Conventions

Common Mistakes

Variables are one of the most important concepts in Java because every Java program stores and manipulates data through variables.

 

 

 

 

 

 

Java Data Types Explained in Detail

What is a Data Type?

A Data Type specifies what kind of value a variable can store.

Think of a data type as a label on a container.

Example:

  • Water Bottle → Stores Water
  • Fuel Tank → Stores Fuel
  • Bank Account → Stores Money

Similarly in Java:

Int age = 25;

Here:

  • Int = Data Type
  • Age = Variable
  • 25 = Value

The data type tells Java that the variable age can store only integer values.


Why Do We Need Data Types?

Data types help Java:

  • Allocate memory efficiently
  • Prevent invalid data storage
  • Improve performance
  • Ensure type safety

Example:

Int age = 25;

Correct.

Int age = "Nageshwar";

Wrong.

Because int can only store numbers.


Types of Data Types in Java

Java Data Types are divided into two categories:

Data Types

── Primitive Data Types

└── Non-Primitive Data Types


Primitive Data Types

Primitive Data Types are predefined by Java.

Java provides 8 primitive data types.

Data Type

Size

Default Value

Byte

1 byte

0

Short

2 bytes

0

Int

4 bytes

0

Long

8 bytes

0L

Float

4 bytes

0.0f

Double

8 bytes

0.0

Char

2 bytes

'\u0000'

Boolean

1 bit

False


1. Byte

Used to store small integer values.

Size:

1 Byte = 8 Bits

Range:

-128 to 127

Example:

Byte age = 25;

Memory:

Age = 25

Use Case:

  • Memory optimization
  • File processing

2. Short

Stores larger values than byte.

Size:

2 Bytes

Range:

-32,768 to 32,767

Example:

Short year = 2026;

Use Case:

  • Moderate-sized numeric data

3. Int

Most commonly used numeric data type.

Size:

4 Bytes

Range:

-2,147,483,648

To

2,147,483,647

Example:

Int salary = 50000;

Why use int?

Because most whole numbers fit comfortably within its range.


4. Long

Used when int is not large enough.

Size:

8 Bytes

Example:

Long population = 8000000000L;

Notice:

L

Must be added at the end.

Without L:

Long population = 8000000000;

Error occurs.

Use Cases:

  • Population
  • Bank Transactions
  • Large Calculations

5. Float

Stores decimal values.

Size:

4 Bytes

Example:

Float price = 99.99f;

Notice:

F

Must be added.

Without f:

Float price = 99.99;

Compilation error.


6. Double

Most commonly used decimal type.

Size:

8 Bytes

Example:

Double salary = 45000.75;

Advantages:

  • More precision
  • Larger range

Most developers prefer double over float.


Difference Between float and double

Feature

Float

Double

Size

4 Bytes

8 Bytes

Precision

Lower

Higher

Suffix

F

Not Required

Example:

Float marks = 95.5f;

 

Double salary = 50000.75;


7. Char

Stores a single character.

Size:

2 Bytes

Example:

Char grade = 'A';

Valid:

Char gender = 'M';

Invalid:

Char name = 'Java';

Because char stores only one character.


ASCII Value Example

Char ch = 65;

 

System.out.println(ch);

Output:

A

Because ASCII value of A is 65.


8. Boolean

Stores only:

True

False

Example:

Boolean isjavaeasy = true;

Output:

True

Use Cases:

  • Login Status
  • Validation
  • Conditions

Example:

Boolean isloggedin = false;


Non-Primitive Data Types

These are created by programmers or provided by Java libraries.

Examples:

  • String
  • Array
  • Class
  • Interface
  • Object

String

Stores text.

Example:

String name = "Nageshwar";

Memory:

Name ---> "Nageshwar"

Unlike char:

Char grade = 'A';

Stores one character.

String stores multiple characters.


Array

Stores multiple values of the same type.

Example:

Int[] marks = {80,90,95};

Memory:

Index  Value

 

0      80

1      90

2      95

Access:

System.out.println(marks[0]);

Output:

80


Type Casting

Type Casting means converting one data type into another.


Widening Casting

Small → Large

Automatic.

Int num = 100;

 

Double value = num;

Output:

100.0

No data loss.


Narrowing Casting

Large → Small

Manual.

Double salary = 45000.75;

 

Int amount = (int) salary;

Output:

45000

Decimal value lost.


Memory Representation

Example:

Int age = 25;

Memory:

Variable      Value

 

Age           25

Example:

Double salary = 50000.75;

Memory:

Variable      Value

 

Salary        50000.75


Choosing the Right Data Type

Requirement

Data Type

Small Number

Byte

Year

Short

General Number

Int

Large Number

Long

Decimal

Double

Single Character

Char

True/False

Boolean

Text

String


Interview Questions

What is a Data Type?

A data type specifies the type of value a variable can store.


How many primitive data types are available in Java?

Java provides 8 primitive data types.


Difference Between float and double?

Double provides more precision and uses 8 bytes, while float uses 4 bytes.


Difference Between char and String?

Char stores a single character.

String stores multiple characters.

Example:

Char grade = 'A';

 

String name = "Java";


Which data type is most commonly used for whole numbers?

Int


Summary

In this chapter you learned:

What are Data Types

Primitive Data Types

byte

short

int

long

float

double

char

boolean

Non-Primitive Data Types

String

Array

Type Casting

Memory Representation

Data Types are the foundation of Java programming because every variable, object, and method uses them.

 

 

 

 

 

 

Java Operators: Complete Beginner's Guide

What is an Operator?

An Operator is a special symbol used to perform operations on variables and values.

Example:

Int a = 10;

Int b = 20;

 

Int result = a + b;

Here:

+

Is an operator.

It performs addition.

Output:

30


Why Do We Need Operators?

Suppose you want to:

  • Add numbers
  • Compare values
  • Check conditions
  • Assign values

Operators help us perform these tasks.

Example:

Int salary = 50000;

Int bonus = 10000;

 

Int totalsalary = salary + bonus;

Output:

60000


Types of Operators in Java

Java provides several types of operators:

Operators

── Arithmetic Operators

── Relational Operators

── Logical Operators

── Assignment Operators

── Unary Operators

── Ternary Operator

── Bitwise Operators

└── Shift Operators


1. Arithmetic Operators

Used for mathematical calculations.

Operator

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus


Addition (+)

Int a = 10;

Int b = 20;

 

System.out.println(a + b);

Output:

30


Subtraction (-)

System.out.println(20 - 10);

Output:

10


Multiplication (*)

System.out.println(5 * 4);

Output:

20


Division (/)

System.out.println(20 / 4);

Output:

5


Modulus (%)

Returns remainder.

System.out.println(10 % 3);

Output:

1

Because:

10 ÷ 3 = 3 remainder 1


2. Relational Operators

Used to compare values.

Result is always:

True

Or

False

Operator

Meaning

==

Equal To

!=

Not Equal To

> 

Greater Than

< 

Less Than

>=

Greater Than Equal

<=

Less Than Equal


Example:

Int a = 10;

Int b = 20;

 

System.out.println(a < b);

Output:

True


3. Logical Operators

Used to combine conditions.

Operator

Meaning

&&

AND

!

NOT


AND Operator (&&)

Both conditions must be true.

Int age = 25;

 

System.out.println(age > 18 && age < 60);

Output:

True


OR Operator (||)

At least one condition must be true.

System.out.println(10 > 20 || 20 > 10);

Output:

True


NOT Operator (!)

Reverses result.

Boolean status = true;

 

System.out.println(!Status);

Output:

False


4. Assignment Operators

Used to assign values.

Operator

Example

=

A = 10

+=

A += 5

-=

A -= 5

*=

A *= 5

/=

A /= 5


Example:

Int a = 10;

 

A += 5;

 

System.out.println(a);

Output:

15


5. Unary Operators

Operate on one operand.

Operator

Meaning

++

Increment

--

Decrement

+

Positive

-

Negative


Increment (++)

Int a = 10;

 

A++;

 

System.out.println(a);

Output:

11


Decrement (--)

Int a = 10;

 

A--;

 

System.out.println(a);

Output:

9


Pre Increment vs Post Increment

Pre Increment

Int a = 10;

 

System.out.println(++a);

Output:

11

Increment happens first.


Post Increment

Int a = 10;

 

System.out.println(a++);

Output:

10

After execution:

11


6. Ternary Operator

Short form of if-else.

Syntax:

Condition ? Value1 : value2;

Example:

Int age = 20;

 

String result =

Age >= 18 ? "Adult" : "Minor";

 

System.out.println(result);

Output:

Adult


7. Bitwise Operators

Work directly on binary values.

Operator

Meaning

&

AND

^

XOR

~

Complement

Example:

Int a = 5;

Int b = 3;

 

System.out.println(a & b);

Output:

1


Operator Precedence

Example:

Int result = 10 + 5 * 2;

Output:

20

Because:

5 * 2 = 10

 

10 + 10 = 20

Multiplication has higher priority than addition.


Common Interview Questions

What is an Operator?

An operator is a symbol used to perform operations on variables and values.

Difference Between == and = ?

=

Assignment Operator

==

Comparison Operator

Difference Between && and || ?

&&

Both conditions must be true.

||

At least one condition must be true.


Summary

In this chapter, you learned:

Arithmetic Operators

Relational Operators

Logical Operators

Assignment Operators

Unary Operators

Ternary Operator

Bitwise Operators

Operator Precedence

Operators are used in almost every Java program and form the foundation for decision-making, calculations, loops, and business logic.

 

Java Control Statements: Complete Guide

What are Control Statements?

Control Statements control the flow of execution of a Java program.

Normally, Java executes statements one by one from top to bottom.

Example:

System.out.println("Step 1");

System.out.println("Step 2");

System.out.println("Step 3");

Output:

Step 1

Step 2

Step 3

But what if:

  • We want to execute code only when a condition is true?
  • We want to repeat a task 100 times?
  • We want to skip some statements?

For these situations, Java provides Control Statements.


Types of Control Statements

Control Statements

── Decision Making

     ── if

     ── if-else

     ── else-if ladder

     └── switch

── Looping Statements

     ── for

     ── while

     ── do-while

     └── enhanced for

└── Jump Statements

      ── break

      ── continue

      └── return


Decision Making Statements

Used when we want Java to make decisions.


1. If Statement

Syntax:

If(condition){

    // code

}

Example:

Int age = 20;

 

If(age >= 18){

    System.out.println("Eligible to Vote");

}

Output:

Eligible to Vote

Explanation:

Condition:

Age >= 18

Returns:

True

Therefore code executes.


Flow Diagram

Condition

   |

   V

 True?

 /    \

Yes    No

 |      |

Execute Skip


2. If-else Statement

Used when we have two choices.

Example:

Int age = 15;

 

If(age >= 18){

    System.out.println("Adult");

}

Else{

    System.out.println("Minor");

}

Output:

Minor


Real-Life Example

ATM Card Eligibility

Int age = 17;

 

If(age >= 18){

    System.out.println("Eligible");

}

Else{

    System.out.println("Not Eligible");

}


3. Else-if Ladder

Used when multiple conditions exist.

Example:

Int marks = 75;

 

If(marks >= 90){

    System.out.println("Grade A");

}

Else if(marks >= 80){

    System.out.println("Grade B");

}

Else if(marks >= 70){

    System.out.println("Grade C");

}

Else{

    System.out.println("Fail");

}

Output:

Grade C


4. Nested if

If inside another if.

Example:

Int age = 25;

Boolean citizen = true;

 

If(age >= 18){

 

    If(citizen){

        System.out.println("Eligible to Vote");

    }

 

}

Output:

Eligible to Vote


Switch Statement

Used when multiple options exist.

Example:

Int day = 3;

 

Switch(day){

 

 

    Case 1:

        System.out.println("Monday");

        Break;

 Case 2:

        System.out.println("Tuesday");

        Break;

Case 3:

        System.out.println("Wednesday");

        Break;

  Default:

        System.out.println("Invalid Day");

}

Output:

Wednesday


Loops in Java

Loops repeat code multiple times.

Without Loop:

System.out.println("Java");

System.out.println("Java");

System.out.println("Java");

System.out.println("Java");

With Loop:

For(int i=1;i<=4;i++){

    System.out.println("Java");

}

Output:

Java

Java

Java

Java


For Loop

Used when number of iterations is known.

Syntax:

For(initialization;condition;increment){

    // code

}

Example:

For(int i=1;i<=5;i++){

    System.out.println(i);

}

Output:

1

2

3

4

5


Understanding for Loop

For(int i=1;i<=5;i++)

Initialization

Int i=1

Starting point.

Condition

I<=5

Loop continues while true.

Increment

I++

Increases value.


While Loop

Used when number of iterations is unknown.

Syntax:

While(condition){

    // code

}

Example:

Int i = 1;

 

While(i <= 5){

 

    System.out.println(i);

 

    I++;

}

Output:

1

2

3

4

5


Do-while Loop

Executes at least once.

Syntax:

Do{

    // code

}

While(condition);

Example:

Int i = 1;

 

Do{

 

    System.out.println(i);

 

    I++;

 

}

While(i <= 5);

Output:

1

2

3

4

5


 

 

Difference Between while and do-while

While

Condition checked first.

Do-while

Code executes first.

Then condition checked.

Example:

Int i = 10;

While(i < 5){

    System.out.println(i);

}

Output:

Nothing


Example:

Int i = 10;

 

Do{

    System.out.println(i);

}

While(i < 5);

Output:

10

Executed once.


Enhanced for Loop

Used with arrays and collections.

Example:

Int[] marks = {80,90,95};

 

For(int mark : marks){

 

    System.out.println(mark);

 

}

Output:

80

90

95


Jump Statements


Break

Terminates loop immediately.

Example:

For(int i=1;i<=10;i++){

If(i==5){

        Break;

    }

  System.out.println(i);

}

Output:

1

2

3

4


Continue

Skips current iteration.

Example:

For(int i=1;i<=5;i++){

 

    If(i==3){

        Continue;

    }

 System.out.println(i);

}

Output:

1

2

4

5


Return

Ends method execution.

Example:

Public static void display(){

Return;

}


Interview Questions

What are Control Statements?

Control statements control program execution flow.

Difference Between if and switch?

If works with conditions.

Switch works with fixed values.

Difference Between while and do-while?

While checks condition first.

Do-while executes at least once.

Difference Between break and continue?

Break terminates loop.

Continue skips current iteration.


 

 

 

 

 

 

 

Java Arrays: Complete Beginner's Guide

What is an Array?

An Array is a collection of similar data types stored in contiguous memory locations.

Arrays are used when we need to store multiple values of the same type.

Problem Without Arrays

Suppose you want to store marks of 5 students.

Without Array:

Int mark1 = 80;

Int mark2 = 85;

Int mark3 = 90;

Int mark4 = 75;

Int mark5 = 95;

Managing many variables becomes difficult.


Solution Using Array

Int[] marks = {80, 85, 90, 75, 95};

Now all values are stored in a single variable.

Benefits:

  • Less code
  • Easy management
  • Better performance
  • Faster access

Array Declaration

Syntax:

Datatype[] arrayname;

Example:

Int[] marks;

Or

Int marks[];

Both are correct.


Array Creation

Int[] marks = new int[5];

Here:

  • Int → Data Type
  • Marks → Array Name
  • 5 → Array Size

Memory:

Index   Value

 

0       0

1       0

2       0

3       0

4       0

Default value for int is 0.


Array Initialization

Method 1

Int[] marks = new int[5];

 

Marks[0] = 80;

Marks[1] = 85;

Marks[2] = 90;

Marks[3] = 75;

Marks[4] = 95;

Method 2

Int[] marks = {80, 85, 90, 75, 95};

Most commonly used.


Understanding Array Index

Arrays start from index 0.

Example:

Int[] marks = {80, 85, 90, 75, 95};

Memory Representation:

Index    Value

 

0         80

1         85

2         90

3         75

4         95


Accessing Array Elements

Int[] marks = {80,85,90};

 

System.out.println(marks[0]);

Output:

80


Modifying Array Elements

Int[] marks = {80,85,90};

 

Marks[1] = 100;

 

System.out.println(marks[1]);

Output:

100


Finding Array Length

Int[] marks = {80,85,90,95};

 

System.out.println(marks.length);

Output:

4


Traversing Array Using for Loop

Int[] marks = {80,85,90};

 

For(int i=0; i<marks.length; i++){

 

    System.out.println(marks[i]);

 

}

Output:

80

85

90


Enhanced for Loop

Simpler way to iterate.

Int[] marks = {80,85,90};

 

For(int mark : marks){

 

    System.out.println(mark);

 

}

Output:

80

85

90


Array Memory Representation

Example:

Int[] numbers = {10,20,30};

Memory:

Numbers

   |

   V

 

+-----+-----+-----+

| 10  | 20  | 30  |

+-----+-----+-----+

 

  0     1     2


Types of Arrays

Single-Dimensional Array

Stores data in one row.

Example:

Int[] marks = {80,85,90};


Multi-Dimensional Array

Stores data in rows and columns.

Example:

Int[][] matrix = {

 

    {1,2,3},

    {4,5,6},

    {7,8,9}

 

};

Memory:

1 2 3

4 5 6

7 8 9


Accessing 2D Array Elements

System.out.println(matrix[1][2]);

Output:

6

Because:

Matrix[1][2]

 

Row 1

Column 2


Traversing 2D Array

For(int i=0;i<3;i++){

 

    For(int j=0;j<3;j++){

 

        System.out.print(matrix[i][j] + " ");

 

    }

 

    System.out.println();

 

}

Output:

1 2 3

4 5 6

7 8 9


Common Array Operations

Find Sum

Int[] arr = {10,20,30};

 

Int sum = 0;

 

For(int num : arr){

 

    Sum += num;

 

}

 

System.out.println(sum);

Output:

60


Find Largest Number

Int[] arr = {10,50,20,80,40};

 

Int max = arr[0];

 

For(int num : arr){

 

    If(num > max){

 

        Max = num;

 

    }

 

}

 

System.out.println(max);

Output:

80


Find Smallest Number

Int[] arr = {10,50,20,80,40};

 

Int min = arr[0];

 

For(int num : arr){

 

    If(num < min){

 

        Min = num;

 

    }

 

}

 

System.out.println(min);

Output:

10


Reverse Array

Int[] arr = {1,2,3,4,5};

 

For(int i=arr.length-1;i>=0;i--){

 

    System.out.print(arr[i]+" ");

 

}

Output:

5 4 3 2 1


Common Errors

Arrayindexoutofboundsexception

Wrong:

Int[] arr = {10,20,30};

 

System.out.println(arr[5]);

Output:

Exception

Because index 5 does not exist.


Advantages of Arrays

  • Fast access
  • Easy traversal
  • Less code
  • Better memory management

Limitations of Arrays

  • Fixed Size
  • Same Data Type Only
  • Cannot grow dynamically

For dynamic collections, Java provides arraylist.


Interview Questions

What is an Array?

An array is a collection of similar data types stored in contiguous memory locations.

Does Array Start from 0 or 1?

Array starts from index 0.

Difference Between Array and arraylist?

Array = Fixed Size

Arraylist = Dynamic Size

How to Find Length of Array?

Array.length


Summary

In this chapter you learned:

What is Array

Array Declaration

Array Creation

Array Initialization

Array Index

Single-Dimensional Array

Multi-Dimensional Array

Array Traversal

Common Array Operations

Advantages and Limitations

Arrays are one of the most important data structures in Java and are heavily used in interviews, algorithms, and real-world applications.

 

Java String: Complete Beginner's Guide

 

 

What is a String?

A String is a sequence of characters.

In simple words, a String is used to store text.

Examples:

"Nageshwar"

"Java"

"Hello World"

"12345"

All of the above are Strings.


Why Do We Need Strings?

Suppose you want to store:

  • Student Name
  • Email Address
  • City Name
  • Company Name

Numbers cannot store these values.

Example:

String name = "Nageshwar";

String city = "Bangalore";


How String is Created?

Method 1: String Literal

String name = "Java";

Most commonly used.


Method 2: Using new Keyword

String name = new String("Java");

Creates a new object in memory.


String Memory Concept

Example:

String s1 = "Java";

String s2 = "Java";

Memory:

String Pool

 

+--------+

| Java   |

+--------+

   ^

   |

 S1,s2

Only one object is created.

This saves memory.


Using new Keyword

String s1 = new String("Java");

String s2 = new String("Java");

Memory:

Heap Memory

 

S1 ---> Object1

 

S2 ---> Object2

Two separate objects created.


String is Immutable

One of the most important interview questions.

What is Immutable?

Immutable means:

"Cannot be changed after creation."

Example:

String name = "Java";

 

Name.concat(" Programming");

 

System.out.println(name);

Output:

Java

No change occurs.


Correct Way

String name = "Java";

 

Name = name.concat(" Programming");

 

System.out.println(name);

Output:

Java Programming

A new String object is created.


Common String Methods

Length()

Returns length of String.

String name = "Java";

 

System.out.println(name.length());

Output:

4


Touppercase()

Converts to uppercase.

String name = "java";

 

System.out.println(name.touppercase());

Output:

JAVA


Tolowercase()

String name = "JAVA";

 

System.out.println(name.tolowercase());

Output:

Java


Charat()

Returns character at index.

String name = "Java";

 

System.out.println(name.charat(1));

Output:

A

Index:

J a v a

0 1 2 3


Contains()

Checks if String contains text.

String name = "Java Programming";

 

System.out.println(name.contains("Java"));

Output:

True


Startswith()

String name = "Java Programming";

 

System.out.println(name.startswith("Java"));

Output:

True


Endswith()

String name = "Java Programming";

 

System.out.println(name.endswith("Programming"));

Output:

True


Equals()

Compares values.

String s1 = "Java";

String s2 = "Java";

 

System.out.println(s1.equals(s2));

Output:

True


Equalsignorecase()

String s1 = "JAVA";

String s2 = "java";

 

System.out.println(s1.equalsignorecase(s2));

Output:

True


Difference Between == and equals()

==

Compares memory addresses.

String s1 = new String("Java");

String s2 = new String("Java");

 

System.out.println(s1 == s2);

Output:

False


Equals()

Compares values.

System.out.println(s1.equals(s2));

Output:

True


Substring()

Extracts part of String.

String name = "Programming";

 

System.out.println(name.substring(0,4));

Output:

Prog


Replace()

String name = "Java";

 

System.out.println(name.replace("Java","Python"));

Output:

Python


Trim()

Removes spaces.

String name = " Java ";

 

System.out.println(name.trim());

Output:

Java


Split()

Splits String into parts.

String data = "Java,Python,C++";

 

String[] arr = data.split(",");

Output:

Java

Python

C++


Stringbuffer

Mutable String.

Example:

Stringbuffer sb = new stringbuffer("Java");

 

Sb.append(" Programming");

 

System.out.println(sb);

Output:

Java Programming

Can be modified.


Stringbuilder

Similar to stringbuffer.

But faster.

Example:

Stringbuilder sb = new stringbuilder("Java");

 

Sb.append(" Programming");

 

System.out.println(sb);

Output:

Java Programming


Difference Between String, stringbuffer and stringbuilder

Feature

String

Stringbuffer

Stringbuilder

Mutable

No

Yes

Yes

Thread Safe

No

Yes

No

Performance

Slow

Medium

Fast


Common Interview Questions

What is String?

A String is a sequence of characters.

Why String is Immutable?

For security, memory optimization, and thread safety.

Difference Between == and equals()?

== compares references.

Equals() compares content.

Difference Between stringbuffer and stringbuilder?

Stringbuffer is thread-safe.

Stringbuilder is faster but not thread-safe.


Summary

In this chapter, you learned:

What is String

String Literal

String Pool

Immutable Strings

String Methods

equals() vs ==

substring()

replace()

split()

stringbuffer

stringbuilder

Interview Questions

Strings are one of the most frequently used classes in Java and are extremely important for interviews and real-world applications.

 

 

Comments

Popular posts from this blog

Top 25 Java Interview Questions and Answers for Freshers (2026)

top-10-spring-boot-interview-questions-and-answers-2026