The document provides information about Java Collection Framework. It discusses that the Collection Framework provides a unified architecture for storing and manipulating groups of objects through interfaces like Set, List, Queue etc. and their implementation classes like ArrayList, LinkedList etc. It also describes various collection interfaces like Collection, List, Queue, Deque and Iterator along with their methods. It provides examples of using ArrayList and LinkedList to demonstrate common collection operations.
The document discusses various topics related to object oriented programming in Java including arrays, foreach loops, collection classes like ArrayList, and differences between generic and non-generic collections. It provides examples of how to create and use arrays, foreach loops, ArrayList to store and retrieve elements, commonly used ArrayList methods, and advantages of generic collections over non-generic collections in Java.
This document discusses arrays in Java. It begins by defining arrays as ordered collections of homogeneous values of fixed length, where each element has an index number beginning with 0. It then covers declaring and initializing arrays, including arrays of objects. The document discusses selecting array elements by index, passing arrays as parameters, and using arrays for tasks like letter frequency counting. It also introduces two-dimensional arrays and ArrayLists, and contrasts arrays with linked lists.
Packages and Java Library: Introduction, Defining Package, Importing Packages and
Classes into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang
Package and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Autoboxing and Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class,
Time Package, Class Instant (java. time. Instant), Formatting for Date/Time in Java, Temporal
Adjusters Class, Temporal Adjusters Class.
Java. lang Package and its Classes:
The most important classes are of lang are
• Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at runtime.
o protected Object clone()
o boolean equals(Object obj)
o protected void finalize()
o Class getClass()
o int hashCode()
o void notify()
o void notifyAll()
o void wait()
o String toString()
• The wrapper classes
o Boolean
o Character
o Integer
o Short
o Byte
o Long
o Float
o Double
• The classes String, StringBuffer, and StringBuilder similarly provide commonly used
operations on character strings.
• Class Throwable encompasses objects that may be thrown by the throw statement.
Subclasses of Throwable represent errors and exceptions.
Enumeration in java:
class EnumExample
{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args)
{
//printing all enum
for (Season s : Season.values())
{
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal()); Java. lang Package and its Classes:
The most important classes are of lang are
• Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at runtime.
o protected Object clone()
o boolean equals(Object obj)
o protected void finalize()
o Class getClass()
o int hashCode()
o void notify()
o void notifyAll()
o void wait()
o String toString()
• The wrapper classes
o Boolean
o Character
o Integer
o Short
o Byte
o Long
o Float
o Double
• The classes String, StringBuffer, and StringBuilder similarly provide commonly used
operations on character strings.
• Class Throwable encompasses objects that may be thrown by the throw statement.
Subclasses of Throwable represent errors and exceptions.
Enumeration in java:
class EnumExample
{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL } Packages in Java SE:
Java Standard Edition provides 14 packages namely –
• applet − This package provides classes and methods to create and communicate with
the applets.
• awt− This package provides classes and methods to create user interfaces.
• io− This package contains classes and methods to read and write data standard input
and output devices, spublic Addition(double a,double b)
{
this.a=a;
this.b=b;
}
public void suImpor
This document provides an overview of Java arrays, strings, and collections. It discusses single and multi-dimensional arrays, parsing command line arguments, and the advantages and disadvantages of arrays. It also covers the ArrayList class, iterating with iterators and list iterators, and common collection methods. Finally, it summarizes working with dates, the String class, and StringBuilder.
Arrays are ordered collections of values of the same type. They have a fixed length and elements are accessed via an integer index. Common array operations include initializing, selecting, and passing elements. Two-dimensional arrays store arrays of the same length. ArrayLists provide dynamic size and additional methods compared to primitive arrays. Linked lists allow flexible insertion and removal but slower element access than arrays.
This document discusses Java collections and interfaces. It provides examples of using an ArrayList to store and retrieve Integer objects. It demonstrates removing an object from the ArrayList. It also shows storing different object types like JButton in an ArrayList. While arrays can store objects, ArrayLists are more flexible as they can dynamically change size. Interfaces allow different classes to implement common methods while abstracting the actual class, as shown with a List interface example.
The document discusses Java collections framework. It describes that the framework includes interfaces like List, Set, and Map that define different types of collections. It also discusses some implementations of these interfaces like ArrayList, LinkedList, Vector. ArrayList is like an array but resizable, while LinkedList stores elements in memory locations linked by addresses, making insertion/deletion faster than ArrayList. The document also covers methods of collections like add, remove, contains.
The primary distinction between an Array and a String is that an Array is a data structure that includes a collection of elements with the same data type, whereas a String is a collection of characters. Arrays and strings are supported by programming languages, including C.
The document discusses Java collection framework. It defines that an array is a collection of elements stored in continuous memory locations with fixed size. Collections were introduced in Java 1.2 to overcome array limitations. The document describes common collection interfaces like List, Set, Map and their implementation classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap etc. It provides details about various collection classes like their creation, methods and differences.
The document discusses ArrayLists in Java. Key points include:
- ArrayLists allow dynamic resizing as elements are added, with O(1) access time. They support methods for insertion, deletion, and updating elements.
- ArrayLists can be iterated over using a for-each loop or indexed access.
- Common ArrayList methods include add(), get(), contains(), clear(), remove(), and size().
- Iterators can be used to iterate over ArrayLists in a single direction. ListIterators allow bidirectional traversal and modification of elements.
This document discusses the Java collections framework and algorithms for manipulating collections. It provides examples of using various collection classes like ArrayList, LinkedList, and methods from the Collections class like sort. Key points include:
- The collections framework contains interfaces and classes for common data structures like lists, sets, and maps.
- Classes like ArrayList and LinkedList implement the List interface and provide different implementations of lists.
- Static methods in the Collections class like sort, binarySearch, reverse provide common algorithms for manipulating collections.
- Examples demonstrate creating and initializing different collection types, adding/removing elements, sorting, searching collections using these algorithms.
The document provides information about Java's collection framework. It discusses the key interfaces like List, Set, and Map. It describes common implementations of these interfaces like ArrayList, LinkedList, HashSet, TreeSet, HashMap. It explains concepts like iterators, storage of elements in ArrayList and Vector, differences between ArrayList and Vector. It also provides examples of using ArrayList, Vector, HashSet and TreeMap.
This document provides an overview of data structures in Java, including arrays, arraylists, and hashmaps. It discusses how to create, populate, and access arrays and arraylists. It also compares the features of arrays and arraylists, and provides an example of using a hashmap to count word frequencies in a file.
The ArrayList class in Java provides a resizable array implementation of the List interface. It allows for dynamic sizing and permits null elements. Methods like add(), remove(), clear(), get(), and size() allow manipulating the elements. ArrayList is more efficient than LinkedList for some operations due to its array implementation but cannot shrink in size.
This document discusses the ArrayList class in Java. ArrayList allows dynamic arrays that can grow and shrink as needed. It extends AbstractList and implements the List interface. ArrayLists are created with an initial capacity that is automatically enlarged when exceeded. Common methods allow adding, removing, and accessing elements in the ArrayList.
This document discusses the ArrayList class in Java and its useful methods. It explains that ArrayList is a resizable array implementation of the List interface that allows adding and removing elements. Some key points covered include how ArrayList uses an internal array to store elements, maintains insertion order, allows duplicates and null values, and is not thread-safe. The document also lists and describes many common ArrayList methods such as add, remove, get, size, and contains. Example code is provided to demonstrate using various ArrayList methods.
Java collection classes and their usage.how to use java collections in a program and different types of collections. difference between the map list set, volatile keyword.
The document discusses arrays in Java. It defines arrays as ordered lists that store multiple values of the same type. Arrays allow accessing elements using indexes, and declaring arrays involves specifying the type and size. The document covers key array concepts like initialization, bounds checking, passing arrays as parameters, multidimensional arrays, and sorting and searching arrays.
The document provides an overview of arrays in Java, including:
- Arrays can hold multiple values of the same type, unlike primitive variables which can only hold one value.
- One-dimensional arrays use a single index, while multi-dimensional arrays use two or more indices.
- Elements in an array are accessed using their index number, starting from 0.
- The size of an array is set when it is declared and cannot be changed, but reference variables can point to different arrays.
- Common operations on arrays include initializing values, accessing elements, looping through elements, and copying arrays.
( ** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ** )
This Edureka tutorial on “Java ArrayList” (Java blog series: https://goo.gl/osrGrS) will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Through this tutorial, you will learn the following topics:
Collections Framework
Hierarchy of ArrayList
What is ArrayList
Internal Working of ArrayList
Constructors of ArrayList
Constructors Example
ArrayList Methods
Methods Example and Demo
Advantages of ArrayList over Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/CRbgFann
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The document discusses Java collection interfaces and classes. It provides details about the Collection interface, List interface, and ArrayList class. Some key points:
- Collection is the root interface for collections in Java. List is a child interface that allows duplicates and preserves insertion order.
- ArrayList is a common implementation of List that uses an array as its underlying data structure. It allows duplicates, preserves order, and provides fast random access.
- Methods of Collection, List, and ArrayList are described for adding, removing, accessing, and iterating over elements. Examples demonstrate using ArrayList to store basic and user-defined objects.
This document discusses Java collections and interfaces. It provides examples of using an ArrayList to store and retrieve Integer objects. It demonstrates removing an object from the ArrayList. It also shows storing different object types like JButton in an ArrayList. While arrays can store objects, ArrayLists are more flexible as they can dynamically change size. Interfaces allow different classes to implement common methods while abstracting the actual class, as shown with a List interface example.
The document discusses Java collections framework. It describes that the framework includes interfaces like List, Set, and Map that define different types of collections. It also discusses some implementations of these interfaces like ArrayList, LinkedList, Vector. ArrayList is like an array but resizable, while LinkedList stores elements in memory locations linked by addresses, making insertion/deletion faster than ArrayList. The document also covers methods of collections like add, remove, contains.
The primary distinction between an Array and a String is that an Array is a data structure that includes a collection of elements with the same data type, whereas a String is a collection of characters. Arrays and strings are supported by programming languages, including C.
The document discusses Java collection framework. It defines that an array is a collection of elements stored in continuous memory locations with fixed size. Collections were introduced in Java 1.2 to overcome array limitations. The document describes common collection interfaces like List, Set, Map and their implementation classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap etc. It provides details about various collection classes like their creation, methods and differences.
The document discusses ArrayLists in Java. Key points include:
- ArrayLists allow dynamic resizing as elements are added, with O(1) access time. They support methods for insertion, deletion, and updating elements.
- ArrayLists can be iterated over using a for-each loop or indexed access.
- Common ArrayList methods include add(), get(), contains(), clear(), remove(), and size().
- Iterators can be used to iterate over ArrayLists in a single direction. ListIterators allow bidirectional traversal and modification of elements.
This document discusses the Java collections framework and algorithms for manipulating collections. It provides examples of using various collection classes like ArrayList, LinkedList, and methods from the Collections class like sort. Key points include:
- The collections framework contains interfaces and classes for common data structures like lists, sets, and maps.
- Classes like ArrayList and LinkedList implement the List interface and provide different implementations of lists.
- Static methods in the Collections class like sort, binarySearch, reverse provide common algorithms for manipulating collections.
- Examples demonstrate creating and initializing different collection types, adding/removing elements, sorting, searching collections using these algorithms.
The document provides information about Java's collection framework. It discusses the key interfaces like List, Set, and Map. It describes common implementations of these interfaces like ArrayList, LinkedList, HashSet, TreeSet, HashMap. It explains concepts like iterators, storage of elements in ArrayList and Vector, differences between ArrayList and Vector. It also provides examples of using ArrayList, Vector, HashSet and TreeMap.
This document provides an overview of data structures in Java, including arrays, arraylists, and hashmaps. It discusses how to create, populate, and access arrays and arraylists. It also compares the features of arrays and arraylists, and provides an example of using a hashmap to count word frequencies in a file.
The ArrayList class in Java provides a resizable array implementation of the List interface. It allows for dynamic sizing and permits null elements. Methods like add(), remove(), clear(), get(), and size() allow manipulating the elements. ArrayList is more efficient than LinkedList for some operations due to its array implementation but cannot shrink in size.
This document discusses the ArrayList class in Java. ArrayList allows dynamic arrays that can grow and shrink as needed. It extends AbstractList and implements the List interface. ArrayLists are created with an initial capacity that is automatically enlarged when exceeded. Common methods allow adding, removing, and accessing elements in the ArrayList.
This document discusses the ArrayList class in Java and its useful methods. It explains that ArrayList is a resizable array implementation of the List interface that allows adding and removing elements. Some key points covered include how ArrayList uses an internal array to store elements, maintains insertion order, allows duplicates and null values, and is not thread-safe. The document also lists and describes many common ArrayList methods such as add, remove, get, size, and contains. Example code is provided to demonstrate using various ArrayList methods.
Java collection classes and their usage.how to use java collections in a program and different types of collections. difference between the map list set, volatile keyword.
The document discusses arrays in Java. It defines arrays as ordered lists that store multiple values of the same type. Arrays allow accessing elements using indexes, and declaring arrays involves specifying the type and size. The document covers key array concepts like initialization, bounds checking, passing arrays as parameters, multidimensional arrays, and sorting and searching arrays.
The document provides an overview of arrays in Java, including:
- Arrays can hold multiple values of the same type, unlike primitive variables which can only hold one value.
- One-dimensional arrays use a single index, while multi-dimensional arrays use two or more indices.
- Elements in an array are accessed using their index number, starting from 0.
- The size of an array is set when it is declared and cannot be changed, but reference variables can point to different arrays.
- Common operations on arrays include initializing values, accessing elements, looping through elements, and copying arrays.
( ** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ** )
This Edureka tutorial on “Java ArrayList” (Java blog series: https://goo.gl/osrGrS) will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Through this tutorial, you will learn the following topics:
Collections Framework
Hierarchy of ArrayList
What is ArrayList
Internal Working of ArrayList
Constructors of ArrayList
Constructors Example
ArrayList Methods
Methods Example and Demo
Advantages of ArrayList over Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/CRbgFann
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The document discusses Java collection interfaces and classes. It provides details about the Collection interface, List interface, and ArrayList class. Some key points:
- Collection is the root interface for collections in Java. List is a child interface that allows duplicates and preserves insertion order.
- ArrayList is a common implementation of List that uses an array as its underlying data structure. It allows duplicates, preserves order, and provides fast random access.
- Methods of Collection, List, and ArrayList are described for adding, removing, accessing, and iterating over elements. Examples demonstrate using ArrayList to store basic and user-defined objects.
Cholera is a life-threatening diarrheal disease caused by the bacterium Vibrio cholerae that affects 1.3 to 4 million people annually, causing 21,000 to 143,000 deaths. The presentation provides a comprehensive overview of cholera's epidemiology, pathogenesis, clinical presentation, treatment, and prevention. Cholera symptoms include sudden profuse watery diarrhea and vomiting that can quickly lead to dehydration, electrolyte imbalances, shock, and organ failure if left untreated. Prompt rehydration with oral or intravenous fluids is the primary treatment, while prevention relies on safe water, sanitation, vaccination, hygiene and food safety education.
The document discusses strategies for combatting malaria, including preventing transmission through insecticide-treated bed nets and indoor spraying. It also covers treating malaria with antimalarial drugs, the importance of early diagnosis and treatment, and engaging communities to take ownership of prevention and treatment efforts. A comprehensive approach involving preventive measures, effective treatment, and community engagement is needed to reduce the impact of malaria.
The document discusses the ant colony optimization algorithm, which mimics how ant colonies find the shortest path to food sources. It involves simulating ant behavior to iteratively find optimal solutions. The algorithm has various applications in engineering problems and demonstrates potential to enhance efficiency. While it offers advantages like robustness and adaptability, it also faces challenges that require understanding to implement successfully.
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
“Intuition-II, The Chakras”
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Week’s Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. It’s for self employed/Practitioners/Coaches…
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and it’s Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. It’s GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. There’s more support and information available.
(See Presentation for all sections, THX AGAIN.)
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
How to Manage Maintenance Request in Odoo 18Celine George
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Rose Cultivation Practices by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of Rose prepared by:
Kushal Lamichhane (AKL)
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
Pests of Rice: Damage, Identification, Life history, and Management.pptxArshad Shaikh
Rice pests can significantly impact crop yield and quality. Major pests include the brown plant hopper (Nilaparvata lugens), which transmits viruses like rice ragged stunt and grassy stunt; the yellow stem borer (Scirpophaga incertulas), whose larvae bore into stems causing deadhearts and whiteheads; and leaf folders (Cnaphalocrocis medinalis), which feed on leaves reducing photosynthetic area. Other pests include rice weevils (Sitophilus oryzae) and gall midges (Orseolia oryzae). Effective management strategies are crucial to minimize losses.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
In Odoo 18's Employee module, organizing your workforce into departments enhances management and reporting efficiency. Departments are a crucial organizational unit within the Employee module.
Exploring Ocean Floor Features for Middle SchoolMarie
This 16 slide science reader is all about ocean floor features. It was made to use with middle school students.
You can download the PDF at thehomeschooldaily.com
Thanks! Marie
THE QUIZ CLUB OF PSGCAS BRINGS T0 YOU A FUN-FILLED, SEAT EDGE BUSINESS QUIZ
DIVE INTO THE PRELIMS OF BIZCOM 2024
QM: GOWTHAM S
BCom (2022-25)
THE QUIZ CLUB OF PSGCAS
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Subscriptions in Odoo 18 are designed to auto-renew indefinitely, ensuring continuous service for customers. However, businesses often need flexibility to adjust pricing or quantities based on evolving customer needs.
How to Manage Upselling of Subscriptions in Odoo 18Celine 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: