[go: up one dir, main page]

0% found this document useful (0 votes)
26 views18 pages

Unit 3-1

Uploaded by

yaaryaari6253243
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views18 pages

Unit 3-1

Uploaded by

yaaryaari6253243
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Java 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.

Simple example of java package


The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");
5. }
6. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
ADVERTISEMENT
Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.

Note: Sequence of the program must be package then import then class.

Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
ADVERTISEMENT
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean
or org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive. For example:

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the
class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the
jar file in the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as C.java otherwise Compilte Time Error
2. class A{}
3. class B{}
4. public class C{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public
class, but keep the package name same. For example:
1. //save as A.java
2. package javatpoint;
3. public class A{}
1. //save as B.java
2. package indu;
3. public class B{}
How to Set CLASSPATH in Java
CLASSPATH: CLASSPATH is an environment variable which is used by Application
ClassLoader to locate and load the .class files. The CLASSPATH defines the path, to find
third-party and user-defined classes that are not extensions or part of Java platform.
Include all the directories which contain .class files and JAR files when setting the
CLASSPATH.

You need to set the CLASSPATH if:

o You need to load a class that is not present in the current directory or any sub-
directories.
o You need to load a class that is not in a location specified by the extensions
mechanism.

The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH
has a directory name or file name at the end. The following points describe what should
be the end of the CLASSPATH.

o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of
the zip or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the
directory that contains the class files.
o If class files placed in a named package, the CLASSPATH ends with the directory
that contains the root package in the full package name, that is the first package
in the full package name.

The default value of CLASSPATH is a dot (.). It means the only current directory
searched. The default value of CLASSPATH overrides when you set the CLASSPATH
variable or using the -classpath command (for short -cp). Put a dot (.) in the new setting
if you want to include the current directory in the search path.

If CLASSPATH finds a class file which is present in the current directory, then it will load
the class and use it, irrespective of the same name class presents in another directory
which is also included in the CLASSPATH.

If you want to set multiple classpaths, then you need to separate each CLASSPATH by
a semicolon (;).

The third-party applications (MySQL and Oracle) that use the JVM can modify the
CLASSPATH environment variable to include the libraries they use. The classes can be
stored in directories or archives files. The classes of the Java platform are stored in
rt.jar.

There are two ways to ways to set CLASSPATH: through Command Prompt or by
setting Environment Variable.

Let's see how to set CLASSPATH of MySQL database:

Step 1: Click on the Windows button and choose Control Panel. Select System.

ADVERTISEMENT

Step 2: Click on Advanced System Settings.

Step 3: A dialog box will open. Click on Environment Variables.


Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button
then put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and
type Variable name as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-Connector Java.jar;.;

Remember: Put ;.; at the end of the CLASSPATH.

Difference between PATH and CLASSPATH

PATH CLASSPATH

PATH is an environment CLASSPATH is also an environment variable.


variable.

It is used by the operating It is used by Application ClassLoader to locate the .class


system to find the executable file.
files (.exe).

You are required to include You are required to include all the directories which
the directory which contains contain .class and JAR files.
.exe files.

PATH environment variable The CLASSPATH environment variable can be overridden


once set, cannot be by using the command line option -cp or -CLASSPATH to
overridden. both javac and java command.
How to Set CLASSPATH in Windows Using Command
Prompt
Type the following command in your Command Prompt and press enter.

1. set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;

In the above command, The set is an internal DOS command that allows the user to
change the variable value. CLASSPATH is a variable name. The variable enclosed in
percentage sign (%) is an existing environment variable. The semicolon is a separator,
and after the (;) there is the PATH of rt.jar file.

How ext folder works in Java


The ext directory works a bit like the CLASSPATH. ext directory is the part of the class
loading mechanism. The classes which are available within JARs in the ext directory are
available to Java applications.

The following table demonstrates the key difference between the CLASSPATH and
Extension Mechanism:

Characteristics CLASSPATH Extension Mechanism

Class loading CLASSPATH loads after bootstrap ext loads after bootstrap
order and extension loading. loading but before CLASSPATH
loading.

Scope It is an application specific. All JREs All JVMs are running in specific
on the host is the CLASSPATH JRE java.ext.dirs.
environment variable.

Package name java.class.path is used to find the java.ext.dirs is used to specify


directories and JAR archives where the extension
containing class files. mechanism loads classes.

Specification It is specified by name including the All JAR files in specified


extension.jar and directory directories are loaded.
containing .class files.

The mechanism will pick up all .jar files from the extension directory even if the file
does not have the .jar extension. The implementation of this is that if one can change
the name of a jar placed in a classpath directory to have an extension other than .jar.
The wildcard (*) does not pick it up. This technique will not work with the extension
directory.

Let's understand the execution process through an example.

A.java

1. public class A {
2. public String toString()
3. {
4. return "hello";
5. } }

B.java

1. public class B {
2. public static void main(final String[] args)
3. {
4. System.out.println(new A());
5. } }

Compile the A.java file. we will archive the compiled A.class file into A.jar. Place this
JAR file into another directory than the compiled B.class file.

To demonstrate the use of the classpath, we place the A.jar file in a directory
C:\JavaPrograms and will access that JAR through wildcard (*) for B to use.

We found that B can still load the A.class while we had deleted it from the current
directory. The Java launcher was explicitly looked for C:\JavaProgram. It is also possible
to have the class loaded without its presence in the same directory and explicit
classpath specification.

It is often referred to as a benefit of Using the extension mechanism because all


applications which are using that JRE can see the same classes without the need to
specify them on the classpath explicitly.

What happens if we change the name of A.jar into A.backup in the same CLASSPATH-
referenced directory. NoClassDefFoundError is encountered when we do the same
because the CLASSPATH-reference does not have the .jar extension.
what is utility classes
utility class is a class that defines a set of methods that perform common, often re-used
functions. Most utility classes define these common methods under static (see Static
variable) scope. Examples of utility classes include java.util.Collections which provides
several utility methods (such as sorting) on objects that implement a Collection
(java.util.collection).

StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is
simple way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O
chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.
Constructors of the StringTokenizer Class
There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, It creates StringTokenizer with specified string and


String delim) delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string,


String delim, boolean delimiter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens. If it is
false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:

Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.


Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class


Let's see an example of the StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.

Simple.java

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

Output:

my
name
is
khan

The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().

Example of nextToken(String delim) method of the


StringTokenizer class
Test.java

1. import java.util.*;
2. public class Test {
3. public static void main(String[] args) {
4. StringTokenizer st = new StringTokenizer("my,name,is,khan");
5. // printing next token
6. System.out.println("Next token is : " + st.nextToken(","));
7. }
8. }

Output:

Next token is : my

Note: The StringTokenizer class is deprecated now. It is recommended to use the split()
method of the String class or the Pattern class that belongs to the java.util.regex package.

Example of hasMoreTokens() method of the StringTokenizer


class
This method returns true if more tokens are available in the tokenizer String otherwise
returns false.

StringTokenizer1.java

1. import java.util.StringTokenizer;
2. public class StringTokenizer1
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTok
enizer class"," ");
9. /* Checks if the String has any more tokens */
10. while (st.hasMoreTokens())
11. {
12. System.out.println(st.nextToken());
13. }
14. }
15. }

Output:

Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and
nextToken() of StringTokenizer class.

Example of hasMoreElements() method of the StringTokenizer


class
This method returns the same value as hasMoreTokens() method of StringTokenizer
class. The only difference is this class can implement the Enumeration interface.

StringTokenizer2.java

1. import java.util.StringTokenizer;
2. public class StringTokenizer2
3. {
4. public static void main(String args[])
5. {
6. StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer","
");
7. while (st.hasMoreElements())
8. {
9. System.out.println(st.nextToken());
10. }
11. }
12. }

Output:

Hello
everyone
I
am
a
Java
developer

The above code demonstrates the use of hasMoreElements() method.

Example of nextElement() method of the StringTokenizer class


nextElement() returns the next token object in the tokenizer String. It can implement
Enumeration interface.

StringTokenizer3.java
1. import java.util.StringTokenizer;
2. public class StringTokenizer3
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
9. /* Checks if the String has any more tokens */
10. while (st.hasMoreTokens())
11. {
12. /* Prints the elements from the String */
13. System.out.println(st.nextElement());
14. }
15. }
16. }

Output:

Hello
Everyone
Have
a
nice
day

The above code demonstrates the use of nextElement() method.

Example of countTokens() method of the StringTokenizer class


This method calculates the number of tokens present in the tokenizer String.

StringTokenizer4.java

1. import java.util.StringTokenizer;
2. public class StringTokenizer3
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
9. /* Prints the number of tokens present in the String */
10. System.out.println("Total number of Tokens: "+st.countTokens());
11. }
12. }

Output:

Total number of Tokens: 6

The above Java code demonstrates the countTokens() method of StringTokenizer()


class.

You might also like