0% found this document useful (0 votes)
9 views27 pages

Java Fundamentals

The document covers Java fundamentals, focusing on data structures such as arrays, lists, maps, and sets. It includes examples of array manipulation, the Java Collections Framework, and the use of interfaces, along with practical tasks like counting character frequencies and finding common elements in sets. Key concepts like the List interface, Map interface, and Set interface are explained with code snippets to illustrate their usage.
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)
9 views27 pages

Java Fundamentals

The document covers Java fundamentals, focusing on data structures such as arrays, lists, maps, and sets. It includes examples of array manipulation, the Java Collections Framework, and the use of interfaces, along with practical tasks like counting character frequencies and finding common elements in sets. Key concepts like the List interface, Map interface, and Set interface are explained with code snippets to illustrate their usage.
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

Java Fundamentals

Dr. Mazhar Hameed


Data Structures in Java
• Exploring data structures in Java: Arrays, Lists, Maps, and Sets?

PC: Dall-E
2
Arrays
• Arrays store a fixed number of elements of the same type.

public class Welcome {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
[Link](numbers[2]); // Output: 30
}
}

"What happens if you try to access numbers[5]?"


3
Array Manipulation
• Write a Java program that fills an array with numbers from 1 to 10
and prints the sum of the elements.

Num1 Num2 Num3 Num4 Num5 Num6 Num7 Num8 Num9 Num10

4
Array Manipulation
• Write a Java program that fills an array with numbers from 1 to 10
and prints the sum of the elements.
public class Welcome {
public static void main(String[] args) {
int[] numbers = new int[10];
int sum = 0;
for (int i = 0; i < [Link]; i++) {
numbers[i] = i + 1;
sum += numbers[i];
}
[Link]("Sum: " + sum);
}
}

5
Array Methods and Utilities
• [Link]()
import [Link];

public class ArrayOperations {

public static void main(String[] args) {


int[] numbers = {13, 15, 10, 67, 32};
// Call the static method directly without creating an instance
[Link](numbers);
}

// Make this method static so no object creation is necessary


public static void arrayUtilities(int[] numbers) {
[Link]("Before sorting");
[Link](numbers);

[Link]("After sorting");
[Link](numbers); // Efficient sorting
[Link](numbers);
}
// Static display method to print array values
public static void display(int[] arrayValues) {
for (int num : arrayValues) {
[Link](num + " ");
}
[Link]("\n");
}
} 6
Array Methods and Utilities
• [Link](), [Link]()
[Link]() method is used to fill all elements of an array with a specific
value. It can be used to initialize or reset the elements of an array to the
same value.
import [Link];

public class ArrayOperations {

public static void main(String[] args) {


int[] numbers = new int[5];
[Link](numbers, 7);
[Link]([Link](numbers)); // Output: [7, 7, 7, 7, 7]
}

Without using [Link]() or manually iterating through the array, you cannot
print the values directly. Printing the array itself will only display its reference in
memory. 7
Number Guessing Game with Arrays
Game Flow:
• The program generates an array of random numbers.
• The user is prompted to guess a number.
• The program checks if the guessed number is in the array.
• The program informs the user whether their guess was correct or not, and
keeps track of how many attempts it took to guess correctly.

8
Java Collections Framework
List Interface:
• The List interface extends the Collection interface and provides methods for
positional access, searching, iteration, and more.
• Common implementations of the List interface include:
• ArrayList
• LinkedList
• Vector (legacy, rarely used)

9
What is an Interface?
• An interface in Java is a blueprint that defines a set of methods, but it doesn’t provide
the implementation for those methods. Interfaces tell you what can be done, but the
actual code that defines how it is done is provided by the classes that implement the
interface.
• Example: The List interface defines methods like add(), get(), remove(), but doesn’t
specify how these methods work. That’s left to the implementing classes like ArrayList
or LinkedList.

10
What is an Interface?
// Define the Interface
interface Animal {
void sound(); // Method declaration, no implementation
}

// Class implementing the Interface


class Dog implements Animal {
public void sound() {
[Link]("Woof!"); // Actual implementation
}
}

public class Main {


public static void main(String[] args) {
// Create an instance of Dog and call the sound method
Animal myDog = new Dog();
[Link](); // Output: Woof!
}
}

11
Java Collections Framework
Why Use Interfaces?
• Flexibility: Interfaces allow you to write more flexible code. You can define a
set of behaviors (methods) in an interface, and then multiple classes can
implement these behaviors in different ways. This means your code can work
with different types of objects through a common interface.
• Polymorphism: Using interfaces allows different objects to be treated the
same way, even if their underlying behavior is different. This is especially
useful when working with collections like ArrayList in Java.

12
List -- ArrayList
Important List Methods:
• add(E e): Adds an element to the list.
• get(int index): Returns the element at the specified position.
• set(int index, E element): Replaces the element at the specified position.
• remove(int index): Removes the element at the specified [Link](): Returns the
number of elements in the list.
• isEmpty(): Checks if the list is empty.
• contains(Object o): Checks if the list contains the specified element.

13
List -- ArrayList
import [Link];
import [Link];

public class ListExample {


public static void main(String[] args) {
// Create a List of String type
List<String> names = new ArrayList<>();

// Add elements to the List


[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");

// Access an element by index


[Link]("First name: " + [Link](0)); // Output: Alice

// Modify an element
[Link](1, "Robert");
[Link]("Modified List: " + names);

// Remove an element
[Link]("Charlie");
[Link]("List after removal: " + names);

// Loop through the List


[Link]("Iterating through List:");
for (String name : names) {
[Link](name);
}
}
} 14
List -- ArrayList
Task: Reverse a List of Numbers
• Objective: Write a program to reverse the elements of a list.
• Operations: get(), size(), set()
• Instructions:
• Create a list of integers, like [10, 20, 30, 40, 50].
• Write a method that reverses the list in place (i.e., without using another list).
• Display the reversed list.

15
List -- ArrayList
Task: Find the Maximum Number in a List
• Objective: Given a list of integers, find and return the maximum number in
the list.

public static int findMax(List<Integer> nums)

16
Map Interface
What is a Map?
• A Map is a collection that maps keys to values.
• Each key can map to at most one value.
• Keys are unique, and each key-value pair is known as an entry.
Common Implementations of Map Interface:
• HashMap: Stores entries based on hash codes (unordered).
• TreeMap: Stores entries in sorted order by keys.
• LinkedHashMap: Stores entries in insertion order.

17
Key Characteristics of a Map
Key Features:
• Unique Keys: No duplicate keys are allowed.
• Key-Value Pairs: Each entry in the map consists of a key-value pair (Entry<K, V>).
• No Direct Indexing: Unlike lists, elements are accessed using the key, not an index.
Key Methods:
• put(K key, V value): Adds or updates a key-value pair.
• get(Object key): Retrieves the value for a given key.
• remove(Object key): Removes the key-value pair for the given key.
• containsKey(Object key): Checks if the map contains a specific key.
• containsValue(Object value): Checks if the map contains a specific value.

18
Map -- HashMap
HashMap Characteristics:
• Stores entries in no particular order.
• Implements the Map interface and is backed by a hash table.
• Allows one null key and multiple null values.

import [Link];
import [Link];

public class ListExample {


public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
[Link]("Alice", 30);
[Link]("Bob", 25);
[Link]([Link]("Alice")); // Output: 30
}
}
19
Map -- HashMap
Task: Count the Frequency of Characters in a String
• Write a Java program that takes a string as input and uses a HashMap to
count the frequency of each character in the string.
• Example:
• Input: "hello"
• Output: {h=1, e=1, l=2, o=1}

20
Map -- HashMap
import [Link];
import [Link];
import [Link];

public class CharacterFrequency {


public static void main(String[] args) {
// Step 1: Take input from the user
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();

// Step 2: Create a HashMap to store character frequencies


Map<Character, Integer> frequencyMap = new HashMap<>();

// Step 3: Iterate over the string and count character frequencies


for (char c : [Link]()) {
if ([Link](c)) {
// Increment the count if the character is already in the map
[Link](c, [Link](c) + 1);
} else {
// Add the character to the map with a count of 1
[Link](c, 1);
}
}

// Step 4: Print the character frequency map


[Link]("Character frequencies: " + frequencyMap);
} 21
}
Map -- HashMap
Task: Find the First Non-Repeating Character in a String
• Write a Java program that finds the first non-repeating character in a string
using a HashMap.
• Example:
• Input: "swiss"
• Output: "w"

22
Set Interface
A Set is a collection that contains no duplicate elements. It models the
mathematical set abstraction.
Key Characteristics:
• No duplicates allowed.
• It is unordered by nature, except for certain implementations.
• Operations like add, remove, and search typically run in constant time (O(1)) with a HashSet.
Set Interface:
• Set is an interface that is part of the Java Collections Framework.
• It extends the Collection interface.

23
Set Interface
Key Methods:
• add(E e): Adds the specified element to the set if it is not already present.
• remove(Object o): Removes the specified element from the set.
• contains(Object o): Returns true if the set contains the specified element.
• isEmpty(): Returns true if the set contains no elements.
• size(): Returns the number of elements in the set.
• clear(): Removes all elements from the set.
Common Implementations of Map Interface:
• HashSet: Does not maintain any order of elements.
• TreeSet: Stores entries in sorted order.
• LinkedHashSet: Stores entries in insertion order.

24
Set -- HashSet
Task: Create and Populate a HashSet
• Objective: Create a HashSet and add some unique numbers to it.
import [Link];
import [Link];

public class HashSetTask1 {


public static void main(String[] args) {
// Step 1: Create a HashSet
Set<Integer> numbers = new HashSet<>();

// Step 2: Add elements to the set


[Link](10);
[Link](20);
[Link](30);
[Link](10); // Duplicate element (won't be added)

// Step 3: Print the HashSet


[Link]("HashSet: " + numbers);
}
} 25
Set -- HashSet
Task: Find Common Elements Between Two Sets
• Write a program to find the common elements between two HashSet objects.
import [Link];
import [Link];

public class HashSetCommonElements {


public static void main(String[] args) {
// Step 1: Create two sets
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();

[Link](1);
[Link](2);
[Link](3);
[Link](4);

[Link](3);
[Link](4);
[Link](5);
[Link](6);

// Step 2: Find common elements (intersection)


[Link](set2);

// Step 3: Print the common elements


[Link]("Common elements: " + set1);
} 26
}
Set -- HashSet
Task: Find Common Elements Between Two Sets
• Write a program to find the common elements between two HashSet objects.
import [Link];
import [Link];

public class SetOperations {


public static void main(String[] args)
{
[Link]("\n--------------retainAll-----------");
Set<Integer> set3 = new HashSet<>([Link](1,2,3,4,5,5));
Set<Integer> set4 = new HashSet<>([Link](10,20,3,40,50));
[Link](set3, set4);
}
public static void setUtility(Set<Integer> set3, Set<Integer> set4)
{
// Step 2: Find common elements (intersection)
[Link](set4);
// Step 3: Print the common elements
[Link]("Common elements using retainAll: " + set3);
}

}
27

You might also like