Java Unit-1
Java Unit-1
Syllabus Unit-1
Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File
Structure, and Compilation. Fundamental,
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding,
Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library
Packages, Import and Static Import Naming Convention For Packages
Java Introduction
Java is a general-purpose, object-oriented programming language that was designed by James
Gosling at Sun Microsystems in 1991. The compilation of the Java applications results in the
bytecode that can be run on any platform using the Java Virtual Machine. Because of this, Java
is also known as a WORA (Write Once, Run Anywhere) language.
Why Java
Top 10 Reasons to Learn Java
Java is one of the most popular programming languages in the world. It is used by some 9
million developers and it runs on around 7 billion devices worldwide according to Oracle
blogs.
Java is quite easy to learn and can be understood in a short span of time as it has a syntax
similar to English.
There is a large online community of Java users ranging from beginner, intermediate, and even
expert levels that are particularly helpful in case any support is required.
Java has an abundant Application Programming Interface (API) that includes many Java
classes, packages, interfaces, etc. This is useful for constructing applications without
necessarily knowing their inside implementations. Java has mainly three types of API
i.e. Official Java core APIs, Optional official Java APIs, and Unofficial APIs. These APIs
overall are used for almost everything including networking, I/O, databases, media, XML
parsing, speech synthesis, etc.
5. Java has Multiple Open Source Libraries
Open-source libraries have resources that can be copied, studied, changed, shared, etc. There
are multiple open source libraries in Java such as JHipster, Maven, Google Guava, Apache
Commons, etc. that can be used to make Java development easier, cheaper and faster.
There are many Integrated development environments (IDEs) in Java that provide various
facilities for software development to programmers. Powerful Java IDEs such as Eclipse,
NetBeans, IntelliJ IDEA, etc. play a big role in the success of Java. These IDEs provide many
facilities such as debugging, syntax highlighting, code completion, language support,
automated refactoring, etc. that make coding in Java easier and faster. Java has created a base
for the Android operating system and opted around 90% of fortune 500 companies to develop a
lot of back-end applications. Also, it plays a great role in Apache Hadoop data processing,
Amazon Web Services, Windows Azure, etc.
One of the reasons Java is very popular among individual programmers is that it is available
under the Oracle Binary Code License (BCL) free of charge. This means that Java is free for
development and test environments, but for commercial purposes, a little pay is required.
Java is platform-independent as the Java source code is converted to byte code by the compiler
which can then be executed on any platform using the Java Virtual Machine. Java is also
known as a WORA (write once, run anywhere) language because it is platform-independent.
Also, the development of most Java applications occurs in a Windows environment while they
are run on a UNIX platform because of the platform-independent nature of Java.
The documentation support for Java is excellent using Javadoc which is the documentation
generator for Java. It uses the Java source code to generate the API documentation in HTML
format. So, Javadoc provides a great reference while coding in Java so that understanding the
code is quite simple.
Java is very versatile as it is used for programming applications on the web, mobile, desktop,
etc. using different platforms. Also, Java has many features such as dynamic coding, multiple
security features, platform-independent characteristics, network-centric designing, etc. that
make it quite versatile. It doesn’t matter if you are in high school or are in the first year of your
college, if you have the curiosity to learn to code, today is the day to start.
History of Java
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team was to create a
new project which can. Initially C++ was the original choice to develop the project. James
Gosling wanted to enhance C++ to achieve the target but due to high memory usage, that idea
was rejected and team started with a new language initially named as GreenTalk. The file
extension used as .gt. Later this language was termed as Oak and finally to Java.
Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office. Also,
Oak is an image of solidarity and picked as a national tree of numerous nations like the U.S.A.,
France, Germany, Romania, etc. But they had to later rename it as “JAVA” as it was already a
trademark by Oak Technologies.
Finally Java
Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by the team. James
Gosling tabled Java title based on type of espresso coffee bean. Java is an island in Indonesia
where new coffee was discovered termed as Java coffee. As per James Gosling, Java was among
the top choice along with Silk. Finally Java was selected as it was quite unique .
Sun released the first public implementation as Java 1.0 in 1996. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).
JDK in Java
The Java Development Kit (JDK) is a cross-platformed software development
environment that offers a collection of tools and libraries necessary for developing
Java-based software applications and applets. It is a core package used in Java,
along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment). It physically exists. It includes the Java Runtime Environment
(JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), and other tools needed in Java development.
JDK=JRE+Development Tools
One can easily install more than one version of JDK on the same computer. The Java
developers can make use of it on macOS, Windows, Linux, and Solaris.
What is JRE?
Java Run-time Environment (JRE) is the part of the Java Development Kit
(JDK). It is a freely available software distribution which has Java Class
Library, specific tools, and a stand-alone JVM. It is the most common
environment available on devices to run java programs. The source Java
code gets compiled and converted to Java bytecode. If you wish to run this
bytecode on any platform, you require JRE. The JRE loads classes, verify
access to memory, and retrieves the system resources. JRE acts as a layer on
the top of the operating system. It physically exists
JRE stands for “Java Runtime Environment” and may also be written as “Java
RTE.” The Java Runtime Environment provides the minimum requirements for
executing a Java application; it consists of the Java Virtual Machine (JVM), core
classes, and supporting files.
JVM
JVM (Java Virtual Machine) is an abstract machine(It means not real machine,
however, it acts like a machine. Not any machine but as a machine). It is called a
virtual machine because it doesn't physically exist. It is a specification that
provides a runtime environment in which Java bytecode can be executed. It
can also run those programs which are written in other languages and
compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JRE, and JDK
are platform dependent because the configuration of each OS is different
from each other. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.
Difference between JVM, JDK, and JRE
JVMs are not same for all hardware and software, for example for window os
JVM is different and for Linux VJM is different.
o
o
Documentation Section
1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends
with */. For example:
Package Declaration
Import Statements
We use the import keyword to import the class. It is written before the class
declaration and after the package statement. For example:
Interface Section
interface car
{
void start();
void stop();
}
Class Definition
. We use the class keyword to define the class. The class is a blueprint of a
Java program. Every Java program has at least one class that contains the
main() method. For example:
In a Java program, the variables and constants are defined just after the
class definition. The variables and constants store values of the parameters.
It is used during the execution of the program. We can also decide and
define the scope of variables by using the modifiers. It defines the life of the
variables. For example:
The execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class.
o
o As displayed in the above diagram, write the simple program of Java in
notepad and saved it as Simple.java. In order to compile and run the
above program, you need to open the command prompt by start
menu -> All Programs -> Accessories -> command prompt.
When we have done with all the steps properly, it shows the following
output:
o
At compile time, the Java file is compiled by Java Compiler (It does not
interact with OS) and converts the Java code into bytecode.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Example 2:
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
Java provides a reserved keyword class to define a class. The keyword must
be followed by the class name. Inside the class, we declare methods and
variables.
Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
Example-
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
Java Methods
Methods are used to perform certain actions, and they are also known
as functions.
Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.
o Return Type: Return type is a data type that the method returns. It
may have a primitive data type, object, collection, void, etc. If the
method does not return anything, we use void keyword.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When
we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already
stored in the library.
Demo.java
User-defined Method
Let's create a user defined method that checks the number is even or odd.
First, we will define the method.
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().
myMethod();
}
Addition.java
Output:
Static Method
Instance Method
Abstract Method
Static Method
A method that has static keyword is known as static method. In other words,
a method that belongs to a class rather than an instance of a class is known
as a static method. We can also create a static method by using the
keyword static before the method name.
The main advantage of a static method is that we can call it without creating
an object. It can access static data members and also change the value of it.
It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.
Display.java
Output:
Instance Method
InstanceMethodExample.java
Output:
Abstract Method
The method that does not has method body is known as abstract method. In
other words, without an implementation is known as abstract method. It
always declares in the abstract class. It means the class itself must be
abstract if it has abstract method. To create an abstract method, we use the
keyword abstract.
Syntax
Demo.java
Output:
Abstract method...
Access Modifiers in Java
1. Private: The access level of a private modifier is only within the class.
It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Java static keyword
o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.
As we have mentioned above, static variable will get the memory only once,
if any object changes the value of the static variable, it will retain its value.
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Every time an object is created using the new() keyword, at least one
constructor is called.
Operators in Java
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise inclusive |
OR
logical OR ||
Ternary ternary ? :
class Main {
boolean result;
}
}
Output
A primitive data type specifies the size and type of variable values, and it
has no additional methods.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Example
int myNum = 5;
Type casting is when you assign a value of one primitive data type to
another type.
System.out.println(myInt); // Outputs 9
System.out.println(myInt); // Outputs 9
To create a variable, you must specify the type and assign it a value:
Syntax
Example
Create a variable called myNum of type int and assign it the value 15:
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//local variable
}
}//end of class
Final Variables
If you don't want others (or yourself) to overwrite existing values, use
the final keyword (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
Example
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition
is true.
Syntax:
if(condition){
//code to be executed
}
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Java Switch Statement
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement. The switch statement works with byte,
short, int, long, enum types, String and some wrapper types like Byte, Short,
Int, and Long. Since Java 7, you can use strings in the switch statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Loops in Java
for Loop
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
The Java while loop is used to iterate a part of the program repeatedly until
the specified Boolean condition is true. As soon as the Boolean condition
becomes false, the loop automatically stops.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
Java do-while Loop
The Java do-while loop is used to iterate a part of the program repeatedly,
until the specified condition is true. If the number of iteration is not fixed and
you must have to execute the loop at least once, it is recommended to use a
do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while
loop and for loop, the do-while check the condition at the end of loop body.
The Java do-while loop is executed at least once because condition is
checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Java Break Statement
We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.
Syntax:
break;
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
Output:
1
2
3
4
Java Continue Statement
The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for
loop or while loop.
The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.
Syntax:
continue;
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
Test it Now
Output:
1
2
3
4
6
7
8
9
10
Java Comments
The Java comments are the statements in a program that are not executed
by the compiler and interpreter.
The single-line comment is used to comment only one line of the code.
Syntax:
/*
This
is
multi line
comment
*/
1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
Java Arrays
Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
In such case, data is stored in row and column based index (also known as
matrix form).
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Note: String objects are stored in a special memory area known as the "string constant
pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference var
iable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).
StringExample.java
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.
Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.
Object Definitions:
Inheritance
When one object acquires all the properties and behaviors of a parent object,
it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.
Polymorphism
Abstraction
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different
medicines.
Modularity: OOP divides complex systems into smaller components, making the
codebase easier to comprehend, create, and maintain.
Reusability: Inheritance allows code reuse, improving code quality and saving time.
Encapsulation: Protects data integrity and privacy by restricting direct access and
allowing controlled access through methods.
Flexibility and Scalability: OOP enables easy addition and modification of features
without impacting the entire codebase.
Code Organization: OOP promotes a structured approach, enhancing collaboration and
code readability.
Code Maintenance: Changes and bug fixes can be made to specific objects or classes
without affecting other parts of the system, reducing errors and improving debugging.
Code Reusability: OOP encourages the development of reusable code elements, saving
time and improving system reliability.
Better Problem Solving: OOP models real-world systems, allowing developers to create
intuitive solutions that closely mimic real-world circumstances.
Disadvantages of OOP
Increased complexity: OOP's emphasis on modularity and code organization can make
larger projects more challenging to understand and maintain.
Performance overhead: OOP languages often have a performance cost compared to
procedural languages due to the additional abstraction layers introduced by objects and
encapsulation.
Dependency management: Inheritance and code reuse in OOP can create
interdependencies among classes, making it difficult to manage changes and maintain
overall functionality.
Overuse of inheritance: Improper use of inheritance can lead to complex class
hierarchies and tightly coupled classes, making code maintenance and modifications
more difficult in the future.
Using the new keyword is the most popular way to create an object or
instance of the class. When we create an instance of the class by using the
new keyword, it allocates memory (heap) for the newly created object and
also returns the reference of that object to that memory. The new keyword
is also used to create an array. The syntax for creating an object is:
CreateObjectExample1.java
Output:
Welcome to java
By using the new keyword, we can also invoke the constructor (default or
parametrized) of the class.
CreateObjectExample2.java
Output:
Welcome to java
Inheritance in Java
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class
as well as of Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits
A and B classes. If A and B classes have the same method and you call it
from child class object, there will be ambiguity to call the method of A or B
class.
Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
In Java, Method Overloading is not possible by changing the return type of the method
only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Test it Now
Output:
22
33
In this example, we have created two methods that differs in data type. The
first add method receives two integer arguments and second add method
receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Test it Now
Output:
22
24.9
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.
Output:
Encapsulation in Java
Data Encapsulation can be defined as wrapping the code or methods(properties) and the related
fields or variables together as a single unit. In object-oriented programming, we call this single
unit - a class, interface, etc.
Polymorphism in Java
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces
In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Syntax:
interface <interface_name>{
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Test it Now
Output:
Hello
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java Package
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
javac -d . Simple.java
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.
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.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
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.
⇒ choose "System Variables" (for all the users) or "User Variables" (only
the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists)
or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the
required directories and JAR files (separated by semicolons) as the value
(e.g., ".;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar").
Take note that you need to include the current working directory
(denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following
command:
> SET CLASSPATH
NOTE: For Unixes and Mac OS X: Use forward slash '/' as the directory
separator and ':' as the path seperator, e.g.,
".:/usr/local/myproject/classes:/usr/local/tomcat/lib/servle
t-api.jar".
2. CLASSPATH can be set temporarily for that particular CMD shell session
by issuing the following command:
3. > SET CLASSPATH=.;c:\myProject\classes;d:\tomcat\lib\
servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use
the command-line option -classpath (or -cp) of
the javac and java commands, for example,
> java –classpath c:\myProject\classes
com.abc.project1.subproject2.MyClass3
Java Create Jar Files
We can either download the JAR files from the browser or can write our own
JAR files using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given
below. In this section, we only understand how we can create JAR files using
eclipse IDE. In the following steps, we don't cover how we can create an
executable JAR in Java.
1. In the first step, we will open Eclipse IDE and select the Export option
from the File When we select the Export option, the Jar File wizard
opens with the following screen:
2. From the open wizard, we select the Java JAR file and click on
the Next The Next button opens JAR Export for JAR File Specification.
3. Now, from the JAR File Specification page, we select the resources
needed for exporting in the Select the resources to export After
that, we enter the JAR file name and folder. By default, the Export
generated class files and resources checkbox is checked. We also
check the Export Java source files and resources checkbox to
export the source code.
If there are other Java files or resources which we want to include and
which are available in the open project, browse to their location and
ensure the file or resource is checked in the window on the right.
4. On the same page, there are three more checkboxes, i.e., Compress
the content of the JAR file, Add directory entries, and Overwrite
existing files without warning. By default, the Compress content
of the JAR file checkbox is checked.
5. Now, we have two options for proceeding next, i.e., Finish and Next. If
we click on the Next, it will immediately create a JAR file to that
location which we defined in the Select the export destination. If
we click on the Next button, it will open the Jar Packaging
Option wizard for creating a JAR description, setting the advance
option, or changing the default manifest.
For now, we skip
the Next and click on the Finish button.
6. Now, we go to the specified location, which we defined in the Select
the export destination, to ensure that the JAR file is created
successfully or not.
2.0
4.0
6.3
// Java Program to illustrate
// calling of predefined methods
// with static import
import static java.lang.Math.*;
class Test2 {
public static void main(String[] args)
{
System.out.println(sqrt(4));
System.out.println(pow(2, 2));
System.out.println(abs(6.3));
}
}
Output:
2.0
4.0
6.3
Naming Conventions
1. com.javatpoint
1. com.javatpoint.examples