Packages & User Input (Part 10)
➤What is a Package ?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
➤Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
User Input in Java
Java provides different ways to get input from the user. However, in this tutorial, you will learn to get input from user using the object of Scanner
class.
In order to use the object of Scanner
, we need to import java.util.Scanner
package.
Syntax:-
// create an object of Scanner
Scanner input = new Scanner(System.in);
// take input from the user
int number = input.nextInt();
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
// closing the scanner object
input.close();
}
}
Enter an integer: 23
You entered 23
System.out.print("Enter text: ");
String myString = input.nextLine();
System.out.println("Text entered = " + myString);
Enter text:
hello
Text entered = hello