0% found this document useful (0 votes)
1 views

Core Java Training

The document provides a comprehensive overview of Core Java, covering its features, setup instructions for JDK and IDE, and fundamental concepts such as data types, variables, operators, control statements, and memory management. It explains the roles of JDK, JRE, and JVM in Java programming, along with type conversion and the use of wrapper classes. Additionally, it discusses various programming constructs like loops, conditional statements, and arithmetic operations essential for Java development.

Uploaded by

niladridutta1988
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Core Java Training

The document provides a comprehensive overview of Core Java, covering its features, setup instructions for JDK and IDE, and fundamental concepts such as data types, variables, operators, control statements, and memory management. It explains the roles of JDK, JRE, and JVM in Java programming, along with type conversion and the use of wrapper classes. Additionally, it discusses various programming constructs like loops, conditional statements, and arithmetic operations essential for Java development.

Uploaded by

niladridutta1988
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Core Java Training

© Copyright 2021. All rights reserved.


Introduction to Java
• Java is an object-oriented, platform-independent programming language,
originally developed by James Gosling at Sun Microsystems in the 1990s.
• Oracle Corporation owns Java since acquiring Sun Microsystems in 2010.
Java's tagline "write once, run anywhere" highlights its versatility across
platforms like Windows, Mac, and Linux.
Java features
• Easy to Use and Safe: Java is designed to remove confusing features found in some
other programming languages, like pointers. It also has built-in tools to protect your
programs from security risks.
• Works Everywhere: You can write a Java program once and run it on any computer
—whether it’s Windows, Mac, or Linux—without changing the code.
• Focuses on Objects: Java is built around "objects," which are like real-world items
with behaviors and features. This makes programs easier to understand and build.
• Handles Many Tasks: Java can perform multiple tasks at once (called
multithreading) and manages memory well, so programs are fast and efficient.
JDK setup
• Download JDK 1.8 -> Visit Oracle JDK Download Page

• Install JDK -> Choose the installation directory (default is recommended) and click
"Install."
• Set Environment Variables -> Go to your system settings and search for
"Environment Variables." -> Under "System Variables," find Path and click "Edit." ->
Add the path to the bin folder of your JDK installation (e.g., C:\Program Files\Java\
jdk-XX\bin).
• Verify Installation: Open the Command Prompt (or Terminal) and type java –
version, If the installation is successful, it will display the installed JDK version.
Setup IDE(Eclipse/JDeveloper)
• Download: Get the
Eclipse IDE for Enterprise Java and Web Developers from Eclipse's
official website.
• Install: Run the installer, select "Eclipse IDE for Enterprise Java and Web
Developers," choose the installation path, and complete the setup.
First Code In Java
• Launch Eclipse and Set Workspace: Open Eclipse IDE and create/select a workspace
folder to save your projects.
• Create a Java Project: Go to File > New > Java Project, name your project (e.g.,
"FirstJavaProject"), and click Finish.
• Create a Java Class: Right-click on your project and select New > Class. Name the class
(e.g., "HelloWorld") and add the main method.
• Run Your Program: Click the Run button (green play icon) in the toolbar or right-click on
the class file and select Run As > Java Application. The output "Hello, World!" will appear
in the console panel at the bottom of the IDE.
How Java Works
• Java Compilation : Java Compilation is a 2 Step process

1.Check the Syntax of Java Code.


2. If the code is Syntactically correct, Byte code gets generated .
Note : If program is Syntactically wrong the compiler doesn’t generates Byte code but rather throws Error

• Platform Independence: Java programs are compiled into bytecode, which can run on any
system with a Java Virtual Machine (JVM). This ensures that programs are not hardware-
dependent and do not need re-compilation for different platforms.
• .Universal Compatibility: Powered by JVM, Java enables "Write Once, Run Anywhere"
functionality, allowing programs to seamlessly run on Windows, Mac, Linux, or any JVM-
supported environment.
JDK
• What is JDK?: JDK (Java Development Kit) is a software development
environment used to create Java applications. It includes Java Runtime
Environment (JRE) and essential development tools.
• Java Platforms: JDK is available in three editions—Standard Edition (SE) for
general applications, Enterprise Edition (EE) for web and enterprise software,
and Micro Edition (ME) for mobile and embedded systems.
JRE
• What is JRE ?

JRE is software that allows you to run Java programs on your computer. It
provides all the tools and libraries needed to execute Java applications
smoothly.
• Works with JVM: It includes the Java Virtual Machine (JVM), which translates
Java code into a format that your computer can understand and execute.
• Not for Development: JRE is designed specifically for running Java
applications—it does not contain tools for writing or compiling code, like a
compiler (javac).
JVM
• What is JVM (Java Virtual Machine) ?
o JVM is a virtual machine that runs Java programs by executing Java bytecode (compiled Java
code).
o It is platform-independent, meaning Java programs can run on any operating system with a
JVM

• How Does JVM Work ?


o Load Bytecode: It loads the .class files (compiled Java bytecode) into memory using the
Class Loader.
o Verify Code: Checks the bytecode for any security risks or errors through the Bytecode
Verifier.
o Interpret or Compile: Translates bytecode into machine code using either the Interpreter
or the JIT Compiler (Just-In-Time).
o Execute Code: Runs the machine code on the underlying hardware and generates the
output.
o Memory Management: JVM manages memory automatically with Garbage Collection,
which removes unused objects.
JVM
• What is an Interpreter?
o It is a program that translates bytecode into machine code line by line during
execution.

• What is JIT (Just-In-Time) Compiler?


o JIT Compiler is part of the JVM that improves performance by compiling frequently
executed bytecode into machine code all at once instead of line by line.
o Once the code is compiled, it is stored in memory for reuse, making execution
faster.

• Interpreter and JIT Compiler: Both the Interpreter and JIT Compiler are
integral parts of the JVM. They work together to convert Java bytecode into
machine code for execution, with the Interpreter translating code line by line
and the JIT Compiler optimizing performance by compiling frequently used
bytecode into machine code.
Data Types In Java
• Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java
o Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
o Non-primitive data types: The non-primitive data types include Classes,
Interfaces, Strings and Arrays.
Variables
• A Variable is a Data Holder which stores the data, There are 2 types of Variables
1. Global Variable-:
• Static Variable / class Variable.
• Non Static Variable / Instance variable.
2. Local Variable
• Global Variable :-
1. A Global variable is a variable which is declared directly within class ,
outside method or constructor.
Variables
• Types of Global Variables-:
• Instance Variables / non static Variables :

1. These are non-static global variables defined within a class but outside any method.
2. They belong to an object and are initialized when the object is created.

• Scope of Instance Variable :


1. An Instance Variable can be accessed throughout the class and also can be accessed
outside class.
2. An Instance Variable can be accessed within same class by using this keyword.
3. Instance variable can be accessed outside class using Object reference.
Variables
• Types of Global Variables-:
• Static Variables :
1. A static variable is a class-level variable, shared among all instances (or objects) of the class.
2. The value of a static variable is common for all objects and can be changed, but the change will
reflect across all objects.

• Scope of Static Variable :


1. A Static Variable can be accessed throughout the class and also can be accessed outside the
class.
2. A Static Variable can be accessed within the same class using the class name directly.
3. Static Variables are shared across all objects of the class, meaning they hold the same value for
every instance.
Stack Area
• Stores method calls and local variables.
• LIFO (Last In, First Out)-: Stack follows this principle—what is added last
gets removed first.
• Memory is allocated when a method is called and deallocated when it ends.
• Speed: Faster memory allocation and retrieval compared to other areas like
Heap.
• Example: If a method calls another method, the details of the first method
are saved in the stack, and it resumes after the second method finishes.
Heap Area
• Purpose: Heap is used for storing objects and variables that need to persist
longer than a method execution, such as global objects.
• LIFO (Last In, First Out)-: Stack follows this principle—what is added last
gets removed first.
• Memory Scope: Exists only while methods or functions are running. Once
they finish, the memory is cleared automatically.
• Speed: Faster memory allocation and retrieval compared to other areas like
Heap.
• Example: If a method calls another method, the details of the first method
are saved in the stack, and it resumes after the second method finishes.
Literals
• What are Literals ?
• Literals are fixed values that are assigned to variables in a program.

• Integer Literals :- Represent whole numbers (e.g., 10, -25).


• Floating-Point Literals :- Represent decimal numbers (e.g., 3.14, -0.25).
• Character Literals :- Represent single characters enclosed in single quotes ('), like 'A',
'z'.

• String Literals: -: Represent a sequence of characters enclosed in double quotes ("), like
"Hello", "Java".
• Boolean Literals: Represent logical values, either true or false.
• Null Literal: Represents the absence of any value or object reference (null).
Wrapper Class
• What Are Wrapper Classes ?
• A Wrapper Class is used to convert primitive data types (like int, char,
boolean) into objects.
• Example: Converting an int into an object of the class Integer.

• Why Do We Use Wrapper Classes ?


• Object Manipulation: Java collections (like ArrayList, HashMap) only work with
objects, not primitive data types. Wrapper classes allow primitives to be used in
collections.
• Additional Methods: Wrapper classes come with useful methods for
manipulating data (e.g., converting a number to a string).
• Data Type Conversion: Helps in converting primitive data types to objects
(Boxing) and objects back to primitive data types (Unboxing).
Wrapper Class
• List of Wrapper Classes :-
• Primitive Type → Wrapper Class

• byte → Byte
• short → Short

• int → Integer

• long → Long

• float → Float

• double → Double

• char → Character

• boolean → Boolean
Type Conversion
• What is Type Conversion ?
• Type Conversion is the process of converting one data type into another in Java.

• It helps in ensuring compatibility between different data types during


calculations or assignments.
• Types of Type Conversion:

• Implicit Type Conversion (Type Casting):


• Automatically performed by Java when converting a smaller data type to a larger
data type (e.g., int to double).
• No data loss occurs.
Type Conversion
• Types of Type Conversion:

• Explicit Type Conversion (Type Casting):


• Requires the programmer to manually convert one data type to another using a cast operator
(e.g., (double) or (int)).
• Data loss may occur, especially when converting larger data types to smaller ones (e.g., double
to int).

• Key Points to Remember:


• Widening Conversion: Safe conversion from smaller to larger data types (e.g., byte → short →
int → long → float → double).
• Narrowing Conversion: Risky conversion from larger to smaller data types, requiring explicit
casting (e.g., double → float → long → int → short → byte).
• Loss of Precision: Occurs during narrowing conversion (e.g., decimal part is lost when converting
double to int).
• String Conversion: Non-numeric data types like String can also be converted to numeric types
using methods like Integer.parseInt() or Double.parseDouble().
Arithmetic Operators
• What Are Arithmetic Operators ?

• Arithmetic operators are used in Java to perform basic mathematical


operations like addition, subtraction, multiplication, division, and modulus.
• These operators work with numerical values (e.g., int, float, double).

• Types of Arithmetic Operators -:


• Addition (+):
 Adds two values together.

 Example: int sum = 5 + 3; // Result: 8

• Subtraction (-):
§ Subtracts one value from another.

§ Example: int difference = 10 - 4; // Result: 6


Arithmetic Operators
• Types of Arithmetic Operators -:
• Multiplication (*):
 Multiplies two values.

 Example: int product = 3 * 7; // Result: 21

• Division (/):
§ Divides one value by another. Returns the quotient.

§ Example: int quotient = 15 / 3; // Result: 5

§ Note: Dividing integers results in integer division (e.g., 7 / 2 = 3). Use floating-point
numbers for precise division.
• Modulus (%):
§ Returns the remainder of division.

§ Example: int remainder = 10 % 3; // Result: 1


Relational Operators
• What Are Relational Operators ?

• Relational operators are used to compare two values or expressions.

• The result of a relational operation is always a boolean value: true or


false.
• Types of Relational Operators -:
• Equal To (==) :
 Checks if two values are equal.

 Example: 5 == 5 // true

• Not Equal To (!=) :


§ Checks if two values are not equal.

§ Example: 5 != 3 // true

• Greater Than (>) :


§ Checks if the left value is greater than the right value.

§ Example: 7 > 5 // true


Relational Operators
• Types of Relational Operators -:
• Less Than (<) :
 Checks if the left value is less than the right value.

 Example: 3 < 8 // true

• Greater Than or Equal To (>=):


§ Checks if the left value is greater than or equal to the right value.

§ Example: 6 >= 6 // true

• Less Than or Equal To (<=):


§ Checks if the left value is less than or equal to the right value.

§ Example: 4 <= 5 // true


Logical Operators
• What Are Logical Operators ?

• Logical operators are used to combine multiple boolean expressions or conditions

• They are commonly used in decision-making statements like if, while, and for.

• Types of Logical Operators -:


• AND (&&):
 Returns true only if both conditions are true.

 Example: (5 > 3 && 8 > 6) // true

• OR (||):
§ Returns true if at least one condition is true.

§ Example: (5 > 3 || 8 < 6) // true

• NOT (!):
§ Negates or reverses the value of a boolean expression (i.e., true becomes false and false
becomes true).
§ Example: !(5 > 3) // false
If else statement
• What is an if-else Statement?

• If-else is a conditional statement used to execute code based on whether


a condition is true or false.
• It helps in making decisions in a program by allowing different actions
depending on the condition.
• Syntax of if-else:
If else if statement
• What is if-else if?

• The if-else if statement is used to check multiple conditions in a


program.
• It allows the program to execute different blocks of code based on which
condition is true.
• Syntax of if-else:
Ternary
• What is the Ternary Operator?

• The ternary operator is a shorthand for if-else statements.

• It is used to evaluate a condition and return one of two values based on


whether the condition is true or false.
• It is also called the conditional operator because it works with
conditions.
• Syntax :
Switch Statement
• What is a Switch Statement ?

• A switch statement is a control flow statement used to execute one block


of code out of multiple options based on a matching value.
• It simplifies cases where you need to compare a single variable or
expression against multiple possible values.
• Syntax -:
Need loop
• What is a Loop ?

• A loop is a programming structure used to repeat a block of code


multiple times.
• It helps in performing repetitive tasks efficiently without writing the same
code again and again.
• Why Do We Need Loops?
• Automation : Loops eliminate the need for manually writing repetitive code,
saving time and effort. Example: Printing numbers from 1 to 10 using a loop
instead of writing 10 print statements.
• Performing Bulk Operations: Useful for scenarios like processing large datasets,
performing calculations on a group of elements, or automating tasks.
While loop
• What is a While Loop ?

• A while loop is a control flow statement that allows code to be executed


repeatedly as long as a given condition is true.
• A while loop is helpful when you don't know how many times your code
needs to run. It keeps repeating as long as a certain condition is true.
Once the condition becomes false, the loop stops. This is useful for
situations where the number of repetitions depends on something that
changes during the program, like user input or calculations.
• Syntax -:

• If the condition is false from the start, the loop won’t execute even once.
Do-While loop
• What is a Do-While Loop?

• A do-while loop is like a while loop, but the key difference is that it
always executes the code at least once, even if the condition is false.
• The condition is checked after the code runs.
• Syntax -:

• The loop body is executed first.


• The condition is evaluated after the execution of the loop body.
• Difference from While Loop:
• While Loop: The condition is checked before executing the code.
• Do-While Loop: The condition is checked after executing the code.
For loop
• What is a For Loop ?

• A for loop is a control flow statement used to repeat a block of code a


specific number of times
• It is ideal when the number of iterations is known beforehand.
• Syntax -:

• Initialization: Starts the loop variable (e.g., int i = 0).


• Condition: Checks whether the loop should continue (e.g., i < 10).
• Update: Updates the loop variable after each iteration (e.g., i++).
• Example:
Nested For loops
• Nested For Loops :

• You can use one loop inside another for handling multidimensional tasks
like matrix operations or patterns.
• It is ideal when the number of iterations is known beforehand.
• Example :
Which loop to use
• While Loop::

• Use when the number of iterations is not known in advance and depends
on a condition.
• Example: Repeating an action while a user has not entered a valid
password.
• Do-While Loop:
• Use when you want the code to execute at least once, regardless of the
condition.
• Example: Prompting a user for input until they enter valid data.

• For Loop:
• Use when you know the exact number of iterations beforehand.
• Example: Counting numbers from 1 to 10.
Class And Object Theory
• What is a Class ?

• A class is a blueprint or template used to create objects.


• It defines the properties (variables) and methods (functions) that an object will
have.
• Example:

• What is an Object ?
• An object is an instance of a class.
• It is a real-world entity that is created using the class blueprint.
• Example -:
Class And Object Practical
• Example: Managing Student Details

• Imagine you want to manage student information in a school. You can create
a class to store details like name, age, and marks, and then use objects to
interact with the data.
• Step 1: Define the Class
Class And Object Practical
• Step 2: Use Objects • Outcomes from This Example:
• Class :- The Student class acts as a
blueprint that defines attributes (name,
age, marks) and behavior
(displayDetails() method).
• Object :- Each object (student1,
student2) represents an individual
student with its own values for attributes.
• Assigning Values :- Values are assigned
directly to the object’s properties (e.g.,
student1.name = "Rahil";).
• Calling Methods :- Methods like
displayDetails() are called using the
object to perform actions.
Class And Object Practical
• Task 1: Create a Class to Represent an Animal

• Objective: Imagine you are tasked with representing an animal in a zoo using a
class.
• Instructions:
 Think about the important details an animal might have (e.g., species, weight, diet, habitat).

 Think of actions the animal might perform (e.g., eating, sleeping, making sounds).

 Implement the class and create objects for different animals like a lion, an elephant, etc.

• Task 2: Create a Class for a Shop

• Objective: Design a class to represent a shop or store.

• Instructions:
§ Think about what aspects of a shop would be important (e.g., name, type of goods, location).

§ Consider the actions a shop might perform (e.g., selling goods, displaying inventory).

§ Create objects for different shops and simulate their behavior (e.g., selling items)
Methods
• What Are Methods ?

• A method is a block of code that performs a specific task in a program.

• They are executed only when called and can take inputs (parameters) and return
outputs.
• Structure of a Method

• Access Modifier :- Defines the method's visibility (e.g., public, private,


protected).
• Return Type :- Specifies the data type the method returns. Use void if no value is
returned.
• Method Name :- Describes the action performed by the method.

• Parameters (Optional) :- Input values that the method processes.

• Method Body :- Contains the code to be executed.

• Syntax of a Method :-
Methods
• Types of Methods
• Void Methods :-
 Perform an action but do not return any value.

 Example - ;

• Return Methods :-
 Perform an action and return a value to the caller.
 Example -: Calculating and returning the sum of two numbers.
Methods
• Types of Methods
• Parameterized Methods :-
 Take input values (parameters) to perform tasks.
 Example: Multiplying two numbers passed as inputs.

• Non-Parameterized Methods :-
 Do not take any inputs and execute the same task every time.

 Example -:
Methods
• Types of Methods
• Static Methods :-
 Belong to the class rather than objects of the class. Can be called without creating an object.

 Example -:

• Instance Methods :-
 Belong to objects of the class. Require an object to be called.

 Example :-
Methods
• How to Call a Method?
• Create an Object :-
 For instance methods, use an object to call the method:

 Example -:

• Call Static Methods :-


 Call directly using the class name:

 Example :-
Method Overloading
• What is Method Overloading?
• Method Overloading is a feature in Java where multiple methods in the same class
have the same name but different parameters.
• It allows a class to perform similar operations with different types or numbers of
arguments.
• The compiler differentiates the methods based on their method signature (method
name + parameter list).

• Rules of Method Overloading


• Methods must have the same name but a different parameter list.
• Return type alone is not sufficient for method overloading. The parameters must
differ.
• Access modifiers can vary in overloaded methods.
Method Overloading
• Example
Constructor
• Special type of method which is used to initialize the object.
• constructs the values at the time of object creation
• Is one of the member of class just like method and variable.
• Memory Allocation – When constructor is initialized (Object
instantiation), memory is allocated to the object of the class
• Every time an object is created using the new() keyword, at least one
constructor is called
• Rules for creating Java constructor
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized
Constructor - Types
• No Org Constructor / Default Constructor
• Default Constructor is type of Constructor which is created by the compiler.
• • Default Constructor will always be non-parameterized.
• • Default constructor is created only if there is no custom constructors.
• • Default Constructor is used or created in order to assign default values to the states present
in class.
Constructor - Types
• Parameterized Constructor
• Any Constructor which is created by the user or by the developer is called as
Custom / Parameterized Constructor.
• • Custom / Parameterized Constructor must be same as that of the class name.
• • Custom / Parameterized Constructor can be parameterized or non parameterized.
• • In a class there can be either Custom constructor or default Constructor but not
both.
• • Custom Constructor is needed in order to assign dynamic values or user defined
values to the states present in the object
Constructor - Types
• Parameterized Constructor
Static block
• What is a Static Block ?
• Static Block is a block of code that belongs to the class rather than any object of
the class.
• It is used to initialize static variables or to perform operations that need to be
executed only once when the class is loaded into memory.
• Multiple static blocks are allowed in a class, and they are executed in the order they
appear.

• Features of Static Block:


• Executed Before main() Method :- The static block runs automatically when the
class is loaded, even before the main() method.
• One-Time Execution :- It is executed only once, no matter how many objects of the
class are created.
Non Static block
• What is a Non-Static Block?
• Non-Static Block (or Instance Block) is a block of code that is executed whenever
an object of the class is created.
• It is used to initialize static variables or to perform operations that need to be
executed only once when the class is loaded into memory.

• Features of Non-Static Block:


• Executed Before Constructor :- Non-static blocks are executed before the
constructor is invoked, but after the static blocks.
• Runs for Every Object: :-The block executes every time a new object is created.
Encapsulation
• What is Encapsulation ?
• Encapsulation is a fundamental principle of Object-Oriented Programming (OOP)
that involves wrapping data and methods that operate on that data within a single
unit, typically a class.
• It is a way to achieve data hiding, ensuring that the internal details of an object are
protected from unauthorized or accidental access.
• Encapsulation provides controlled access to the class’s data through public getter
and setter methods.

• Key Characteristics of Encapsulation


• Data Hiding :-
§ By declaring variables as private, direct access is restricted.
§ Data can only be accessed or modified through methods like getters and setters.
• Controlled Access:
§ Getter and setter methods allow you to validate or restrict how the data is accessed and
updated.
Encapsulation
• Steps to Achieve Encapsulation
• Declare variables in a class as private.
• Provide public getter and setter methods to control the access to these variables.
• Access variables only through these methods to enforce validation and data
integrity.

• Example -: Encapsulation in Java

• Getters and setter method example -: Getter and Setter in Java


this keyword
• What is the this Keyword?
• The this keyword in Java refers to the current instance of the class.
• It provides a way to refer to the object that is currently being acted upon.

• Uses of the this Keyword


• To Refer to Instance Variables :- Used to resolve ambiguity when local variables or
method parameters have the same name as instance variables.

• To Call Current Class Methods :- Used to call another method in the same class
from a method.
this keyword
• Uses of the this Keyword
• To Call Current Class Constructor :- Used for constructor chaining (calling one
constructor from another within the same class).


• To Return the Current Class Object :- Helps return the current instance of the
class.

• To Pass Current Object as a Parameter :- Allows passing the current object as an


argument to other methods or constructors.
String
• What is a String ?

• A String in Java is a sequence of characters stored together as a single unit.


It is used to handle text data like names, messages, or sentences.
• Strings are immutable, which means once a String is created, its value
cannot be modified. Instead, any changes create a new String.
• Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
String
• How to create a string object ?
• By String Literal :- String literals are created using double quotes.
§ String Constant Pool (SCP) :- When a string literal is created, the JVM checks the String Constant Pool
for existing strings.
§ If the string exists, it reuses the reference to the pooled instance.
§ If the string doesn’t exist, a new object is created and added to the pool.

• By new Keyword :-
• Strings can also be created using the new keyword.
• Example:
• In this case: A new String object is created in the heap (non-pool), The literal "Welcome" is stored in
the String Constant Pool separately.
StringBuffer and StringBuilder
• What are StringBuffer and StringBuilder?

• Both StringBuffer and StringBuilder are classes used to create and


manipulate mutable (modifiable) sequences of characters.
• Unlike the immutable String class, these classes allow dynamic modifications
such as appending, replacing, or deleting characters.
• SCP is Irrelevant for StringBuffer/StringBuilder:
• Unlike String, objects of StringBuffer and StringBuilder are not stored in SCP
because they are mutable
• They are always created in the heap memory, as SCP is designed for immutable
Strings to ensure memory efficiency.
StringBuffer and StringBuilder
Need of Array
• What is an Array ?
• An array is a data structure used to store multiple values of the same type under a single
variable name.
• Elements in an array are stored in a contiguous memory location and are accessed using
an index.

• Why Do We Need Arrays?


• Efficient Data Management :- Arrays allow you to store a large number of values (e.g., 100
marks of students) without needing to create individual variables for each value.
• Fixed Size and Memory Allocation : - When an array is created, a specific amount of
memory is allocated for it, making memory management more efficient.
• Index-Based Access :- Elements in an array can be accessed or modified using their index,
starting from 0 for the first element.
• Group Similar Data :- Arrays help in organizing related data under a single name (e.g.,
temperatures of a week, list of employee IDs).
• Looping for Operations :- Using loops, you can easily perform operations (e.g., calculating
the total, searching) on all elements of an array.
Creation of Array
• Steps to Create an Array in Java
• Declaration :-
 Declare the array by specifying the data type and array name.

 Syntax:

 Example:

• Memory Allocation:
§ Allocate memory for the array using the new keyword and define its size.

§ Syntax:

§ Example :

• Initialization :-
§ Assign values to individual elements of the array using their indices.

§ Syntax:

§ Example :
Creation of Array
• Steps to Create an Array in Java
• Shortcut (Declare + Allocate + Initialize):
 Combine all steps into a single line.

 Syntax:

 Example:
Jagged and 3D array
• What is a Jagged Array ?
• A jagged array is an array of arrays where the sub-arrays can have different
lengths.
• It is also known as an uneven array.
• Jagged arrays are especially useful for representing irregular data structures, like a
triangle or a matrix with unequal rows.
Jagged and 3D array
• What is a 3D Array ?
• A 3D Array is an array of arrays of arrays, meaning it has elements arranged in three
dimensions.

• It is useful for storing data in three dimensions, like a group of tables or a


cube-shaped space.
Drawbacks of Arrays
• Fixed Size:
• The size of an array must be declared at the time of creation and cannot be changed later.
• This leads to either wasted memory (if the array size is too large) or insufficient memory (if the array size is
too small).

• Homogeneous Data:
• Arrays can only store elements of the same data type.
• This makes them unsuitable for storing mixed data types (e.g., combining integers, strings, and floats).

• No Dynamic Memory Allocation:


• Arrays do not provide flexibility in terms of memory allocation at runtime.
• For dynamic resizing, other data structures like ArrayList (in Java) are preferred.

• No Built-in Methods:
• Arrays lack built-in methods for common operations like searching, sorting, or resizing.
• You need to write additional code or use external libraries for these tasks.

• Inefficient Insertion and Deletion:


• Adding or removing elements in the middle of an array is time-consuming, as it requires shifting elements to maintain order.
• Arrays are not ideal for scenarios requiring frequent modifications to data.

• No Direct Support for Complex Data Structures:


• Arrays cannot directly represent advanced structures like linked lists, stacks, or queues. You need to implement
these separately.
Array of Objects
• What is an Array of Objects ?
• An array of objects is a collection of objects stored in a single array.
• It allows multiple instances of a class to be stored and managed together efficiently.
• Useful for scenarios where you need to store and process data for multiple objects of the same
type.
• Creating an Array Of Objects In Java

• Declaration :- To declare an array of objects, specify the class name followed by square
brackets [ ].

• Instantiation :- After declaring the array, instantiate it using the new keyword, specifying the
size of the array.

• Initialize Objects in the Array: Assign individual objects to array elements.


Enhanced for loop
• What is an Enhanced for Loop ?
• The Enhanced for Loop (or for-each loop) is a simplified version of the traditional for loop,
designed to iterate over arrays and collections effortlessly.
• It eliminates the need for managing an index or counter, making the code more concise and
readable.

• Syntax of Enhanced for Loop

You might also like