Java Unit 1 AKTU
Java Unit 1 AKTU
Unit-1
Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File
Structure, and Compilation.
Fundamental, Programming Structures in Java: Defining Classes in Java, Constructors,
Methods, Access Specifies, Static Members, Final Members, Comments, Data types,
Variables, Operators, Control Flow, Arrays & String.
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
Introduction To Java
History
Applications
• Java applications are compiled to byte code that can run on any JVM.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
6) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
4) JavaFX
It is used to develop rich internet applications.
It uses a light-weight user interface API.
JAVA VERSIONS
Versions of Java released till date: Version Year
JDK Alpha and Beta 1995
JDK 1.0 1996
JDK 1.1 1997
J2SE 1.2 1998
J2SE 1.3 2000
J2SE 1.4 2002
J2SE 5.0 2004
Java SE 6 2006
Java SE 7 2011
Java SE 8 2014
Java SE 9 2017
Java SE 10 2018
FEATURES OF JAVA
Cont…
1. Object-Oriented: Everything in Java is an object. OO means we organize our software as a
combination of different types of objects that incorporates both data and behavior.
2. Simple: very easy to learn, simple syntax, clean and easy to understand. Removed many
complicated and rarely-used features: pointers, operator overloading, etc.
3. Portable: It facilitates us to carry Java bytecode to any platform. Doesn't require any implementation.
4. Secured
we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
5) Platform independent: Java code can be run on multiple platforms(i.e., Write Once and Run
Anywhere(WORA). Ex. Windows, Linux, Sun Solaris, Mac/OS, etc
6) Robust(means strong)
Strong memory management.
• No pointers that avoids security problems.
• Automatic garbage
•Exception handling & the type checking mechanism
JAVA ARCHITECTURE
First Java Program | Hello World Example
class First{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as First.java
DATA TYPES
OPERATORS
KEYWORDS
VARIABLE
• A variable is a container which holds the value.
• It is name of reserved area allocated in memory.
• It is a combination of "vary + able" i.e. its value can be changed.
• It is assigned with a data type.
• There are 3 types of variables in java: local, instance and static.
Example to understand the types of variables
Types of Variables
class A{
a) Local variables: int data=50; //instance variable
static int m=100; //static variable
• Tied to method
void method(){
• Its scope is within the method. int n=90; //local variable
• It cannot be defined with "static" keyword. }
} //end of class
b) Instance variable:
• variable declared inside the class but outside the body of the method.
• It is not declared as static.
• Its value is instance specific and is not shared among instances, ie. Scope is whole class
c) Static variable:
• Variable declared is as static.
• Cannot be local.
• Its single copy is created and shared among all the instances of the class.
• Its memory allocation happens only once when class is loaded in memory.
Example: (Static variable , Instance variable, local variable)
public class VarEx {
static int stVar = 10;
int instVar = 20;
public void exMethod() {
int locVar = 30;
System.out.println("Static Variable: " + stVar);
System.out.println("Instance Variable: " + instVar);
System.out.println("Local Variable: " + locVar); }
1.Primitive data types: It include boolean, char, byte, short, int, long, float & double.
Types of operators:
Operator Type Category Precedence
>> is used to move left operands value to right by the no. of bits specified by the right operand.
Example:
class TrnyOpr {
public static void main(String[] args) {
1. A scanner is a much more powerful utility than BufferedReader. It can parse the user input and
read an int, short, byte, float, long and double apart from String. On the other
hand, BufferedReader can only read String in Java.
2. BuffredReader has a significantly large buffer (8KB) than Scanner (1KB), which means if
you are reading long String from a file, you should use BufferedReader but for short input and
input other than String, you can use Scanner class.
3. BufferedReader is older than Scanner. It's present in Java from JDK 1.1 onward but
Scanner is only introduced in JDK 1.5 release.
4. BufferedReader is synchronized while Scanner is not. This means, you cannot share
Scanner between multiple threads but you can share the BufferedReader object.
Command-line Arguments
• CLA is the information that is passed to the program when it is executed.
• There is no restriction on the number of java command line arguments.
• Information is passed as Strings. They are captured into the String args of the main method.
• Information directly follows the program’s name on the command line when it is running.
Example:
While running a class Demo, you can specify command line arguments as
java Demo arg1 arg2 arg3 …
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]);
System.out.println("Argument two = "+b[1]);
}
}
# PARSE #
PARSE : It is a method which take a string(input) as an argument and convert in other formats as
like :
Integer
Float
Double
79 87 94 82 67 98 87 81 74 91
scores
An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9
Value in an array is referenced by the array name followed by the index in brackets.
For example, scores[2]: refers to the value 94 (the 3rd value in the array)
Syntax to declare:
1.dataType[][] arrayRefVar; (or) Instantiation:
2.dataType arrayRefVar[][]; (or)
3.dataType []arrayRefVar[]; int[][] arr=new int[3][3]; //3 row,3 column
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println(); } }}
STRING HANDLING
String
• In Java, String is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p',’r',’o',’g',’r’,’a’,’m’};
String s=new String(ch);
is same as: String s="javatprogram";
• String class methods: Used to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The StringBuffer and StringBuilder classes have the same methods with one
• By the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
3 ways:
• public boolean equals(Object another) compares this string to the specified object.
Example: It compares the content of the strings. It will return true if string matches, else returns false.(But match the
case). To ignore the case, use “equalsIgnoreCase())
class Teststringcomparison2{
public static void main(String args[]){
String s1="Kunj";
String s2="KUNJ";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));//false
System.out.println("s1.equalsIgnoreCase(s2)=>>"+s1.equalsIgnoreCase(s2));//true
} }
(B-2) Using == operator
compares two object references to check whether they refer to same instance.
This also, will return true on successful match else returns false.
class Test3{
public static void main(String args[]){
String s1="Kunj";
String s2="Kunj";
String s3=new String("Kunj");
System.out.println("s1==s2=>>"+(s1==s2));//true (because both refer to same instance)
System.out.println("s1==s3=>>"+(s1==s3));//false(because s3 refers to instance created in nonpool)
} }
We can get substring from the given string object by one of the two methods:
Example :
public class TestSubstring{
public static void main(String args[]){
String s="Aviral Maitrey";
System.out.println(s.substring(7)); //Maitrey
System.out.println(s.substring(0,6)); // Aviral
}
}
(D) String toUpperCase() and toLowerCase() method
toUpperCase() : converts given string into uppercase letter
toLowerCase() : converts given string into lowercase letter.
Example: public class TestCase{
public static void main(String args[]){
String s="Abhineet";
System.out.println("s.toUpperCase()=>>"+s.toUpperCase()); //ABHINEET
System.out.println("s.toLowerCase()=>>"+s.toLowerCase()); //abhineet
System.out.println("Original String=>>"+s); //Abhineet(no change in
original)
} }
(E) String trim() method
eliminates white spaces before and after string
Example:
public class TestTrim
{
public static void main(String args[]){
String s=" Abhineet";
System.out.println("Actual string=>>"+s); // Abhineet(with whitespace)
System.out.println("Using trim=>>"+s.trim()); //Abhineet(no whitespace)
}
}
(F) startsWith() and endsWith() method
startsWith(): check whether the given string starts with given prefix or not and returns true when prefix matches the string else it returns
false.
endsWith(): check whether the string ends with the given suffix or not and returns true when suffix matches the string else it returns false.
Example: public class TestStartEnd{
public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println(s.startsWith("Se")); //false
System.out.println(s.endsWith("t")); //true
System.out.println(s.startsWith("Ab")); //true
System.out.println(s.startsWith("ab")); //false
System.out.println(s.endsWith("T")); //false
} }
Example:
A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class.
b) class
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.
It is a logical entity. It can't be physical. Syntax to declare a class:
class <class_name>{
A class in Java can contain:
field;
Fields method;
Methods }
Constructors
Blocks
Nested class and interface
Create an Object
An object is created from a class.
To create an object, specify the class name, followed by the object name, and use keyword new:
class Student.
A simple class example {
Suppose, Student is a class and student's name, roll number, age are its String name;
fields and info() is a method. Then class will look like below. int rollno;
int age;
void info(){
// some code
}
}
Ex: Create Student class
Student class has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's value.
(1) Predefined Method: Methods that is already defined in the Java class libraries.
• 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.
Output:
Ex: Create and call user defined method(findEvenOdd) that checks the number is even or odd:
import java.util.Scanner;
public class EvenOdd {
}
Call by Value and Call by Reference in Java
1) call-by-value :
In this approach copy of an argument value is pass to a method.
Changes made to the argument value inside the method will have no
effect on the arguments.
2) call-by-reference :
Java does not support call by reference directly. However, we can
achieve similar behavior by passing objects as arguments since object
references are passed by value.
original value is not changed, because a copy of the argument is passed to the
method, and modifications to the parameter inside the method do not affect the
original argument.)
• Method overloading is one of the ways through which java supports polymorphism.
• Polymorphism is a concept of OOPg that deal with multiple forms.
• Method overloading can be done by changing number of arguments or by changing the
data type of arguments.
Student(int r, String n)
{ rollno = r; name = n; }
void display ()
{System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[])
{ Student.change();
Student s1 = new Student (111,"Kiran"); Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,“Avi");
s1.display(); s2.display(); s3.display(); } }
Static block
// create a final class We have created a final class named FinalClass. Here,
final class FinalClass { we have tried to inherit the final class by the Main
public void display() { class.
System.out.println("This is a final method."); } }
When we run the program, we will get a compilation
// try to extend the final class error with the following message.
class Main extends FinalClass {
public void display() {
System.out.println("The final method is
overridden."); }
class Book{
Example:
Book()
{
System.out.println("Book is published");
}
public static void main(String args[])
{
Book b=new Book();
}} Output: Book is published
Another Example:
class AddDemo1 {
AddDemo1() {
int a=10;
int b=5;
int c;
c=a+b;
System.out.println("*****Default Constructor*****");
System.out.println("Total of 10 + 5 = "+c); }
class Student{
int id; String name; int age;
Example: Student(int i,String n){
id = i;
name = n; }
Student(int i,String n,int a){ Output:
id = i;
name = n; age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
class ChainingDemo1 {
public static void main(String as[])
{
abc obj = new abc(); }}
** Used when we want to perform multiple tasks by creating a single object of the class.
Difference between constructor and method
Constructor Method
compiler provides a default constructor if not specified. not provided by compiler in any case.
name must be same as the class name. may or may not be same as class name.
INHERITANCE IN JAVA
INHERITANCE IN JAVA
It is a mechanism in which one object acquires all the properties and behaviors of a parent
object.
• It is an important part of OOPs
• Idea behind inheritance: We can create new classes that are built upon existing classes.
• When existing class gets inherited, we can reuse methods and fields of the parent class.
• Moreover, we can add new methods and fields in our current class also.
• Represents the IS-A relationship which is also known as a parent-child relationship.
Usefulness of Inheritance:
•Class: group of objects which have common properties. A blueprint from which objects are created.
•Sub Class/Child Class: class which inherits other class. Also called a derived class or extended class.
•Super Class/Parent Class: class from where a subclass inherits the features. Also called a base class
•Reusability: Able to use the same fields and methods already defined in previous class by a new class
Syntax of Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword used to make a class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
class which is inherited is called a superclass, and the new class is called
subclass.
Example:
• In this figure, Programmer is the subclass and Employee is the superclass.
• The relationship between the two classes is Programmer IS-A Employee.
• It means that Programmer is a type of Employee.
class Employee{
float salary=80000;
}
class Programmer extends Employee{
int bonus=25000; Output:
public static void main(String args[]){
Programmer p=new Programmer(); Programmer salary is:80000.0
System.out.println("Programmer salary is:"+p.salary); Bonus of programmer is:25000
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
In this example:
Programmer object can access its own field as well as of Employee class i.e. code reusability.
Types of Inheritance
1) Single Inheritance: One class inherits from one parent class. (One parent, one
children)
class B extends A{
int edition=2;
void display() {
System.out.println(" Book Edition= "+ edition);
}}
class C extends A{
String publisher="TMH";
void print() {
System.out.println(" Book Publisher="+publisher);}}
class D{
public static void main(String[] args) {
B b=new B(); b.show(); b.display() ;
C c = new C(); c. show(); c.print();
} }
Encapsulation
Definition: hiding the internal details of a class and only allowing access
through public methods.
Encapsulation = Data + Methods bundled together and make variables
private, use getters and setters to access them.
Encapsulation = Private Data + Public Access Methods
Key Points:
Use private for variables (to hide data)
Use public methods to get and set the values.
It's like a capsule that keeps data safe inside
Benefits:
Protects data (no direct access)
Provides control over what is stored
Easy to maintain and modify
Prevents invalid data
Example: simple encapsulation program that includes age with validation.
class Student {
public class AgeValidationExample {
private int age;
public static void main(String[] args) {
// Setter with validation
Student s = new Student();
public void setAge(int newAge) {
s.setAge(15); // valid age
if (newAge > 0 && newAge <= 120) {
age = newAge; System.out.println("Student Age: " +
s.getAge());
} else {
System.out.println("Invalid age! s.setAge(-3); // invalid age
Please enter a value between 1 and 120."); System.out.println("Student Age: " +
} } s.getAge()); // will still show previous valid
// Getter method age
class Animal {
void sound() {
System.out.println("Animal makes a sound"); } }
s1.area();
s2.area();
s3.area();
Benefit: You treat all objects the same (as Shape), but
they behave differently!
Key Difference:
Real-Life Example:
When you drive a car, you just: turn the steering press accelerator.
But do you care how the engine works inside?
That’s abstraction — you use features, not internal code.
Output:
Area of Circle: 78.5
Area of Rectangle: 50
Abstract class with non-abstract method
Abstract classes can also have non abstract methods along with abstract methods.
But, while extending the class, provide definition for the abstract method.
abstract class A {
abstract void ROI();
public void show() {
System.out.println("this is non-abstract method");
}
}
class B extends A {
void ROI() {
System.out.println("Calling parent... Rate of Interest!!!!"); }
public static void main(String[] args) {
B b = new B();
b.ROI();
b.show(); } }
INTERFACE
INTERFACE
is a blueprint of a class. It has static constants and abstract methods.
• It is used to achieve abstraction and multiple inheritance in Java.
• There can be only abstract methods in the java interface not method body.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
• Declare an interface: using the interface keyword.
It provides total abstraction; means all the methods in an interface are declared
with the empty body, and all the fields are public, static and final by default.
- A class that implements an interface must implement all methods declared in
interface.
interface <interface_name>{
Syntax: // declare constant fields
// declare methods that abstract by default.
}
• Java compiler adds public & abstract keywords before the interface method.
• Also adds public, static and final keywords before data members.
• Thus, Interface fields are public, static and final by default, and the methods are public
and abstract.
but
class abc{
public static void main(String args[]){
Bank ob1 = new SBI();
Bank ob2 = new BOB();
System.out.println("Hello");
System.out.println("ROI of SBI=>>"+ob1.printROI());
System.out.println("ROI of BOB=>>"+ob2.printROI()); } }
Multiple inheritance in Java by Interface:
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
Example:
interface emp{
void print(); }
interface dept
void print(); }
class MyInterface implements emp, dept{
public void print(){
System.out.println("Hello");}
emp and dept interface have same methods but its implementation is provided by
class MyInterface1, so there is no ambiguity.
Why Interfaces required?
• Interface allows us to implement common behaviour in two different
classes.
• Interfaces allows us to apply behaviours beyond classes and class
hierarchy.
• Consistent specification among unrelated classes.
• Reduce coupling between software component
• Two or more classes may not achieve same functionality.(No duplicity
of class)
• Create richer classes.
Abstract class Interface
a class which contain one or more abstract Interface is a Java Object containing method
methods, which has to be implemented by declaration but no implementation. The
its sub classes. classes which implement the Interfaces must
provide the method definition for all the
methods.
Abstract class is a class prefix with an Interface is a pure abstract class which starts
abstract keyword followed by class with interface keyword.
definition.
Abstract class can also contain concrete Interface contains all abstract methods and
methods. final variable declarations.
Abstract classes are useful in a situation that Interfaces are useful in a situation that all
Some general methods should be properties should be implemented.
implemented and specialization behavior
should be implemented by child classes.
Access Specifiers
Packages
Modifiers in java
Modifiers are specific keywords using which we can make changes to the characteristics of a
variable, method, or class and limit its scope.
Types of modifiers in java: Access modifiers and non-access modifiers.
1. private
-The access modifiers/specifiers— a very important OOP
2. default
concept for data protection, security, and encapsulation.
3. protected
specifies accessibility (scope) of a data member, method,
4. public
constructor or class.
There are 4 types of java access modifiers
1. static
2. final
- Non-Access modifiers: provide information about the
3. abstract
characteristics of a class, method, or variable to the 4. synchronized
JVM. 7 types of Non-Access modifiers are: 5. volatile
6. transient
7. native
Types of Access Specifiers in Java:
package mainapp;
package test; import test.A;
class A { class B {
int x = 30; // default access public static void main(String[] args) {
A obj = new A(); // Same package
void show() { obj.show();
System.out.println("Default show() in A"); }
} }
}
Advantage of Package
1) used to categorize the classes and interfaces into a separate namespace, or name group
so that they can be easily maintained.
2) provides access protection.
3) removes naming collision.
Built-in Packages
These packages consist of a large number of classes . Commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for GUI (like button , menus
etc).
6) java.net: Contain classes for supporting networking operations.
Steps to Create a Package in Eclipse
1. Create shapes package, Right-click on src → New → PackageName: shapes → Click Finish
2. Create mainapp package, Right-click on src → New → PackageName: mainapp → Click
Finish
Step 1: Create Square.java in shapes package, Right-click on the shapes package, Click
New → ClassName it: Square → Click Finish
package shapes;
public class Square {
double side;
public Square(double s) {
side = s; }
package mainapp;
// Import both classes
import shapes.Circle; Output:
import shapes.Square;
Area of Circle = 95.03317777109125
public class MainApp { Area of Square = 16.0
public static void main(String[] args) {
// Circle
Circle c = new Circle(5.5);
c.area();
// Square
Square s = new Square(4);
s.area();
}}
Classpath settings for packages in Eclipse
Required especially while working with multiple packages
- Eclipse automatically handles classpath settings for packages inside the src folder of a
Java project. We rarely need to manually set anything unless we are importing external
libraries (JARs).
Here’s where you add external JARs (if needed), Click OK to close
Using External Packages or JARs or external Java libraries:
Now your classpath includes that library, and you can use it in
your code.
Making jar files for library packages
To create a JAR file in Eclipse for our library packages like shapes, so they can be reused in
other projects:
We'll create a JAR file that contains: shapes.Circle , shapes.Square. Then, we’ll learn how
to use this JAR in another project.
Both classes should be public, and in the shapes package under the src folder.
Step 2: Export as JAR,
Right-click your project (e.g., PackageDemo),
• Click Export… Choose: Java → JAR file → Click Next.
• In the export window: Select only the shapes package, Leave mainapp or
MainApp.java unchecked (since we're exporting only the library)
• Tick: Export generated class files and resources
• Uncheck: Export Java source files (optional)
• Destination: Choose where to save your JAR file (e.g.,
C:\Users\You\Documents\shapes-lib.jar), Click Finish
• Create a new project: File → New → Java Project (e.g., name it JARUserApp)
• Create a new class with main()
• Add the JAR to Classpath: Right-click the project → Build Path → Configure Build
Path
• Click Libraries tab → Add External JARs-> Select shapes-lib.jar →
• Click Apply and Close
import shapes.Circle;
import shapes.Square; Output:
Code to Use the JAR: public class TestJAR { Area of Circle = 63.61725123519331
public static void main(String[] args) { Area of Square = 25.0
Circle c = new Circle(4.5);
c.area();
Square s = new Square(5);
s.area(); }}
What is import?
import is used to access classes or interfaces from other packages.
Syntax: import packageName.ClassName;
import java.util.Scanner;
Or:
2. Use your reversed domain name (for large projects) Especially in real-world
applications or libraries:
com.google.maps, org.apache.logging
4. Avoid using Java keywords or special characters. Package names can't contain symbols
like -, #, or start with numbers.
5. Be descriptive and specific. Name should reflect the purpose of the package.
math.operations, user.profile.details
• Package statement must be first statement in the program even before the import
statement.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the package must be declared
public.
• All classes within the package must have the package statement as its first line.
• All classes of the package must be compiled before use.
To access package from another package:
There are three ways to access the package from outside the package :
a) import package.*;
b) import package.classname;
c) fully qualified name.
1) Using packagename.* : all classes and interfaces of this package are accessible but not subpackages.
The import k/w is used to make classes & interface of another package accessible to current package.
//save by A.java
package pack; Example:
public class A {
public void msg() { Output: Hello! I
System.out.println("Hello! I am from class A, package pack"); } }
am from class A,
//save by B.java package pack
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
} }
2) Using packagename.classname: only declared class of this package will be accessible.
Example:
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello ! I am from class A, package pack"); } }
Output: Hello! I
//save by B.java am from class A,
package mypack; package pack
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
3) Using fully qualified name
Only declared class of this package will be accessible. Now, import is not required.
Needed to use fully qualified name every time the class or interface are accessed.
- generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example: //save by A.java
package pack;
public class A {
public void msg() {
System.out.println(("Hello ! I am from class A, package pack");
} }
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
} }
Subpackage in java
- On import of a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages.
Hence, needed to import the subpackage as well.
For example :
If I create a package inside letmecalculate package then that will be called sub package.
Lets say I have created another package inside letmecalculate and the sub package name is multiply.
So if I create a class in this subpackage it should have this package declaration in the beginning:
package letmecalculate.multiply;
// Save as Multiplication.java Now if I need to use this Multiplication class I have to
either import the package like this:
public class Multiplication
{ import letmecalculate.multiply;
int product(int a, int b){
or I can use fully qualified name like this:
return a*b;
}
} letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();