ACTIVITY NO.
3 - JAVA BASIC STRUCTURE AND SYNTAX
Lecture Discussion: Java Packages and Scanner
1. What is a Package in Java?
A package in Java is like a folder that groups related classes and interfaces together.
It helps in:
o Organizing code properly.
o Avoiding name conflicts (two classes can have the same name if they are in different packages).
o Reusing code easily.
Analogy:
Think of your computer files. You store documents in a folder to keep them organized. Similarly, in
Java, we store classes inside packages.
2. Types of Packages
1. Built-in Packages – Already provided by Java.
Examples:
o [Link] (contains Scanner, ArrayList, Date, etc.)
o [Link] (input/output classes)
o [Link] (database connectivity)
2. User-defined Packages – Created by the programmer to organize their own classes.
3. Importing Packages
To use classes from a package, we use the import keyword.
Example:
import [Link];
This means we are using the Scanner class from the [Link] package.
4. The Scanner Class
Scanner is a Java class used to take input from the user.
It can read:
o Strings
o Integers
o Floating-point numbers
o Other data types
Syntax:
Scanner sc = new Scanner([Link]);
Here:
Scanner → the class we are using
sc → the object/variable name
new Scanner([Link]) → allows us to take input from the keyboard
5. Example Program Using Scanner
import [Link]; // Importing Scanner class from [Link]
package
public class UserInfo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]); // Create Scanner object
// Asking for personal info
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Enter your grade level: ");
int grade = [Link]();
// Output
ACTIVITY NO. 3 - JAVA BASIC STRUCTURE AND SYNTAX
[Link]("\n--- User Information ---");
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Grade: " + grade);
}
}
6. Sample Output
Enter your name: Carl
Enter your age: 17
Enter your grade level: 11
--- User Information ---
Name: Carl
Age: 17
Grade: 11
Key Takeaways
Packages organize Java classes.
import allows us to use classes from packages.
Scanner is used for user input, and it belongs to the [Link] package.