Spread the love

How To Set Classpath in Java

Spread the love

What is the Classpath in Java?

Once you download and install java these settings are not immediately required. It is only required when you try to run java programs from other than the bin folder. Without the classpath settings, one can run Java programs from the bin folder.

But after the number of coding codes, the bin folder looks very unorganized. Even if you have created and archived the source and .class files to another folder. To run them you need to bring them into the bin folder.

It would have been great if we could create our own folder structure place required source code and .class files into them and could run.

In java, the source file is written in normal text and saved with the .java  extension.
The compiler upon invoked by the command javac creates a .class file for the corresponding .java file.

The JVM during run time reads the .class file, performs certain checks and executes the same. if the .class file is placed under …../java/bin/ folder . It is not required to mention classpath. But when our project becomes larger, it is required to create some folder structure and place all the necessary .class file at one place, it is extremely required for JVM to know where the .class files reside.

This post will talk about the different settings on how to set classpath in different ways. they are as follows:

  1. Temporary
  2. Permanent

Temporary for a command session.

set classpath=%classpath%;E:myPrograms
//%classpath% is to keep what ever is already present in the classpath;Now provide the required classpath followed by a semi colon(;)

This command is valid for the command prompt it has been set. If you open another command prompt the java command will not work.

  • One more option is also available for setting classpath, valid for a single command.
    java -cp <<full classpath>> <<name of the class>>
    like-java -cp E:myProgram Test123

The scope of the process:

  • Set globally–across the command prompts
  • Set classpath at the command prompt–only for that command prompt session
  • Set classpath on command level-only for that command

While going for the 3rd option there are things to remember:

  • -cp will not consider present working directory by default. We need to include the dot(.) to get present working directory into the classpath
  • Always use full path while working with -cp
  • if the same class file available in different directories then JVM will read from left to write for the -cp command and whenever the first occurrence of the class is available JVM will pick that and execute. But the next sequence will not be picked again.


so in drive C, D, E three test class is available.
Now if we provide

java -cp C:;D:;E: test 

only C: drives test will be executed, D and E will be ignored.
similarly, if we provide

java -cp D:;C:;E: test

only D: drives test will be executed, C and E will be ignored.

READ  HashSet Concept Simplified In Java

How to set classpath in java permanently?

Yes!! if you are thinking this then this post is for you. To solve this problem we need to set classpath for java.
Let’s see how:

Step 1: First install java software, say in E drive or in C drive inside folder j2sdk1.4.2_01 or java

How to Set Classpath in Java?
How to Set Classpath in Java?

Step 2: Now, set the classpath.
Step 3: Go to ‘My Computer’.
Step 4: Right-click on the mouse and go to ‘Properties’.

READ  HashSet Concept Simplified In Java
Classpath in Java
Classpath in Java

Step 5: Go to ‘Advanced’ on the ‘System Properties’. then click on ‘Environment Variables’

Class path settings in Java
Classpath settings in Java

Step 6: In User Variables click ‘New’.

Class path settings in Java
Classpath settings in Java
Class path settings in Java
Classpath settings in Java

Step 7: Write ‘JAVA_HOME’ in Variable name and the path where the software is installed in Variable value. And then click ‘OK’.

Operating SystemHow to set
WindowsSet the environment variable JAVA_HOME to java’s installation directory
LinuxExport JAVA_HOME=/usr/local/java-current.
MacExport JAVA_HOME=/Library/Java/Home.

Step 8: In System variables, click new and give the values as in the figure. And then click ‘OK’.
Step 9: In System variables, there will be a variable named ‘Path’. Double click there. A new window will come. In ‘Variable value’ give a semi-colon after whatever is written. After that write ‘%Path%;C:\j2sdk1.4.2_01\lib;.;’  (if the software is installed in j2sdk1.4.2_01 folder of C drive.for this device it is in E:\java\lib And click ‘OK’ wherever required.

Class path settings in Java
Classpath settings in Java

what are the differences Between Path And Classpath In Java?

Let us understand what is a path in java.
In java, the path is the variable which holds the specific location of the binary executable files of java like- java/javac, etc

How to set path?

Well there are two ways by which we can set path

  • Permanently set path via environment variable-(click here for more)
  • Temporary for a session.

we will check out how to set path temporarily…

Temporary settings:
1. Go to start–>run –>type cmd

2. click on ok. It will open a command prompt for windows

3. Now navigate to the path where you have installed your java(JDK installation folder)
it might be C:\Program Files\java\jdk<<version>>

4. Copy the path and come back to the command prompt.
5. Type the below-written command:

set path=C:Program FilesJavajdk1.7.0_21bin

 

The permanently set path

we need to open the path variable and append the java’s bin folder.

Operating SystemHow to set
WindowsSet the environment variable JAVA_HOME to java’s installation directory
LinuxExport PATH=$PATH:$JAVA_HOME/bin/
MacNA

Hope you enjoyed this post. Please consider sharing this article. Also, let me know if you face any issues regarding the same.

How to verify if Java is installed in our machine and the path and classpath are set up correctly?

  • We need to open the cmd prompt or console.
  • Use the following command to see the output
Operating SystemWhere to seeCommand to see
Windowscmd/consolec:\>java -version
Linuxterminal$ java -version
Macterminalmachine:~techtravelhub$ java -version

In case it produces the same version of java, we have installed, then path and classpath setting is correct.

 

ClassPath tester

This below write-up is about a tiny basic selection of batch information which can be utilized to examine the actions of the javac compiler and java class launcher for various classpath eventualities. The method is called ClasspathTester.

READ  How To Handle Keyboard and Mouse Operation In Selenium Via Action class?

When you are in the center of striving to debug a java develop it is a terrible time to attempt to boil everything down to a straightforward takes a look at the scenario, so generally the intent of my take a look at collection is to do this for you ahead of time. If you can’t locate the precise check you require, it is simple to modify the present exams or make a new exam to match yours requires.

How ClasspathTester Is effective?

As previously mentioned, I did almost everything with batch files, for the reason that I required the tests to be as uncomplicated, portable (inside the Home windows surroundings), and very simple as possible. There are a couple of helper batch files to do issues like make formatted output and make a directory construction, but or else virtually all of the get the job done is accomplished in the RunAllTests.bat file.

What RunAllTests.bat is made up of is tests and sub-tests. If you haven’t downloaded it nonetheless, I suggest you download it and get a glance. Just about every examination is composed of some kind of setup. Set up generally involves the pursuing:

  • Exam surroundings are cleaned up of outdated directories, files, and classpath.
  • The new listing structure is created, new data files are made and placed in the right directories, and the classpath is established if vital.
READ  This-Keyword Simplified in Java

Just after set up, the assessments are run. This is composed of functioning possibly the javac.exe compiler, the java.exe launcher, or equally. Which is all there is to it.

A Simple Case in point

To fully grasp what ClasspathTester, does, open the RunAllTests.bat file in your text editor and search at Test1. Each check is an assortment of sub-tests that are loosely grouped about some kind of a central screening theme, and Examination1 is a single of the most straightforward.

So what transpires in Test1? Initial it phone calls banner.bat to insert a header to the success file. Then it results in the Good day.java and MyLibClass.java files, by copying them from their corresponding java information. Now every little thing is set up to run some subtests.

Exam1A is very simple. In accordance with its description, ” The Hello.java file is located in the current listing and the Hi there.class file will be prepared to the existing directory and operate from the latest directory”. As you can imagine, Exam1A operates flawlessly.

Check1B and Take a look at1C are made to demonstrate unique means that making use of java.exe to start the Hi.class file can are unsuccessful. In Exam1B the classpath is been set to a vacant directory. In Take a look at1C the file Hello.class is erased. Curiously, these two exams fall short in specifically the similar way.

Be aware that all assessment effects are stored in the benefits.log file.

How the Tests are Kept Safe and sound?

By “harmless” I mean secure to your personal computer, harmless to your other facts. Because the checks entail batch data files that are building and destroying files and directories, treatment has to be taken to stay away from accidentally destroying or creating more than other unrelated data files. This is attained in the cleanup.bat file by keeping away from the use of statements like “erase /S *.*” or “rmdir /S *”. In its place, all erasures are kept rather certain.

READ  Abstract Class URLStreamHandler in Java

In point, the cleanup.bat file is made up of the next statements:

set classpath=

rmdir /S /Q aq

rmdir /S /Q EmptyDirectory

erase Howdy*.java

erase Hi there*.class

erase MyLibClass*.java

erase MyLibClass*.course

This guarantees that there will be no tragic accidental reduction of unrelated information.

Why Use .java Suffix Data files?

Aspect of the procedure of ClasspathTester requires completely wiping the foundation listing cleanse of all .java data files, .class information, and subdirectories therefore, all the suffix of all long term java information is mangled to java. For any check, the correct java files are copied to java information. The readily available documents are:

Hi.java

Hello1.java

Howdy2.java

MyLibClass.java

MyLibClass1.java

MyLibClass2.java

Download Details

You can obtain and obtain a zipped duplicate of the ClasspathTester from the internet.

Summary

ClasspathTester is basic, portable, unobtrusive, customizable and solves an annoying progress issue, the need to promptly test distinctive classpath cases with javac.exe, java.exe, or the two.

How To Find Java In A System and Set In The Path?

It is very common to the error java is not recognized as an internal command, operable program or batch file error while invoking any jar or trying to run a jar by providing command java -jar jarname.jar. For me it was very tough to distribute any jar file as most of my team members were unable to open the jar file from the command prompt. To resolve this, I had to come up with something new. I work in a closed environment where we do not have admin rights to set the classpath in the environment variable.
The process we follow:
Open the command prompt and set the java (JDK or JRE). Then try to open the jar file. My objective was to do something that will dynamically find java and set in path.
There is a command in cmd in windows -7, i.e where java ,it immidiately shows up C:windowsSystem32
I happened to navigate to oracle’s page here.
It was said under Java.exe executable section-
Two copies of java.exe executable are installed. One copy is in the bin directory of the JRE . The second copy is placed in either
C:WindowsSystem
or
C:WindowsSystem32
or
C:WinNTSystem32
depending upon the system.
Because of this the second copy of the java.exe, java can be launched from any directory without giving path.
It was more than enough for me to set the java path and initiate a jar file
While googling more for a concrete solution I found the below Stackoverflow links-

  1. Question -4681090
  2. Question- 17602113
  3. Question-3930383
READ  Class ClassLoader in Java

I found these solution was very nice. And I took the third one: Thanks to Glob for the solution.

@ECHO off
SET KIT=JavaSoftJava Runtime Environment
call:ReadRegValue VER "HKLMSoftware%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=Wow6432NodeJavaSoftJava Runtime Environment
call:ReadRegValue VER "HKLMSoftware%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=JavaSoftJava Development Kit
call:ReadRegValue VER "HKLMSoftware%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
SET KIT=Wow6432NodeJavaSoftJava Development Kit
call:ReadRegValue VER "HKLMSoftware%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE
ECHO Failed to find Java
GOTO :EOF
:FoundJRE
call:ReadRegValue JAVAPATH "HKLMSoftware%KIT%%VER%" "JavaHome"
ECHO %JAVAPATH%
SET PATH=%JAVAPATH%bin
// run your jar--I modified a little bit

GOTO :EOF
:ReadRegValue
SET key=%2%
SET name=%3%
SET “%~1=”
SET reg=reg
IF DEFINED ProgramFiles(x86) (
IF EXIST %WINDIR%sysnativereg.exe SET reg=%WINDIR%sysnativereg.exe
)
FOR /F “usebackq tokens=3* skip=1” %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET “%~1=%%A %%B”
GOTO :EOF

 

 




Spread the love
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special keyword called...

Comments

  1. […] JVM loads classes from the local file system in a platform-dependent manner(directory defined by CLASSPATH), however, some classes may be originated from another source like network or by an […]

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special...

Learn Object Repository in UFT in An Efficient and Fast Manner

Object Repository in UFT The post will cover the following...

Learn What Primary Tools For Test Automation

Primary Tools For Test Automation According to the Gartner report...

EDITOR PICKS


Spread the love