Java for Beginners
October 4th, 2023
Week 4: Standard Classes and Libraries
Class 7: Introduction to Standard Java Classes
Introduction to Standard Classes
In this class, we will explore some of the standard Java classes and libraries that provide useful functionality for common programming tasks. These classes are part of the Java Standard Library and can save you time when developing Java applications.
String Class
The String
class is one of the most commonly used classes in Java. It represents sequences of characters and provides various methods for working with strings.
String greeting = "Hello, World!";
int length = greeting.length(); // Returns the length of the string (13)
String uppercase = greeting.toUpperCase(); // Converts the string to uppercase
Math Class
The Math
class provides mathematical functions and constants. It is useful for performing mathematical calculations in your Java programs.
double pi = Math.PI; // The value of π (pi)
double sqrt = Math.sqrt(16); // Square root of 16
double random = Math.random(); // Generates a random double between 0.0 (inclusive) and 1.0 (exclusive)
Random Class
The Random
class allows you to generate random numbers. You can use it to introduce randomness into your programs or simulate unpredictable behavior.
import java.util.Random;
Random random = new Random();
int randomNumber = random.nextInt(100); // Generates a random integer between 0 (inclusive) and 100 (exclusive)
Commonly Used Functions from the Random
Class in Java
The Random
class in Java, which is part of the java.util
package, provides methods for generating random numbers. These methods are commonly used for various applications, including simulations, games, and randomness in program behavior. Here are some commonly used functions from the Random
class:
-
nextInt(int bound)
: Generates a random integer between 0 (inclusive) and the specifiedbound
(exclusive). For example:Random random = new Random(); int randomNumber = random.nextInt(10); // Generates a random integer between 0 and 9.
-
nextDouble()
: Generates a random double value between 0.0 (inclusive) and 1.0 (exclusive). For example:Random random = new Random(); double randomValue = random.nextDouble(); // Generates a random double between 0.0 and 1.0.
-
nextBoolean()
: Generates a random boolean value (true or false). For example:Random random = new Random(); boolean randomBoolean = random.nextBoolean(); // Generates a random true or false.
-
nextLong()
: Generates a random long integer. For example:Random random = new Random(); long randomLong = random.nextLong(); // Generates a random long integer.
-
nextFloat()
: Generates a random float value between 0.0 (inclusive) and 1.0 (exclusive). For example:Random random = new Random(); float randomFloat = random.nextFloat(); // Generates a random float between 0.0 and 1.0.
For more references, please refer to this link.
Practice with Standard Classes: Hot and Cold number game
Create a simple hot and cold number game where the program generates a random number, and the player has to guess it.
Requirements The program should provide hints to the player:
- Hot: +/- 3 or less
- Warm: +/- 10 or less
- Cold: +/- 20 or less
- Freezing: other
Hints
- Use the
Random
class to generate the random number. - Use the
Scanner
class to take input from the player. - Use the
Math.abs()
method to calculate the absolute difference between the player’s guess and the random number.
Sample output
Welcome to the Hot and Cold Number Game!
I'm thinking of a number between 1 and 100. Try to guess it.
Enter your guess: 50
Clue: Warm
Enter your guess: 25
Clue: Freezing
Enter your guess: 75
Clue: Cold
Enter your guess: 65
Clue: Warm
Enter your guess: 55
Clue: Warm
Enter your guess: 45
Clue: Cold
Enter your guess: 57
Clue: Hot
Enter your guess: 58
Clue: Hot
Enter your guess: 59
Congratulations! You guessed the number in 9 guesses.
Here’s a sample code you can begin with:
import java.util.Random;
import java.util.Scanner;
public class HotAndColdGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// COMPLETE HERE: Generate a random integer between 1 and 100
int numberOfGuesses = 0;
System.out.println("Welcome to the Hot and Cold Number Game!");
System.out.println("I'm thinking of a number between 1 and 100. Try to guess it.");
while (true) {
System.out.print("Enter your guess: ");
// COMPLETE HERE: Take in an integer input
numberOfGuesses++;
if (userGuess < 1 || userGuess > 100) {
System.out.println("Please enter a number between 1 and 100.");
} else if (userGuess == targetNumber) {
// COMPLETE HERE: Print the end of the game sentence, together with the number of attempts made.
break;
} else {
String clue = getClue(userGuess, targetNumber);
System.out.println("Clue: " + clue);
}
}
scanner.close();
}
// Method to provide clues based on the proximity of the guess
private static String getClue(int guess, int target) {
// COMPLETE HERE: Calculate the absolute difference between the guess and the target
if (difference <= 3) {
return "Hot";
} else if (difference <= 10) {
return "Warm";
}
// COMPLETE HERE: Handle the Cold and Freezing condition
}
}
Pop Quiz
Quiz 1: Which standard Java class is used to represent sequences of characters?
- Math
- Random
- String
- Scanner
Quiz 2: What does the length()
method of the String
class return?
- The character at a specified index.
- The index of the first occurrence of a substring.
- The number of characters in the string.
- The uppercase version of the string.
Quiz 3: Which standard Java class is used for mathematical calculations and provides constants like π (pi)?
- String
- Math
- Random
- Scanner
Quiz 4: To generate random numbers in Java, which class is commonly used?
- String
- Math
- Random
- Scanner
Quiz 5: What is the purpose of the Random
class in Java?
- To perform mathematical calculations.
- To generate random numbers.
- To work with sequences of characters.
- To read user input.
Answers:
- C
- C
- B
- C
- B
Class 8: Working with ArrayLists
Introduction to ArrayLists
In this class, we will explore the ArrayList
class, which is a part of the Java Collections Framework. ArrayList
provides a dynamic array-like data structure that can grow or shrink in size as needed. It is commonly used to store collections of objects.
Creating an ArrayList
To create an ArrayList
, you need to import the ArrayList
class and specify the type of objects it will hold (e.g., String
, Integer
).
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
Adding and Removing Elements
You can add elements to an ArrayList
using the add()
method and remove elements using the remove()
method.
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.remove("Bob"); // Removes "Bob" from the ArrayList
Accessing Elements
You can access elements in an ArrayList
by their index.
String firstPerson = names.get(0); // Retrieves the first element (Alice)
Iterating through an ArrayList
You can use loops to iterate through the elements of an ArrayList
.
for (String name : names) {
System.out.println(name);
}
ArrayList Methods
ArrayList
provides various methods for working with lists, such as size()
, isEmpty()
, contains()
, and more.
int size = names.size(); // Returns the number of elements in the ArrayList
boolean isEmpty = names.isEmpty(); // Checks if the ArrayList is empty
boolean containsAlice = names.contains("Alice"); // Checks if "Alice" is in the ArrayList
Practice with ArrayLists
Let’s practice creating, modifying, and using ArrayLists
in Java. Write code snippets that demonstrate the use of ArrayList
methods.
Pop Quiz
Quiz 1: Which standard Java class provides a dynamic array-like data structure that can grow or shrink in size?
- String
- Math
- Random
- ArrayList
Quiz 2: How do you create an ArrayList
in Java?
- By using the `new ArrayList()` constructor without specifying the element type.
- By specifying the element type when creating the `ArrayList` (e.g., `ArrayList
`).</li> - By using the `ArrayList.add()` method to add elements to an existing array.
- By importing the `java.util.Array` class.
</ol> **Quiz 3**: What method is used to add elements to an `ArrayList`?- `get()`
- `remove()`
- `add()`
- `contains()`
- By using the `get()` method.
- By using the `remove()` method.
- By using the `add()` method.
- By using the `contains()` method.
- The size of the ArrayList (number of elements).
- The first element in the ArrayList.
- The last element in the ArrayList.
- The type of elements in the ArrayList.