Final, Package, Class Path

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Java final keyword

In Java, the final keyword is used to denote constants. It can be used with variables,
methods, and classes.
Once any entity (variable, method or class) is declared final, it can be assigned only
once. That is,
 the final variable cannot be reinitialized with another value
 the final method cannot be overridden
 the final class cannot be extended

1. Java final Variable


In Java, we cannot change the value of a final variable. For example,
class Main {
public static void main(String[] args) {

// create a final variable


final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}

In the above program, we have created a final variable named age. And we have
tried to change the value of the final variable.
When we run the program, we will get a compilation error with the following
message.
cannot assign a value to final variable AGE
AGE = 45;
^
2. Java final Method
Before you learn about final methods and final classes, make sure you know about
the Java Inheritance.
In Java, the final method cannot be overridden by the child class. For example,
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the
program, we will get a compilation error with the following message.
display() in Main cannot override display() in FinalDemo
public final void display() {
^
overridden method is final

3. Java final Class


In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}

// try to extend the final class


class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final class named FinalClass. Here, we
have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following
message.
cannot inherit from final FinalClass
class Main extends FinalClass {
^
Packages in Java
PACKAGE in Java is a collection of classes, sub-packages, and
interfaces. It helps organize your classes into a folder structure
and make it easy to locate and use them. More importantly, it helps
improve code reusability.
Each package in Java has its unique name and organizes its classes
and interfaces into a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in
the same package, they can appear in different packages. This is
possible by assigning a separate namespace to each Java package.

Types of Packages in Java


Packages in Java can be categorised into 2 categories.
1. Built-in / predefined packages
2. User-defined packages.
Let’s understand them in a little more detail.

Built in packages in Java


Java has already defined some packages and included that in java software, these
packages are known as built-in packages or predefined packages. These packages
contains a large number of classes and interfaces useful for java programmers for
different requirements. Programmers can import these packages in their program
and can use the classes and interfaces of these packages in that program.
Built-in packages comes automatically in your jdk/jre download. These packages
comes in the form of jar files. By unzipping the jar file you can see the packages
available in that jar. For example if you unzip rt.jar file available in lib folder of JRE,
you can see the directory java which contains packages like lang, io, util, sql etc.
There are many built-in packages available in java. In this tutorial we will see some
of the built-in packages and how to use their classes in our program. Some of the
inbuilt packages in java are :
 java.awt : Contains classes for creating user interfaces and for painting
graphics and images. Classes like Button, Color, Event, Font, Graphics,
Image etc are part of this package.
 java.io : Provides classes for system input/output operations. Classes
like BufferedReader, BufferedWriter, File, InputStream, OutputStream,
PrintStream, Serializable etc are part of this package.
 java.lang : Contains classes and interfaces that are fundamental to the
design of Java programming language. Classes like String, StringBuffer,
System, Math, Integer etc are part of this package.
 java.net : Provides classes for implementing networking applications. Classes
like Authenticator, HttpCookie, Socket, URL, URLConnection, URLEncoder,
URLDecoder etc are part of this package.
 java.sql : Provides the classes for accessing and processing data stored in a
database. Classes like Connection, DriverManager, PreparedStatement,
ResultSet, Statement etc are part of this package.
 java.util : Contains the collections framework, some internationalization
support classes, properties, random number generation classes. Classes
like ArrayList, LinkedList, HashMap, Calendar, Date, TimeZone etc are part of
this package.

How to Create a package?


Creating a package is a simple task as follows
 Choose the name of the package
 Include the package command as the first line of code in your Java Source
File.
 The Source file contains the classes, interfaces, etc you want to include in the
package
 Compile to create the Java packages
Step 1) Consider the following package program in Java:
package p1;

class c1(){
public void m1(){
System.out.println("m1 of c1");
}
public static void main(string args[]){
c1 obj = new c1();
obj.m1();
}
}
Here,
1. To put a class into a package, at the first line of code define package p1
2. Create a class c1
3. Defining a method m1 which prints a line.
4. Defining the main method
5. Creating an object of class c1
6. Calling method m1
Step 2) In next step, save this file as demo.java

Step 3) In this step, we compile the file.

The compilation is completed. A class file c1 is created. However, no package is


created? Next step has the solution
Step 4) Now we have to create a package, use the command
javac –d . demo.java
This command forces the compiler to create a package.
The “.” operator represents the current working directory.

Step 5) When you execute the code, it creates a package p1. When you open the
java package p1 inside you will see the c1.class file.

Step 6) Compile the same file using the following code


javac –d .. demo.java
Here “..” indicates the parent directory. In our case file will be saved in parent
directory which is C Drive

File saved in parent directory when above code is executed.


Step 7) Now let’s say you want to create a sub package p2 within our existing java
package p1. Then we will modify our code as
package p1.p2;

class c1{
public void m1() {
System.out.println("m1 of c1");
}
}

Step 8) Compile the file

As seen in below screenshot, it creates a sub-package p2 having class c1 inside the


package.
Step 9) To execute the code mention the fully qualified name of the class i.e. the
package name followed by the sub-package name followed by the class name –
java p1.p2.c1

This is how the package is executed and gives the output as “m1 of c1” from the
code file.

How to Import Package


Importing specific class
Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.
Syntax
import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;

import java.util.Scanner;
public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}
}

In the above code, the class ImportingExample belongs to myPackage package,


and it also importing a class called Scanner from java.util package.

Importing all the classes


Using an importing statement, we can import all the classes of a package. To import
all the classes of the package, we use * symbol. The following syntax is employed to
import all the classes of a package.
Syntax
import packageName.*;

Let's look at an import statement to import a built-in package.


Example
package myPackage;

import java.util.*;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

Random rand = new Random();

int num = rand.nextInt(100);

System.out.println("Randomly generated number " + num);


}
}
PATH and CLASSPATH in Java
The PATH and CLASSPATH are the two most important environment variables of the
Java environment which are used to find the JDK binaries used to compile and run
Java in windows and Linux and class files which are compiled Java bytecodes. From
my personal experience I can say that PATH and CLASSPATH are the two most
problematic things for beginners in Java programming language due to two reasons;
first because in most Java courses nobody tells details of what is a PATH and
CLASSPATH, What do PATH and CLASSPATH do, What is meaning of setting PATH
and CLASSPATH, What happens if we do not set them, Difference between PATH vs
CLASSPATH in Java or simply How Classpath works in Java, etc.

These basic question which answers most of the details about PATH and
CLASSPATH in Java are mostly not answered until Java programmer itself acquire
this knowledge, Things may be changed nowadays but important of PATH and
CLASSPATH is still high.

The most common cause of dreaded error


like java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException is
either incorrect or misconfigured CLASSPATH in Java.

In this article, I'll tell you about the practical difference between PATH and
CLASSPATH environment variables, where are they located, and how exactly they
are used by the Java compiler and JVM. Once you know this basic detail, you would
be able to solve most of the classpath-related problems by yourself.

Difference between PATH and CLASSPATH in Java


Here are some of the common differences between PATH vs CLASSPATH in Java :

1. The main difference between PATH and CLASSPATH is that PATH is an


environment variable that is used to locate JDK binaries like the "java" or "javac"
command used to run java program and compile the java source file. On the other
hand, CLASSPATH, an environment variable is used by System or Application
ClassLoader to locate and load compile Java bytecodes stored in the .class file.

2. In order to set PATH in Java, you need to include JDK_HOME/bin directory in


PATH environment variable while in order to set CLASSPATH in Java you need to
include all those directories where you have put either your .class file or JAR file
which is required by your Java application.

3. Another significant difference between PATH and CLASSPATH is that PATH can
not be overridden by any Java settings but CLASSPATH can be overridden by
providing command-line option -classpath or -cp to both "java" and "javac"
commands or by using Class-Path attribute in Manifest file inside JAR archive.

4. PATH environment variable is used by the operating system to find any binary or
command typed in the shell, this is true for both Windows and Linux environments
while CLASSPATH is only used by Java ClassLoaders to load class files.

These were some notable differences between PATH vs CLASSPATH in Java and
they are worth remembering to debug and troubleshoot Java-related issues. Though,
I highly recommend you to join these best Java Programming courses to build your
fundamentals in Java.

You might also like