Java Package
Java Package
Java Package
For example, you can find two Date classes in Java. However, the rule of
thumb in Java programming is that only one unique class name is allowed in
a Java project.
How did they manage to include two classes with the same name Date
in JDK?
This was possible because these two Date classes belong to two different
packages:
java.util.Date - this is a normal Date class that can be used anywhere.
java.sql.Date - this is a SQL Date used for the SQL query and such.
Based on whether the package is defined by the user or not, packages are
divided into two categories:
Built-in Package
Built-in packages are existing java packages that come along with the JDK.
For example, java.lang, java.util, java.io, etc. For example:
import java.util.ArrayList;
class ArrayListUtilization {
public static void main(String[] args) {
System.out.println(myList);
}
}
Output:
myList = [3, 2, 1]
The ArrayList class belongs to java.util package. To use it, we have to import
the package first using the import statement.
import java.util.ArrayList;
User-defined Package
Java also allows you to create packages as per your need. These packages are
called user-defined packages.
package packageName;
Java uses file system directories to store packages. Let's create a Java file
inside another directory.
For example:
└── com
└── test
└── Test.java
Now, edit Test.java file, and at the beginning of the file, write the package
statement as:
package com.test;
Here, any class that is declared within the test directory belongs to
the com.test package.
Here's the code:
package com.test;
class Test {
System.out.println("Hello World!");
Output:
Hello World!
The package name must be unique (like a domain name). Hence, there's a
convention to create a package as a domain name, but in reverse order. For
example, com.company.name
Here, each level of the package is a directory in your file system. Like this:
└── com
└── company
└── name
4. A pop-up box will appear where you can enter the package name.
Java has an import statement that allows you to import an entire package (as
in earlier examples), or use only certain classes and interfaces defined in the
package.
The general form of import statement is:
For example,
import java.util.Date;
// body
The same task can be done using the fully qualified name as follows:
//body
package com.programiz;
}
Now, you can import Helper class from com.programiz package to your
implementation class. Once you import it, the class can be referred directly
by its name. Here's how:
import com.programiz.Helper;
class UseHelper {
Output:
formattedValue = $99.50
Here,
In Java, the import statement is written directly after the package statement
(if it exists) and before the class definition.
For example,
package package.name;
class MyClass {
// body
class Main {
public static void main(String[] args) {
Output
import java.util.Scanner;
Once we import the package, here is how we can create Scanner objects.
Here, we have created objects of the Scanner class that will read input
from InputStream, File, and String respectively.
The Scanner class provides various methods that allow us to read inputs of
different types.
Method Description
class Main {
public static void main(String[] args) {
input.close();
}
}
Run Code
Output
Enter an integer:
22
Using nextInt(): 22
In the above example, we have used the nextInt() method to read an integer
value.
class Main {
public static void main(String[] args) {
input.close();
}
}
Run Code
Output
class Main {
public static void main(String[] args) {
input.close();
}
}
Run Code
Output
In the above example, we have used the next() method to read a string from
the user.
Here, we have provided the full name. However, the next() method only
reads the first name.
This is because the next() method reads input up to
the whitespace character. Once the whitespace is encountered, it returns
the string (excluding the whitespace).
Example 5: Java Scanner nextLine()
import java.util.Scanner;
class Main {
public static void main(String[] args) {
input.close();
}
}
Run Code
Output
In the first example, we have used the nextLine() method to read a string
from the user.
Unlike next(), the nextLine() method reads the entire line of input including
spaces. The method is terminated when it encounters a next line character, \
n.
To learn more, visit Java Scanner skipping the nextLine().
Java Scanner with BigInteger and BigDecimal
Java scanner can also be used to read the big integer and big decimal
numbers.
class Main {
public static void main(String[] args) {
input.close();
}
}
Run Code
Output
The Scanner class reads an entire line and divides the line into tokens.
Tokens are small elements that have some meaning to the Java compiler. For
example,
Suppose there is an input string:
He is 22
In this case, the scanner object will read the entire line and divides the string
into tokens: "He", "is" and "22". The object then iterates over each token and
reads each token using its different methods.
Before you learn about Java Type Casting, make sure you know about Java
Data Types.
Type Casting
The process of converting the value of one data type ( int, float, double, etc.)
to another data type is known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we
will only focus on the major 2 types.
To learn about other types of type conversion, visit Java Type Conversion
(official Java documentation).
Widening Type Casting
Output
In the above example, we are assigning the int type variable named num to
a double type variable named data.
Here, the Java first converts the int type data into the double type. And then
assign it to the double variable.
In the case of Widening Type Casting, the lower data type (having smaller
size) is converted into the higher data type (having larger size). Hence there
is no loss in data. This is why this type of conversion happens automatically.
Output
Here, the int keyword inside the parenthesis indicates that that
the num variable is converted into the int type.
In the case of Narrowing Type Casting, the higher data types (having larger
size) are converted into lower data types (having smaller size). Hence there
is the loss of data. This is why this type of conversion does not happen
automatically.
Output
Here, we have used the valueOf() method of the Java String class to convert
the int type variable into a string.
Output
Here, we have used the parseInt() method of the Java Integer class to
convert a string type variable into an int variable.
Note: If the string variable cannot be converted into the integer variable
then an exception named NumberFormatException occurs.
int a = 56;
// autoboxing
Integer aObj = a;
class Main {
public static void main(String[] args) {
//autoboxing
list.add(5);
list.add(6);
System.out.println("ArrayList: " + list);
}
}
Run Code
Output
ArrayList: [5, 6]
In the above example, we have created an array list of Integer type. Hence
the array list can only hold objects of Integer type.
Notice the line,
list.add(5);
Here, we are passing primitive type value. However, due to autoboxing, the
primitive value is automatically converted into an Integer object and stored
in the array list.
// autoboxing
Integer aObj = 56;
// unboxing
int a = aObj;
Like autoboxing, unboxing can also be used with Java collections.
class Main {
public static void main(String[] args) {
//autoboxing
list.add(5);
list.add(6);
// unboxing
int a = list.get(0);
System.out.println("Value at index 0: " + a);
}
}
Run Code
Output
ArrayList: [5, 6]
Value at index 0: 5
int a = list.get(0);
Here, the get() method returns the object at index 0. However, due
to unboxing, the object is automatically converted into the primitive
type int and assigned to the variable a.
The lambda expression was introduced first time in Java 8. Its main objective
to increase the expressive power of the language.
If a Java interface contains one and only one abstract method then it is
termed as functional interface. This only one method specifies the intended
purpose of the interface.
import java.lang.FunctionalInterface;
@FunctionalInterface
public interface MyInterface{
// the single abstract method
double getValue();
}
In the above example, the interface MyInterface has only one abstract
method getValue(). Hence, it is a functional interface.
// anonymous class
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("I just implemented the Runnable Functional
Interface.");
}
}).start();
}
}
Run Code
Output:
Java 8 extended the power of a SAMs by going a step further. Since we know
that a functional interface has just one method, there should be no need to
define the name of that method when passing it as an argument. Lambda
expression allows us to do exactly that.
double getPiValue() {
return 3.1415;
}
() -> 3.1415
Here, the method does not have any parameters. Hence, the left side of the
operator includes an empty parameter. The right side is the lambda body
that specifies the action of the lambda expression. In this case, it returns the
value 3.1415.
() -> {
double pi = 3.1415;
return pi;
};
This type of the lambda body is known as a block body. The block body
allows the lambda body to include multiple statements. These statements
are enclosed inside the braces and you have to add a semi-colon after the
braces.
Note: For the block body, you can have a return statement if the body
returns a value. However, the expression body does not require a return
statement.
Let's write a Java program that returns the value of Pi using the lambda
expression.
import java.lang.FunctionalInterface;
// abstract method
double getPiValue();
}
// lambda expression
ref = () -> 3.1415;
Output:
Value of Pi = 3.1415
MyInterface ref;
Finally, we call the method getPiValue() using the reference interface. When
// abstract method
String reverse(String n);
}
}
Run Code
Output:
Till now we have used the functional interface that accepts only one type of
value. For example,
@FunctionalInterface
interface MyInterface {
String reverseString(String n);
}
The above functional interface only accepts String and returns String.
However, we can make the functional interface generic, so that any data type
is accepted. If you are not sure about generics, visit Java Generics.
Example 5: Generic Functional Interface and Lambda Expressions
// GenericInterface.java
@FunctionalInterface
interface GenericInterface<T> {
// generic method
T func(T t);
}
// GenericLambda.java
public class Main {
int result = 1;
for (int i = 1; i <= n; i++)
result = i * result;
return result;
};
Output:
return places;
}
}
Run Code
Output:
myPlaces.stream()
.filter((p) -> p.startsWith("Nepal"))
.map((p) -> p.toUpperCase())
.sorted()
.forEach((p) -> System.out.println(p));
Here, we are using the methods like filter(), map() and forEach() of the
Stream API. These methods can take a lambda expression as input.
We can also define our own expressions based on the syntax we learned
above. This allows us to reduce the lines of code drastically as we saw in the
above example.
Java Generics
Java Generics allows us to create a single class, interface, and method that
can be used with different types of data (objects).
Note: Generics does not work with primitive types (int, float, char, etc).
We can create a class that can be used with any type of data. Such a class is
known as Generics Class.
// variable of T type
private T data;
Output
Here, T used inside the angle bracket <> indicates the type parameter.
Inside the Main class, we have created two objects of GenericsClass
intObj - Here, the type parameter T is replaced by Integer. Now,
the GenericsClass works with integer data.
stringObj - Here, the type parameter T is replaced by String. Now,
the GenericsClass works with string data.
Similar to the generics class, we can also create a method that can be used
with any type of data. Such a class is known as Generics Method.
class DemoClass {
Output
Generics Method:
Data Passed: Java Programming
Generics Method:
Data Passed: 25
Here, the type parameter <T> is inserted after the modifier public and
before the return type void.
We can call the generics method by placing the actual
type <String> and <Integer> inside the bracket before the method name.
demo.<String>genericMethod("Java Programming");
demo.<Integer>genericMethod(25);
Note: We can call the generics method without including the type
parameter. For example,
demo.genericsMethod("Java Programming");
In this case, the compiler can match the type parameter based on the value
passed to the method.
Bounded Types
In general, the type parameter can accept any data types (except primitive
types).
However, if we want to use generics for some specific types (such as accept
data of number types) only, then we can use bounded types.
In the case of bound types, we use the extends keyword. For example,
class Main {
public static void main(String[] args) {
1. Code Reusability
With the help of generics in Java, we can write code that will work with
different types of data. For example,
Here, we have created a generics method. This same method can be used to
perform operations on integer data, string data, and so on.
// using Generics
GenericsClass<Integer> list = new GenericsClass<>();
The collections framework uses the concept of generics in Java. For example,
In the above example, we have used the same ArrayList class to work with
different types of data.
Similar to ArrayList, other collections (LinkedList, Queue, Maps, and so on)
are also generic in Java.
The File class of the java.io package is used to perform various operations on
files and directories.
There is another package named java.nio that can be used to work with files.
However, in this tutorial, we will focus on the java.io package.
A file is a named location that can be used to store related information. For
example,
main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a
directory is known as subdirectory.
Here, we have created a file object named file. The object can be used to
work with files and directories.
Note: In Java, creating a file object does not mean creating a file. Instead, a
file object is an abstract representation of the file or directory pathname
(specified in the parenthesis).
class Main {
public static void main(String[] args) {
try {
In the above example, we have created a file object named file. The file
object is linked with the specified file path.
Here, we have used the file object to create the new file with the specified
path.
If newFile.txt doesn't exist in the current location, the file is created and
this message is shown.
class Main {
public static void main(String[] args) {
Output
To read the data from the input.txt file, we have used the read() method
of FileReader.
class Main {
public static void main(String args[]) {
Output
In the above example, we have created a writer using the FileWriter class.
The writer is linked with the output.txt file.
We can use the delete() method of the File class to delete the specified file
or directory. It returns
true if the file is deleted.
false if the file does not exist.
import java.io.File;
class Main {
public static void main(String[] args) {
Output
In the above example, we have created an object of File named file. The file
now holds the information about the specified file.
Here we have used the delete() method to delete the file specified by the
object.
byte Byte
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short
We can also use the valueOf() method to convert primitive types into
corresponding objects.
Example 1: Primitive Types to Wrapper Objects
class Main {
public static void main(String[] args) {
Output
In the above example, we have used the valueOf() method to convert the
primitive types into objects.
Here, we have used the instanceof operator to check whether the generated
objects are of Integer or Double type or not.
However, the Java compiler can directly convert the primitive types into
corresponding objects. For example,
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b;
Output
The value of a: 23
The value of b: 5.55
This process is known as unboxing. To learn more, visit Java autoboxing and
unboxing
Advantages of Wrapper Classes
// error
ArrayList<int> list = new ArrayList<>();
// runs perfectly
In such cases, wrapper classes help us to use primitive data types as objects.
We can store the null value in wrapper objects. For example,
// generates an error
int a = null;
// runs perfectly
Integer a = null;
Note: Primitive types are more efficient than corresponding objects. Hence,
when efficiency is the requirement, it is always recommended primitive
types.
javac Main.java
java Main
Now suppose we want to pass some arguments while running the program,
we can pass the arguments after the class name. For example,
Here apple, ball, and cat are arguments passed to the program through the
command line. Now, we will get the following output.
The String array stores all the arguments passed through the command line.
The main() method of every Java program only accepts string arguments.
Hence it is not possible to pass numeric arguments through the command
line.
However, we can later convert string arguments into numeric values.
}
}
Run Code
Here 11 and 23 are command-line arguments. Now, we will get the following
output.
Arguments in integer form
11
23
Here, the parseInt() method of the Integer class converts the string
argument into an integer.
Similarly, we can use the parseDouble() and parseFloat() method to convert
the string into double and float respectively.
Note: If the arguments cannot be converted into the specified numeric value
then an exception named NumberFormatException occurs.
Pause
Unmute
Loaded: 8.11%
2.
1. Now Playing
Java Tutorial for Beginners Part 1
2.
Design Registation and Login Forms using Java Netbeans
27:40
3.
Java Course Introduction with Interview question
21:10
4.
Java Course Introduction with Interview question
21:10
5.
Java Course Introduction with Interview question
21:10
6.
Java Course Introduction with Interview question
21:10
7.
Bash Script – Read User Input | User Input in Bash Scripting
2:16
8.
Java Tutorial For Beginners [20 MIN GUIDE]
20:22
9.
Python tutorial 6 | input( ) method in python
12:37
12.
Java Course Introduction with Interview question
21:10
13.
Java Course Introduction with Interview question
21:10
14.
Java Course Introduction with Interview question
21:10
15.
Java Course Introduction with Interview question
21:10
16.
Bash Script – Read User Input | User Input in Bash Scripting
2:16
17.
Java Tutorial For Beginners [20 MIN GUIDE]
20:22
18.
Python tutorial 6 | input( ) method in python
12:37
19.
Play Video
1. Command Line Arguments
4. Console Class
5. Scanner Class
It is one of the simplest ways to read values from user. It will work only when
you are running the program from command line.
1 class CLAExample
2{
3 public static void main(String...s)
4{
5 System.out.println(s[0]+" "+s[1]);
6}
7}
1 import java.io.BufferedReader;
2 import java.io.InputStreamReader;
3
4 class BufferedReaderExample {
5 public static void main(String...s) throws Exception{
6 InputStreamReader isr = new InputStreamReader(System.in);
7 BufferedReader br = new BufferedReader(isr);
8
9 System.out.println("Enter a value:");
10 String str = br.readLine();
11 System.out.println(str);
12 }
13 }
3. DataInputStream Class
1 import java.io.DataInputStream;
2
3 class DataInputStreamExample {
4 public static void main(String...s) throws Exception{
5 DataInputStream dis = new DataInputStream(System.in);
6 System.out.println("Enter a value:");
7 String str = dis.readLine();
8 System.out.println(str);
9 }
10 }
4. Console Class
It will work only when you are running the program from command line.
1 import java.io.Console;
2
3 class ConsoleExample {
4 public static void main(String...s){
5 Console c = System.console();
6 System.out.println("Enter a value:");
7 String str = c.readLine();
8 System.out.println(str);
9 }
10 }
5. Scanner Class
One of the most commonly used way to read from keyboard.
1 import java.util.Scanner;
2
3 class ScannerExample {
4 public static void main(String...s){
5 Scanner sc = new Scanner(System.in);
6 System.out.println("Enter a value:");
7 String str = sc.nextLine();
8 System.out.println(str);
9 }
10 }