SlideShare a Scribd company logo
Arrays and ArrayLists
• Arrays and ArrayLists are both used in Java to store collections of elements,
but they have significant differences in terms of their properties, usage, and
behavior.
• Key Characteristics:
• Fixed Size: Once an array is created, its size cannot be changed. The size is
determined when the array is initialized.
• Index-Based: Elements in an array are accessed using an index, starting from
0.
• Homogeneous: All elements in an array must be of the same type.
• Memory Allocation: Arrays are stored in contiguous memory locations.
// Declaration and Initialization
int[] numbers = new int[5]; // An array of integers with 5 elements
// Assignment
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
// Accessing Elements
System.out.println(numbers[0]); // Output: 10
// Array Initialization with Values
int[] scores = {85, 90, 75, 60, 95}; // An array with 5 elements
Pros and cons
• Efficiency: Arrays provide fast access to elements since they are
stored in contiguous memory.
• Predictable Memory Use: The fixed size of arrays ensures that the
memory required is known at compile time.
• Cons:
• Inflexibility: The size of an array cannot be changed once it is created.
• Manual Management: Inserting or removing elements involves
manual shifting of elements, which can be error-prone.
arraylist in java a comparison of the array and arraylist
class Student {
// Instance variables
String name;
int rollNumber;
double grade;
// Constructor
public Student(String name, int rollNumber, double
grade) {
this.name = name;
this.rollNumber = rollNumber;
this.grade = grade;
}
// Method to display student details
public void displayStudentInfo() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Grade: " + grade);
public class StudentArrayExample {
public static void main(String[] args) {
// Create an array to store 3 Student objects
Student[] students = new Student[3];
// Create Student objects and store them in the
array
students[0] = new Student("Alice", 101, 85.5);
students[1] = new Student("Bob", 102, 90.0);
students[2] = new Student("Charlie", 103, 78.8);
// Display the details of each student
System.out.println("Student Details:");
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + ":");
students[i].displayStudentInfo();
System.out.println();
}
}
ARRAYLIST
Definition:
An ArrayList is a resizable array implementation of the List interface in Java. It is part of the
java.util package and can grow or shrink dynamically as elements are added or removed.
Key Characteristics:
•Resizable: The size of an ArrayList can dynamically change as elements are added or
removed.
•Index-Based: Similar to arrays, elements in an ArrayList are accessed using an index,
starting from 0.
•Heterogeneous in Terms of Wrapper Types: ArrayLists can hold objects of any type
(including custom objects), but only objects—not primitives. However, Java autoboxes
primitives into their corresponding wrapper types (e.g., int to Integer).
•Built-in Methods: ArrayLists provide a variety of methods to manipulate the collection,
such as adding, removing, and searching for elements.
Pros:
•Flexibility: ArrayLists can grow and shrink dynamically, which makes them
more flexible than arrays.
•Convenience: ArrayLists provide many built-in methods for common
operations like adding, removing, or searching for elements.
•No Manual Management: When elements are added or removed,
ArrayLists automatically handle resizing and shifting of elements.
Cons:
•Performance Overhead: ArrayLists may have a slight performance
overhead due to dynamic resizing and the fact that they hold objects (which
introduces some additional memory overhead compared to primitive
arrays).
•Not Suitable for Primitives: Since ArrayLists can only hold objects,
primitives like int and char are automatically converted to their wrapper types
(like Integer and Character), which can introduce additional overhead.
import java.util.ArrayList;
ArrayList<Integer> numbers = new ArrayList<>();
// An ArrayList of Integer objects
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Accessing elements
System.out.println(numbers.get(0)); // Output: 10
// Removing an element
numbers.remove(1); // Removes the element at index 1 (which is 20)
// Dynamic resizing
numbers.add(40); // The ArrayList now has 3 elements: 10, 30, 40
Traditional for Loop
for (initialization; termination condition;
increment/decrement) {
// Statements to execute in each iteration
}
public class TraditionalForLoopArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Iterating over array using
traditional for loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " +
numbers[i]);
}
}
}
import java.util.ArrayList;
public class TraditionalForLoopArrayList {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Iterating over ArrayList
using traditional for loop:");
for (int i = 0; i < fruits.size(); i++) {
System.out.println("Element at index " + i
+ ": " + fruits.get(i));
}
}
}
Enhanced for Loop (For-Each Loop)
import java.util.ArrayList;
public class EnhancedForLoopArrayList {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Iterating over ArrayList using enhanced
loop:");
for (String fruit : fruits) {
System.out.println("Element: " + fruit);
}
}
}
for (Type element : collection)
{ // Statements to execute for each element
}
public class EnhancedForLoopArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Iterating over array
using enhanced for loop:");
for (int num : numbers) {
System.out.println("Element: " +
num);
}
}
Java ArrayList
• Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there
is no size limit. We can add or remove elements anytime. So, it is much more flexible than the
traditional array. It is found in the java.util package. It is like the Vector in C++.
• The ArrayList in Java can have the duplicate elements also. It implements the List interface so we
can use all the methods of the List interface here. The ArrayList maintains the insertion order
internally.
• It inherits the AbstractList class and implements List interface.
• The important points about the Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because the array works on an index basis.
• In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.
• We can not create an array list of the primitive types, such as int, float, char, etc. It is required to
use the required wrapper class in such cases. For example:
Creating and Using ArrayLists
•Declaration and Initialization:
•Syntax: ArrayList<Type> listName = new ArrayList<>();
•Example: ArrayList<String> names = new ArrayList<>();
•Adding Elements:
•Use add() method: names.add("Alice");
•Accessing Elements:
•Use get() method: String name = names.get(0);
•Modifying Elements:
•Use set() method: names.set(1, "Bob");
•Removing Elements:
•By index: names.remove(2);
•By value: names.remove("Alice");
•Size of the ArrayList:
•Use size() method: int size = names.size();
•Checking if an Element Exists:
•Use contains() method: boolean hasAlice = names.contains("Alice");
Wrapper classes in Java
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.
Use of Wrapper classes in Java
• Java is an object-oriented programming language, so we need to deal
with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we need
to use the wrapper classes.
• Change the value in Method: Java supports only call by value. So, if we pass
a primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal
with objects.
• Collection Framework: Java collection framework works with objects only.
All classes of the collection framework (ArrayList, LinkedList, Vector,
HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with
objects only.
arraylist in java a comparison of the array and arraylist
Autoboxing
• The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
• Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicity
Integer j=a;//
autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
Unboxing
• The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to use the intValue() method
of wrapper classes to convert the wrapper type into primitives.
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
2D Array
• 2D array can be defined as an array of arrays. The 2D array is organized
as matrices which can be represented as the collection of rows and
columns.
• How to declare 2D Array
• The syntax of declaring two dimensional array is very much similar to
that of a one dimensional array, given as follows.
1.int arr[max_rows][max_columns];
arraylist in java a comparison of the array and arraylist
How do we access data in a 2D array
• Due to the fact that the elements of 2D arrays can be random accessed. Similar to one dimensional arrays, we can access
the individual cells in a 2D array by using the indices of the cells. There are two indices attached to a particular cell, one
is its row number while the other is its column number.
• However, we can store the value stored in any particular cell of a 2D array to some variable x by using the following
syntax.
1. int x = a[i][j];
• where i and j is the row and column number of the cell respectively.
• We can assign each cell of a 2D array to 0 by using the following code:
1. for ( int i=0; i<n ;i++)
2. {
3. for (int j=0; j<n; j++)
4. {
5. a[i][j] = 0;
6. }
7. }
Java String
• In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
1.char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2.String s=new String(ch);
• is same as:
1.String s="javatpoint";
• Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String
class is used to create a string object.
• How to create a string object?
• There are two ways to create String object:
1.By string literal
2.By new keyword
1) String Literal
• Java String literal is created by using double quotes. For Example:
String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the
pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1.String s1="Welcome";
2.String s2="Welcome";//It doesn't create a new instance
• String objects are stored in a special memory area known as the "string
constant pool".
• Why Java uses the concept of String literal?
• To make Java more memory efficient (because no new objects are
created if it exists already in the string constant pool).
2) By new keyword
1.String s=new String("Welcome");//
creates two objects and one reference variable
• In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-
pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Anonymous class
• An anonymous class in Java is a local class without a name, defined
and instantiated all at once. Anonymous classes are often used when
you need to override the behavior of an existing class or interface
without creating a separate named class.
• When to Use Anonymous Classes:
• Simplification: When you need to create a simple, one-time-use
implementation of an interface or abstract class.
• Conciseness: When you want to avoid the verbosity of creating a
separate class file for a small piece of functionality.
// Base class: Cycle
class Cycle {
// Method to display a message for Cycle
public void msg() {
System.out.println("This is a Cycle.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the base class Cycle
Cycle cycle = new Cycle();
cycle.msg(); // Output: This is a Cycle.
}
}
o/p:
// Base class: Cycle
class Cycle {
// Method to display a message for Cycle
public void msg() {
System.out.println("This is a Cycle.");
}
}
// Child class: Tricycle (inherits from Cycle)
class Tricycle extends Cycle {
// Method to display a message for Tricycle
@Override
public void msg() {
System.out.println("This is a Tricycle.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the base class
Cycle
Cycle cycle = new Tricycle();
cycle.msg(); // Output: This is a
Cycle.
}
}
// Base class: Cycle
class Cycle {
// Method to display a message for Cycle
public void msg() {
System.out.println("This is a Cycle.");
}
}
// Child class: Tricycle (inherits from Cycle)
class Tricycle extends Cycle {
// Method to display a message for Tricycle
@Override
public void msg() {
System.out.println("This is a Tricycle.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the base class Cycle
Cycle cycle = new Cycle()
{
public void msg() {
System.out.println("This is a
Tricycle.");
}
};
cycle.msg(); // Output: This is a Cycle.
Cycle cycle1 = new Cycle();
cycle1.msg();
}
}
// Base class: Cycle
class Cycle {
// Method to display a message for Cycle
public void msg() {
System.out.println("This is a Cycle.");
}
}
// Child class: Tricycle (inherits from Cycle)
class Tricycle extends Cycle {
// Method to display a message for Tricycle
@Override
public void msg() {
System.out.println("This is a Tricycle.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the base
class Cycle
Cycle cycle = new Cycle();
cycle.msg(); // Output: This is a
Cycle.
}
}
• o/p:
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist

More Related Content

Similar to arraylist in java a comparison of the array and arraylist (20)

Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
Shahriar Robbani
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
Rajeev Uppala
 
Array list
Array listArray list
Array list
vishal choudhary
 
22.ppt
22.ppt22.ppt
22.ppt
BharaniDaran15
 
A2003822018_21789_17_2018_09. ArrayList.ppt
A2003822018_21789_17_2018_09. ArrayList.pptA2003822018_21789_17_2018_09. ArrayList.ppt
A2003822018_21789_17_2018_09. ArrayList.ppt
RithwikRanjan
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptxM251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
arraylistinjava.pptx
arraylistinjava.pptxarraylistinjava.pptx
arraylistinjava.pptx
dintakurthigayathri9
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
ArrayList class and useful methods.pptx
ArrayList class and useful methods.pptxArrayList class and useful methods.pptx
ArrayList class and useful methods.pptx
Abid523408
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
charan kumar
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
dplunkett
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
CF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworksCF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworks
mpfbaa
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
veerendranath12
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
A2003822018_21789_17_2018_09. ArrayList.ppt
A2003822018_21789_17_2018_09. ArrayList.pptA2003822018_21789_17_2018_09. ArrayList.ppt
A2003822018_21789_17_2018_09. ArrayList.ppt
RithwikRanjan
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptxM251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
ArrayList class and useful methods.pptx
ArrayList class and useful methods.pptxArrayList class and useful methods.pptx
ArrayList class and useful methods.pptx
Abid523408
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
charan kumar
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
dplunkett
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!
 
CF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworksCF5_Unit4.ppt.pdf java collection frameworks
CF5_Unit4.ppt.pdf java collection frameworks
mpfbaa
 

More from PriyadharshiniG41 (20)

artificial intelligence agents and its environment
artificial intelligence agents and its environmentartificial intelligence agents and its environment
artificial intelligence agents and its environment
PriyadharshiniG41
 
Knapsack problem based questions for practice
Knapsack problem based questions for practiceKnapsack problem based questions for practice
Knapsack problem based questions for practice
PriyadharshiniG41
 
Presentation on the artificial intelligenc
Presentation on the artificial intelligencPresentation on the artificial intelligenc
Presentation on the artificial intelligenc
PriyadharshiniG41
 
Presentation on the artificial intelligenc
Presentation on the artificial intelligencPresentation on the artificial intelligenc
Presentation on the artificial intelligenc
PriyadharshiniG41
 
Presentation on the artificial intelligence
Presentation on the artificial intelligencePresentation on the artificial intelligence
Presentation on the artificial intelligence
PriyadharshiniG41
 
advanced java programming paradigms presentation
advanced java programming paradigms presentationadvanced java programming paradigms presentation
advanced java programming paradigms presentation
PriyadharshiniG41
 
types of operating system an overview of the topics.pptx
types of  operating  system an overview of the topics.pptxtypes of  operating  system an overview of the topics.pptx
types of operating system an overview of the topics.pptx
PriyadharshiniG41
 
Philosophy of engineering unit one by SRM
Philosophy of engineering unit one by SRMPhilosophy of engineering unit one by SRM
Philosophy of engineering unit one by SRM
PriyadharshiniG41
 
MYSQL-database basic queries for good understanding
MYSQL-database basic queries for good understandingMYSQL-database basic queries for good understanding
MYSQL-database basic queries for good understanding
PriyadharshiniG41
 
multithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptxmultithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
java basics concepts and the keywords needed
java basics concepts and the keywords neededjava basics concepts and the keywords needed
java basics concepts and the keywords needed
PriyadharshiniG41
 
interface in java explained in detailed form
interface in java explained in detailed forminterface in java explained in detailed form
interface in java explained in detailed form
PriyadharshiniG41
 
Abstraction encapsulation inheritance polymorphism
Abstraction encapsulation inheritance polymorphismAbstraction encapsulation inheritance polymorphism
Abstraction encapsulation inheritance polymorphism
PriyadharshiniG41
 
System Boot how it works in the operating system
System Boot how it works in the operating systemSystem Boot how it works in the operating system
System Boot how it works in the operating system
PriyadharshiniG41
 
An overview of antcolonyoptimization.ppt
An overview of antcolonyoptimization.pptAn overview of antcolonyoptimization.ppt
An overview of antcolonyoptimization.ppt
PriyadharshiniG41
 
BFS,DFS,Depth bound,Beam search,Iterative.pptx
BFS,DFS,Depth bound,Beam search,Iterative.pptxBFS,DFS,Depth bound,Beam search,Iterative.pptx
BFS,DFS,Depth bound,Beam search,Iterative.pptx
PriyadharshiniG41
 
recommendation system a topic in marketing analytics
recommendation system a topic in marketing analyticsrecommendation system a topic in marketing analytics
recommendation system a topic in marketing analytics
PriyadharshiniG41
 
understanding-cholera-a-comprehensive-analysis.pdf
understanding-cholera-a-comprehensive-analysis.pdfunderstanding-cholera-a-comprehensive-analysis.pdf
understanding-cholera-a-comprehensive-analysis.pdf
PriyadharshiniG41
 
combatting-malaria-strategies-for-prevention-and-treatment.pdf
combatting-malaria-strategies-for-prevention-and-treatment.pdfcombatting-malaria-strategies-for-prevention-and-treatment.pdf
combatting-malaria-strategies-for-prevention-and-treatment.pdf
PriyadharshiniG41
 
ant colony optimization working and explanation
ant colony optimization working and explanationant colony optimization working and explanation
ant colony optimization working and explanation
PriyadharshiniG41
 
artificial intelligence agents and its environment
artificial intelligence agents and its environmentartificial intelligence agents and its environment
artificial intelligence agents and its environment
PriyadharshiniG41
 
Knapsack problem based questions for practice
Knapsack problem based questions for practiceKnapsack problem based questions for practice
Knapsack problem based questions for practice
PriyadharshiniG41
 
Presentation on the artificial intelligenc
Presentation on the artificial intelligencPresentation on the artificial intelligenc
Presentation on the artificial intelligenc
PriyadharshiniG41
 
Presentation on the artificial intelligenc
Presentation on the artificial intelligencPresentation on the artificial intelligenc
Presentation on the artificial intelligenc
PriyadharshiniG41
 
Presentation on the artificial intelligence
Presentation on the artificial intelligencePresentation on the artificial intelligence
Presentation on the artificial intelligence
PriyadharshiniG41
 
advanced java programming paradigms presentation
advanced java programming paradigms presentationadvanced java programming paradigms presentation
advanced java programming paradigms presentation
PriyadharshiniG41
 
types of operating system an overview of the topics.pptx
types of  operating  system an overview of the topics.pptxtypes of  operating  system an overview of the topics.pptx
types of operating system an overview of the topics.pptx
PriyadharshiniG41
 
Philosophy of engineering unit one by SRM
Philosophy of engineering unit one by SRMPhilosophy of engineering unit one by SRM
Philosophy of engineering unit one by SRM
PriyadharshiniG41
 
MYSQL-database basic queries for good understanding
MYSQL-database basic queries for good understandingMYSQL-database basic queries for good understanding
MYSQL-database basic queries for good understanding
PriyadharshiniG41
 
multithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptxmultithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
java basics concepts and the keywords needed
java basics concepts and the keywords neededjava basics concepts and the keywords needed
java basics concepts and the keywords needed
PriyadharshiniG41
 
interface in java explained in detailed form
interface in java explained in detailed forminterface in java explained in detailed form
interface in java explained in detailed form
PriyadharshiniG41
 
Abstraction encapsulation inheritance polymorphism
Abstraction encapsulation inheritance polymorphismAbstraction encapsulation inheritance polymorphism
Abstraction encapsulation inheritance polymorphism
PriyadharshiniG41
 
System Boot how it works in the operating system
System Boot how it works in the operating systemSystem Boot how it works in the operating system
System Boot how it works in the operating system
PriyadharshiniG41
 
An overview of antcolonyoptimization.ppt
An overview of antcolonyoptimization.pptAn overview of antcolonyoptimization.ppt
An overview of antcolonyoptimization.ppt
PriyadharshiniG41
 
BFS,DFS,Depth bound,Beam search,Iterative.pptx
BFS,DFS,Depth bound,Beam search,Iterative.pptxBFS,DFS,Depth bound,Beam search,Iterative.pptx
BFS,DFS,Depth bound,Beam search,Iterative.pptx
PriyadharshiniG41
 
recommendation system a topic in marketing analytics
recommendation system a topic in marketing analyticsrecommendation system a topic in marketing analytics
recommendation system a topic in marketing analytics
PriyadharshiniG41
 
understanding-cholera-a-comprehensive-analysis.pdf
understanding-cholera-a-comprehensive-analysis.pdfunderstanding-cholera-a-comprehensive-analysis.pdf
understanding-cholera-a-comprehensive-analysis.pdf
PriyadharshiniG41
 
combatting-malaria-strategies-for-prevention-and-treatment.pdf
combatting-malaria-strategies-for-prevention-and-treatment.pdfcombatting-malaria-strategies-for-prevention-and-treatment.pdf
combatting-malaria-strategies-for-prevention-and-treatment.pdf
PriyadharshiniG41
 
ant colony optimization working and explanation
ant colony optimization working and explanationant colony optimization working and explanation
ant colony optimization working and explanation
PriyadharshiniG41
 
Ad

Recently uploaded (20)

Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Ad

arraylist in java a comparison of the array and arraylist

  • 1. Arrays and ArrayLists • Arrays and ArrayLists are both used in Java to store collections of elements, but they have significant differences in terms of their properties, usage, and behavior. • Key Characteristics: • Fixed Size: Once an array is created, its size cannot be changed. The size is determined when the array is initialized. • Index-Based: Elements in an array are accessed using an index, starting from 0. • Homogeneous: All elements in an array must be of the same type. • Memory Allocation: Arrays are stored in contiguous memory locations.
  • 2. // Declaration and Initialization int[] numbers = new int[5]; // An array of integers with 5 elements // Assignment numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; // Accessing Elements System.out.println(numbers[0]); // Output: 10 // Array Initialization with Values int[] scores = {85, 90, 75, 60, 95}; // An array with 5 elements
  • 3. Pros and cons • Efficiency: Arrays provide fast access to elements since they are stored in contiguous memory. • Predictable Memory Use: The fixed size of arrays ensures that the memory required is known at compile time. • Cons: • Inflexibility: The size of an array cannot be changed once it is created. • Manual Management: Inserting or removing elements involves manual shifting of elements, which can be error-prone.
  • 5. class Student { // Instance variables String name; int rollNumber; double grade; // Constructor public Student(String name, int rollNumber, double grade) { this.name = name; this.rollNumber = rollNumber; this.grade = grade; } // Method to display student details public void displayStudentInfo() { System.out.println("Name: " + name); System.out.println("Roll Number: " + rollNumber); System.out.println("Grade: " + grade); public class StudentArrayExample { public static void main(String[] args) { // Create an array to store 3 Student objects Student[] students = new Student[3]; // Create Student objects and store them in the array students[0] = new Student("Alice", 101, 85.5); students[1] = new Student("Bob", 102, 90.0); students[2] = new Student("Charlie", 103, 78.8); // Display the details of each student System.out.println("Student Details:"); for (int i = 0; i < students.length; i++) { System.out.println("Student " + (i + 1) + ":"); students[i].displayStudentInfo(); System.out.println(); } }
  • 7. Definition: An ArrayList is a resizable array implementation of the List interface in Java. It is part of the java.util package and can grow or shrink dynamically as elements are added or removed. Key Characteristics: •Resizable: The size of an ArrayList can dynamically change as elements are added or removed. •Index-Based: Similar to arrays, elements in an ArrayList are accessed using an index, starting from 0. •Heterogeneous in Terms of Wrapper Types: ArrayLists can hold objects of any type (including custom objects), but only objects—not primitives. However, Java autoboxes primitives into their corresponding wrapper types (e.g., int to Integer). •Built-in Methods: ArrayLists provide a variety of methods to manipulate the collection, such as adding, removing, and searching for elements.
  • 8. Pros: •Flexibility: ArrayLists can grow and shrink dynamically, which makes them more flexible than arrays. •Convenience: ArrayLists provide many built-in methods for common operations like adding, removing, or searching for elements. •No Manual Management: When elements are added or removed, ArrayLists automatically handle resizing and shifting of elements. Cons: •Performance Overhead: ArrayLists may have a slight performance overhead due to dynamic resizing and the fact that they hold objects (which introduces some additional memory overhead compared to primitive arrays). •Not Suitable for Primitives: Since ArrayLists can only hold objects, primitives like int and char are automatically converted to their wrapper types (like Integer and Character), which can introduce additional overhead.
  • 9. import java.util.ArrayList; ArrayList<Integer> numbers = new ArrayList<>(); // An ArrayList of Integer objects // Adding elements numbers.add(10); numbers.add(20); numbers.add(30); // Accessing elements System.out.println(numbers.get(0)); // Output: 10 // Removing an element numbers.remove(1); // Removes the element at index 1 (which is 20) // Dynamic resizing numbers.add(40); // The ArrayList now has 3 elements: 10, 30, 40
  • 10. Traditional for Loop for (initialization; termination condition; increment/decrement) { // Statements to execute in each iteration } public class TraditionalForLoopArray { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Iterating over array using traditional for loop:"); for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } } import java.util.ArrayList; public class TraditionalForLoopArrayList { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); System.out.println("Iterating over ArrayList using traditional for loop:"); for (int i = 0; i < fruits.size(); i++) { System.out.println("Element at index " + i + ": " + fruits.get(i)); } } }
  • 11. Enhanced for Loop (For-Each Loop) import java.util.ArrayList; public class EnhancedForLoopArrayList { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); System.out.println("Iterating over ArrayList using enhanced loop:"); for (String fruit : fruits) { System.out.println("Element: " + fruit); } } } for (Type element : collection) { // Statements to execute for each element } public class EnhancedForLoopArray { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Iterating over array using enhanced for loop:"); for (int num : numbers) { System.out.println("Element: " + num); } }
  • 12. Java ArrayList • Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++. • The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally. • It inherits the AbstractList class and implements List interface. • The important points about the Java ArrayList class are: • Java ArrayList class can contain duplicate elements. • Java ArrayList class maintains insertion order. • Java ArrayList class is non synchronized. • Java ArrayList allows random access because the array works on an index basis. • In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. • We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example:
  • 13. Creating and Using ArrayLists •Declaration and Initialization: •Syntax: ArrayList<Type> listName = new ArrayList<>(); •Example: ArrayList<String> names = new ArrayList<>(); •Adding Elements: •Use add() method: names.add("Alice"); •Accessing Elements: •Use get() method: String name = names.get(0); •Modifying Elements: •Use set() method: names.set(1, "Bob"); •Removing Elements: •By index: names.remove(2); •By value: names.remove("Alice"); •Size of the ArrayList: •Use size() method: int size = names.size(); •Checking if an Element Exists: •Use contains() method: boolean hasAlice = names.contains("Alice");
  • 14. Wrapper classes in Java • The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. • Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.
  • 15. Use of Wrapper classes in Java • Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the wrapper classes.
  • 16. • Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value. • Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes. • Synchronization: Java synchronization works with objects in Multithreading. • java.util package: The java.util package provides the utility classes to deal with objects. • Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
  • 18. Autoboxing • The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short. • Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.
  • 19. Wrapper class Example: Primitive to Wrapper //Java program to convert primitive into objects //Autoboxing example of int to Integer public class WrapperExample1{ public static void main(String args[]){ //Converting int into Integer int a=20; Integer i=Integer.valueOf(a);//converting int into Integer explicity Integer j=a;// autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a+" "+i+" "+j); }}
  • 20. Unboxing • The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives.
  • 21. //Java program to convert object into primitives //Unboxing example of Integer to int public class WrapperExample2{ public static void main(String args[]){ //Converting Integer to int Integer a=new Integer(3); int i=a.intValue();//converting Integer to int explicitly int j=a;//unboxing, now compiler will write a.intValue() internally System.out.println(a+" "+i+" "+j); }}
  • 22. 2D Array • 2D array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns.
  • 23. • How to declare 2D Array • The syntax of declaring two dimensional array is very much similar to that of a one dimensional array, given as follows. 1.int arr[max_rows][max_columns];
  • 25. How do we access data in a 2D array • Due to the fact that the elements of 2D arrays can be random accessed. Similar to one dimensional arrays, we can access the individual cells in a 2D array by using the indices of the cells. There are two indices attached to a particular cell, one is its row number while the other is its column number. • However, we can store the value stored in any particular cell of a 2D array to some variable x by using the following syntax. 1. int x = a[i][j]; • where i and j is the row and column number of the cell respectively. • We can assign each cell of a 2D array to 0 by using the following code: 1. for ( int i=0; i<n ;i++) 2. { 3. for (int j=0; j<n; j++) 4. { 5. a[i][j] = 0; 6. } 7. }
  • 26. Java String • In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: 1.char[] ch={'j','a','v','a','t','p','o','i','n','t'}; 2.String s=new String(ch); • is same as: 1.String s="javatpoint";
  • 27. • Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. • How to create a string object? • There are two ways to create String object: 1.By string literal 2.By new keyword
  • 28. 1) String Literal • Java String literal is created by using double quotes. For Example: String s="welcome"; • Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: 1.String s1="Welcome"; 2.String s2="Welcome";//It doesn't create a new instance
  • 29. • String objects are stored in a special memory area known as the "string constant pool". • Why Java uses the concept of String literal? • To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
  • 30. 2) By new keyword 1.String s=new String("Welcome");// creates two objects and one reference variable • In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non- pool).
  • 31. Java String Example public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by Java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }}
  • 32. Anonymous class • An anonymous class in Java is a local class without a name, defined and instantiated all at once. Anonymous classes are often used when you need to override the behavior of an existing class or interface without creating a separate named class. • When to Use Anonymous Classes: • Simplification: When you need to create a simple, one-time-use implementation of an interface or abstract class. • Conciseness: When you want to avoid the verbosity of creating a separate class file for a small piece of functionality.
  • 33. // Base class: Cycle class Cycle { // Method to display a message for Cycle public void msg() { System.out.println("This is a Cycle."); } } public class InheritanceExample { public static void main(String[] args) { // Create an object of the base class Cycle Cycle cycle = new Cycle(); cycle.msg(); // Output: This is a Cycle. } } o/p:
  • 34. // Base class: Cycle class Cycle { // Method to display a message for Cycle public void msg() { System.out.println("This is a Cycle."); } } // Child class: Tricycle (inherits from Cycle) class Tricycle extends Cycle { // Method to display a message for Tricycle @Override public void msg() { System.out.println("This is a Tricycle."); } } public class InheritanceExample { public static void main(String[] args) { // Create an object of the base class Cycle Cycle cycle = new Tricycle(); cycle.msg(); // Output: This is a Cycle. } }
  • 35. // Base class: Cycle class Cycle { // Method to display a message for Cycle public void msg() { System.out.println("This is a Cycle."); } } // Child class: Tricycle (inherits from Cycle) class Tricycle extends Cycle { // Method to display a message for Tricycle @Override public void msg() { System.out.println("This is a Tricycle."); } } public class InheritanceExample { public static void main(String[] args) { // Create an object of the base class Cycle Cycle cycle = new Cycle() { public void msg() { System.out.println("This is a Tricycle."); } }; cycle.msg(); // Output: This is a Cycle. Cycle cycle1 = new Cycle(); cycle1.msg(); } }
  • 36. // Base class: Cycle class Cycle { // Method to display a message for Cycle public void msg() { System.out.println("This is a Cycle."); } } // Child class: Tricycle (inherits from Cycle) class Tricycle extends Cycle { // Method to display a message for Tricycle @Override public void msg() { System.out.println("This is a Tricycle."); } } public class InheritanceExample { public static void main(String[] args) { // Create an object of the base class Cycle Cycle cycle = new Cycle(); cycle.msg(); // Output: This is a Cycle. } } • o/p: