Lecture 7- 11-Feb-2025
Lecture 7- 11-Feb-2025
Creating Objects
The String Class
Packages
Formatting Output
Enumerated Types
Wrapper Classes
3-20
Class Libraries
• A class library is a collection of classes that we can use when developing
programs
• The Java standard class library is part of any Java development
environment.
• Its classes are not part of the Java language itself but provide essential
functionality.
• Various classes we've already used (System , Scanner, String) are
part of the Java standard class library
• Other class libraries can be obtained through third party vendors, or you
can create them yourself
Java Standard Class Library = A collection of pre-built classes and methods provided by Java. 3-21
Packages
• The classes of the Java standard class library are organized into packages
• The Java Standard Library is a collection of packages.
• Some of the packages in the standard class library are:
Package Purpose
• Or you can import the class, and then use just the class name
import java.util.Scanner;
3-24
The import Declaration
• To import all classes in a particular package, you can use the * wildcard character
import java.util.*;
• All classes of the java.lang package are imported automatically into all programs
• It's as if all programs contain the following line:
import java.lang.*;
• That's why we didn't have to import the System or String classes explicitly in earlier programs
• The Scanner class, on the other hand, is part of the java.util package, and therefore must
be imported
• What we do if two classes from different packages have the same name ? Use fully qualified name
3-25
The Random Class
• The Random class is part of the java.util package
• It provides methods that generate pseudo-random numbers
• A Random object performs complicated calculations to produce a
stream of seemingly random values
float nextFloat(); 0.0 ( inclusive) – 1 (exclusive)/random float between 0 and 1
int nextInt(); returns any random integer, including positive and negative val
int nextInt( int num); generates a random integer from 0 to num (excluding num).
3-26
RandomNumbers.java
import java.util.Random;
public class RandomNumbers
{// Generates random numbers in various ranges.
public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
} 3-27
The Random Class using a Seed