0% found this document useful (0 votes)
3 views7 pages

2.2set Method in Java

The document explains the set() and get() methods in Java, which are used for updating and accessing elements in collections like ArrayList. It provides syntax examples and code snippets demonstrating their usage. Additionally, it introduces Java API packages as a way to organize and reuse code functionality.

Uploaded by

sanskariop79
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

2.2set Method in Java

The document explains the set() and get() methods in Java, which are used for updating and accessing elements in collections like ArrayList. It provides syntax examples and code snippets demonstrating their usage. Additionally, it introduces Java API packages as a way to organize and reuse code functionality.

Uploaded by

sanskariop79
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Set() Method in Java

• The set() method in Java is commonly used with collections


like ArrayList, HashSet, etc. It is used to change or update a
value at a specific position in a list.
Syntax:
[Link](index, newValue);

• index: position (starting from 0)


• newValue: the value to set at that index
import [Link];

public class SetExample {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");

// Before change
[Link]("Before set: " + fruits);

// Changing "Banana" to "Orange"


[Link](1, "Orange");
// After change
[Link]("After set: " + fruits);
}
}
Output:
Before set: [Apple, Banana, Mango]
After set: [Apple, Orange, Mango]
get() Method in Java
• The get() method in Java is used to access (or read) an
element from a collection, especially from List-based
structures like ArrayList or LinkedList.

• Syntax
[Link](index);
import [Link];

public class GetExample {


public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();

// Adding elements
[Link]("Red");
[Link]("Green");
[Link]("Blue");

// Getting element at index 1


String color = [Link](1);

[Link]("Element at index 1: " + color);


}
}
Output:Element at index 1: Green
Java API Packages
• API - Application Programming Interface (Java's pre-built code
library)
• Java API packages are groups of related classes and interfaces
bundled together to provide specific functionality. They help
you organize code and reuse functionality without writing
everything from scratch.

• import [Link]; // Import ArrayList from [Link]


package

• import [Link]; // Import Scanner for user input

You might also like