Unit 1 Notes OOPS Using Java AKTU
Unit 1 Notes OOPS Using Java AKTU
It is used for:
● Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
● It is one of the most popular programming languages in the world
● It has a large demand in the current job market
● It is easy to learn and simple to use
● It is open-source and free
● It is secure, fast and powerful
● It has huge community support (tens of millions of developers)
● Java is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs
● As Java is close to C++ and C#, it makes it easy for programmers to switch to
Java or vice versa
History of Java
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.
Oak
James Gosling renamed language to Oak. There was an Oak tree in front of his office.
James Gosling used this name as Oak represents solidarity and Oak tree is the national
tree of multiple countries like USA, France, Romania etc. But Oak technologies
already had Oak as a trademark and James team had to brainstrom another title for the
language.
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 and represented the essence of being
dynamic,revolutionary and fun to say.
Sun released the first public implementation as Java 1.0 in 1995. 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).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
The latest release of the Java Standard Edition is Java SE 21. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
Over the period of nearly 30 years, Java has seen many minor and major versions.
Following is a brief explaination of versions of java till date.
19
Major features like JavaBeans, RMI, JDBC, inner classes were
3 JDK 1.1 Feb
added in this release.
1997
8
HotSpot JVM, JNDI, JPDA, JavaSound and support for Synthetic
5 JDK 1.3 May
proxy classes were added.
2000
30
JDK 1.5 Various new features were added to the language like foreach,
7 Sep
or J2SE 5 var-args, generics etc.
2004
11
JAVA SE 1. notation was dropped to SE and upgrades done to JAXB 2.0,
8 Dec
6 JSR 269 support and JDBC 4.0 support added.
2006
17
JAVA SE Feature added - Text Blocks (Multiline strings), Enhanced
15 Sep
13 Thread-local handshakes.
2019
15
JAVA SE Feature added - Sealed Classes, Hidden Classes, Foreign Function
17 Sep
15 and Memory API (Incubator).
2020
16
JAVA SE Feature added as preview - Records, Pattern Matching for switch,
18 Mar
16 Unix Domain Socket Channel (Incubator) etc.
2021
20
JAVA SE Feature added - Record pattern, Vector API (Fourth incubator),
21 Sep
19 Structured Concurrency (Incubator) etc.
2022
JDK, JRE, and JVM plays a very important role in understanding how Java works
and how each component contributes to the development and execution of Java
applications. The main difference between JDK, JRE, and JVM is:
● JDK: Java Development Kit is a software development environment used for
developing Java applications and applets.
● JRE: JRE stands for Java Runtime Environment and it provides an environment
to run only the Java program onto the system.
● JVM: JVM stands for Java Virtual Machine and is responsible for executing the
Java program.
Platform Platform-Independen
Platform-dependent Platform-dependent
Dependency t
Note: From above, media operation computing during the compile time can be
interpreted.
The following actions occur at runtime as listed below:
● Class Loader
● Byte Code Verifier
● Interpreter
o Execute the Byte Code
o Make appropriate calls to the underlying hardware
Working of JVM
It is mainly responsible for three activities.
● Loading
● Linking
● Initialization
It is used to describe that the Java Source Code file must follow a scheme or structure.
The maximum number of classes that may be declared as public in a Java program is
one. If a public class exists, the program’s name and the name of the public class must
match for there to be no compile time errors. There are no limitations when using any
name as the name of the Java source file if there is no public class.
In this article, we will see some instructions that a Java program must follow.
class demo
{// class definition
int x;
}
Java Classes
A class in Java is a set of objects which shares common characteristics and common
properties. It is a user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Ravi is an object.
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents
real-life entities. Objects are the instances of a class that are created to use the
attributes and methods of a class. A typical Java program creates many objects, which
as you know, interact by invoking methods. An object consists of:
● State: It is represented by attributes of an object. It also reflects the properties of
an object.
● Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
● Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Example of an object: Dog
Java Objects
Objects correspond to things found in the real world. For example, a graphics program
may have objects such as “circle”, “square”, and “menu”. An online shopping system
might have objects such as “shopping cart”, “customer”, and “product”.
Constructors in Java
A Constructor in Java is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
Every time an object is created using the new keyword, at least one constructor is
called.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because Java
compiler creates a default constructor if your class does not have any.
Rules for Creating Java Constructor
There are following rules for defining a constructor:
Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor
in Java.
A constructor is called "Default Constructor" when it does not have any parameter.
Syntax:
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
Example
1. //Java Program to create and call a default constructor
2. class Bike{
3. //creating a default constructor
4. Bike(){System.out.println("Bike is created");}
5. }
6. public class Main{
7. //main method
8. public static void main(String args[]){
9. //calling a default constructor
10. Bike b=new Bike();
11. }
12.}
Compile and Run
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Example
1. //Let us see another example of default constructor
2. //which displays the default values
3. class Student{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8. }
9. //Main class to create objects and calling methods
10.public class Main{
11. public static void main(String args[]){
12. //creating objects
13. Student s1=new Student();
14. Student s2=new Student();
15. //displaying values of the object
16. s1.display();
17. s2.display();
18. }
19.}
Compile and Run
Output:
0 null
0 null
Explanation: In the above class, we are not creating any constructor so compiler
provides us a default constructor. Here, 0 and null values are provided by default
constructor.
Example
1. //Java Program to demonstrate the use of the parameterized constructor.
2. class Student{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.}
13.//Main class to create objects and class methods
14.public class Main{
15. public static void main(String args[]){
16. //creating objects and passing values
17. Student s1 = new Student(111,"Joseph");
18. Student s2 = new Student(222,"Sonoo");
19. //calling method to display the values of object
20. s1.display();
21. s2.display();
22. }
23.}
Compile and Run
Output:
111 Joseph
222 Sonoo
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Example
1. //Java program to overload constructors
2. class Student{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. //creating method to display values
18. void display(){System.out.println(id+" "+name+" "+age);}
19.}
20.//creating a Main class to create instance and call methods
21.public class Main{
22. public static void main(String args[]){
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan",25);
25. s1.display();
26. s2.display();
27. }
28.}
Compile and Run
Output:
111 Karan 0
222 Aryan 25
Difference Between Constructor and Method in Java
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an A method is used to expose the behavior of
object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor The method is not provided by the compiler
if we do not have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as t
name. class name.
Access Modifiers in Java
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
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.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
Access Modifier within class within package outside package outside packag
by subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12.}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11.}
The default modifier is more restrictive than protected. That is why, there is a
compile-time error.
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static. Static
methods can access only static fields, methods. To access static methods there is no
need to instantiate the class
The final keyword is a non-access modifier used for classes, attributes and methods,
which makes them non-changeable (impossible to inherit or override). The final
keyword is useful when you want a variable to always store the same value, like PI
(3.14159...). The final keyword is called a "modifier".
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.
Single-line Comments
Any text between // and the end of the line is ignored by Java (will not be executed).
Primitive data are only single values and have no special capabilities. There are 8
primitive data types. They are depicted below in tabular format below as follows:
Example
Type Description Default Size Literals Range of values
8
true or false false true, false true, false
boolean bits
twos-compl
8
ement 0 (none) -128 to 127
bits
byte integer
twos-compl
16
ement 0 (none) -32,768 to 32,767
bits
short integer
-2,147,483,648
twos-compl 32
0 -2,-1,0,1,2 to
ement intger bits
int 2,147,483,647
-9,223,372,036,854,775,80
twos-compl
64 -2L,-1L,0L,1L 8
ement 0
bits ,2L to
integer
long 9,223,372,036,854,775,807
1.23456e300d
IEEE 754
64 ,
floating 0.0 upto 16 decimal digits
bits -123456e-300
point
double d , 1e1d
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a
name of the memory location. It is a combination of "vary + able" which means its
value can be changed.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
Java Operators
Java operators are special symbols that perform operations on variables or values.
They can be classified into several categories based on their functionality. These
operators play a crucial role in performing arithmetic, logical, relational, and bitwise
operations
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive
and non-primitive data types.
● * : Multiplication
● / : Division
● % : Modulo
● + : Addition
● – : Subtraction
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or
negate a value.
● - , Negates the value.
● + , Indicates a positive value (automatically converts byte, char, or short to int).
● ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
● -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
● ! , Inverts a boolean value.
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side value must be declared before using
it or should be a constant.
The general format of the assignment operator is:
variable= value;
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less
than. They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements.
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations,
similar to AND gate and OR gate in digital electronics. They have a short-circuiting
effect, meaning the second condition is not evaluated if the first is false.
Conditional operators are:
● &&, Logical AND: returns true when both conditions are true.
● ||, Logical OR: returns true if at least one condition is true.
● !, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary.
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number
and with any of the integer types. They are used when performing update and query
operations of the Binary indexed trees.
● & (Bitwise AND) – returns bit-by-bit AND of input values.
● | (Bitwise OR) – returns bit-by-bit OR of input values.
● ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
● ~ (Bitwise Complement) – inverts all bits (one’s complement).
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively. They can be used when we have to
multiply or divide a number by two. The general format ,
numbershift_opnumber_of_places_to_shift;
● << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
● >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two),
with the leftmost bit depending on the sign.
● >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit
always 0.
9. instanceof operator
The instance of operator is used for type checking. It can be used to test if an object is
an instance of a class, a subclass, or an interface. The general format ,
objectinstance of class/subclass/interface
Array
An array is a collection of similar type of elements that are stored in a contiguous
memory location. Arrays can contain primitives(int, char, etc) as well as
object(non-primitives) references of a class depending upon the definition of the array.
In the case of primitive data type, the actual values are stored in contiguous memory
locations whereas in the case of objects of a class the actual objects are stored in the
heap segment.
Java Strings
In Java, String is the type of objects that can store the sequence of characters enclosed
by double quotes and every character is stored in 16 bits i.e using UTF 16-bit
encoding. A string acts the same as an array of characters. Java provides a robust and
flexible API for handling strings, allowing for various operations such
as concatenation, comparison, and manipulation.
Example:
String name = “Geeks”;
String num = “1234”
Difference between Array and String :
S.NO
Array String
.
06. The length of the array is fixed. The size of the string is not fixed.
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
class
Fruit
objects
Apple
Banana
Mango
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that we can create new classes that are built
upon existing classes. When we inherit methods from an existing class, we can reuse
methods and fields of the parent class. However, we can add new methods and fields
in your current class also.
What is Inheritance?
Inheritance in Java enables a class to inherit properties and actions from another class,
called a superclass or parent class. A class derived from a superclass is called a
subclass or child group. Through inheritance, a subclass can access members of its
superclass (fields and methods), enforce reuse rules, and encourage hierarchy.
In the terminology of Java, a class that is inherited is called a parent or superclass, and
the new class is called child or subclass.
Example
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. public class Main{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
Compile and Run
Output:
barking...
eating...
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.
Example
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10.public class Main{
11.public static void main(String args[]){
12.BabyDog d=new BabyDog();
13.d.weep();
14.d.bark();
15.d.eat();
16.}}
Compile and Run
Output:
weeping...
barking...
eating...
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
Suppose there are three classes A, B, and C. The C class inherits A and B classes. If A
and B classes have the same method and we call it from child class object, there will
be ambiguity to call the method of A or B class.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.
Advantages of Polymorphism
1. Code Reusability
Polymorphism allows methods in subclasses to override methods in their superclass,
enabling code reuse and maintaining a consistent interface across related classes.
4. Interface Implementation:
Interfaces in Java allow multiple classes to implement the same interface with their
own implementations, facilitating polymorphic behavior and enabling objects of
different classes to be treated interchangeably based on a common interface.
5. Method Overloading:
Types of Polymorphism
The methods in method overloading must have the same name but differ in the
quantity or kind of parameters. Based on the inputs passed in during the method call,
the compiler chooses the suitable overloaded method when a method is called. In the
event of a perfect match, that procedure is used. If not, the compiler uses broadening
to find the closest match depending on the parameter types.
Example
1. class Calculation {
2. int add(int a, int b) {
3. return a + b;
4. }
5. double add(double a, double b) {
6. return a + b;
7. }
8. }
9. public class Main {
10. public static void main(String[] args) {
11. Calculation calc = new Calculation();
12. // Compile-time polymorphism: selecting the appropriate add method based on p
arameter types
13. System.out.println("Sum of integers: " + calc.add(5, 3));
14. System.out.println("Sum of doubles: " + calc.add(2.5, 3.7));
15. }
16.}
Compile and Run
Output:
Sum of integers: 8
Sum of doubles: 6.2
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Method Overloading Method Overriding
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit, for example, a capsule
which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
It provides you the control over the data. Suppose you want to set the value of id
which should be greater than 100 only, you can write the logic inside the setter
method. You can write the logic not to store the negative numbers in the setter
methods.
It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.
Example:
class Person {
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());
}
}
Why Encapsulation?
● Better control of class attributes and methods
● Class attributes can be made read-only (if you only use
the get method), or write-only (if you only use the set method)
● Flexible: the programmer can change one part of the code without
affecting other parts
● Increased security of data
A class that is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Points to Remember
// Regular method
System.out.println("Zzz");
class Main {
myCat.sleep();
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
interface SecondInterface {
System.out.println("Some text..");
class Main {
myObj.myMethod();
myObj.myOtherMethod();
}
Packages in Java
A Java package is a group of similar types of classes, interfaces and sub-packages.
Packages in java can be categorized in two forms, built-in packages and user-defined
packages.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Simple example of java package
The package keyword is used to create a package in java.
If you are not using any IDE, you need to follow the syntax given below:
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
.represents the current folder.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
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:
Output:Welcome to package
● Temporary
o By setting the classpath in the command prompt
o By -classpath switch
● 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.
3. class A{}
4. class B{}
5. public class C{}