KEMBAR78
Unit 1 Notes OOPS Using Java AKTU | PDF | Java Virtual Machine | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
33 views50 pages

Unit 1 Notes OOPS Using Java AKTU

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is versatile, supporting mobile, desktop, web applications, and more, and is known for its platform independence, ease of learning, and strong community support. The document also covers Java's history, version evolution, and the differences between JDK, JRE, and JVM, as well as the structure of Java programs, classes, and objects.

Uploaded by

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

Unit 1 Notes OOPS Using Java AKTU

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is versatile, supporting mobile, desktop, web applications, and more, and is known for its platform independence, ease of learning, and strong community support. The document also covers Java's history, version evolution, and the differences between JDK, JRE, and JVM, as well as the structure of Java programs, classes, and objects.

Uploaded by

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

Java?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

●​ Mobile applications (specially Android apps)


●​ Desktop applications
●​ Web applications
●​ Web servers and application servers
●​ Games
●​ Database connection
●​ And much, much more!

Why Use Java?

●​ 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

Java programming language was originally developed by Sun Microsystems which


was initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]). History of even naming of the Java is
very interesting. It went under many names.

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.

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.

Java Versions History

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.

Sr.No. Version Date Description

1 JDK Beta 1995 Initial Draft version


23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996

19
Major features like JavaBeans, RMI, JDBC, inner classes were
3 JDK 1.1 Feb
added in this release.
1997

8 Dec Swing, JIT Compiler, Java Modules, Collections were introduced


4 JDK 1.2
1998 to JAVA and this release was a great success.

8
HotSpot JVM, JNDI, JPDA, JavaSound and support for Synthetic
5 JDK 1.3 May
proxy classes were added.
2000

Image I/O API to create/read JPEG/PNG image were added.


6 Feb
6 JDK 1.4 Integrated XML parser and XSLT processor (JAXP) and
2002
Preferences API were other important updates.

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

Support for dynamic languages added to JVM. Another


JAVA SE 7 Jul
9 enhancements included string in switch case, compressed 64 bit
7 2011
pointers etc.

18 Support for functional programming added. Lambda


JAVA SE
10 Mar expressions, streams, default methods, new date-time
8
2014 APIs introduced.
21
JAVA SE
11 Sep Module system introduced which can be applied to JVM platform.
9
2017

20 Unicode language-tag extensions added. Root certificates,


JAVA SE
12 Mar threadlocal handshakes, support for heap allocation on alternate
10
2018 memory devices etc were introduced.

Dynamic class-file constants, Epsilon a no-op garbage collector,


JAVA SE 5 Sep
13 local-variable support in lambda parameters, Low-overhead heap
11 2018
profiling support added.

19 Experimental Garbage Collector,Shenandoah: A Low-Pause-Time


JAVA SE
14 Mar Garbage Collector, Microbenchmark Suite, JVM Constants API
12
2019 added.

17
JAVA SE Feature added - Text Blocks (Multiline strings), Enhanced
15 Sep
13 Thread-local handshakes.
2019

17 Feature added - Records, a new class type for modelling, Pattern


JAVA SE
16 Mar Matching for instanceof, Intuitive NullPointerException
14
2020 handling.

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

14 Feature added as finalized - Sealed Classes, Pattern Matching for


JAVA SE
19 Sep instanceof, Strong encapsulation of JDK internals by default. New
17
2021 macOS rendering pipeline etc.
22 Feature added - UTF-8 by Default, Code Snippets in Java API
JAVA SE
20 Mar Documentation, Vector API (Third incubator), Foreign Function,
18
2022 Memory API (Second Incubator) etc.

20
JAVA SE Feature added - Record pattern, Vector API (Fourth incubator),
21 Sep
19 Structured Concurrency (Incubator) etc.
2022

21 Feature added - Scoped Values (Incubator), Record Patterns


JAVA SE
22 Mar (Second Preview), Pattern Matching for switch (Fourth
20
2023 Preview),Foreign Function & Memory API (Second Preview) etc.

19 Feature added - String Templates (Preview), Sequenced


JAVA SE
22 Sep Collections, Generational ZGC, Record Patterns, Pattern Matching
21
2023 for switch etc.

Feature added - Region Pinning for G1 garbage collector, foreign


19
Java SE functions and memory APIs , multi-file source code programs
23 Mar
22 support, string templates, vector apis (seventh incubator), unnamed
2024
variables, patterns, stream gatherers (first preview) etc.

17 Feature added - Primitive types in patterns, class file APIs, vector


Java SE
24 Sep APIs (Eighth incubator), stream gatherers (second preview), ZDC,
23
2024 generation mode by default etc.

Differences between JDK, JRE and JVM

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.

JDK vs JRE vs JVM

Aspect JDK JRE JVM

Used to develop Used to run Java Responsible for


Purpose Java applications applications running Java code

Platform Platform-Independen
Platform-dependent Platform-dependent
Dependency t

It includes It runs the java byte


It includes libraries
development tools code and make java
to run Java
like (compiler) + application to work
application + JVM
Includes JRE on any platform.

Running a Java Convert bytecode


Writing and
application on a into native machine
compiling Java code
Use Case system code
Note: The JVM is platform-independent, but JVM implements differently in each
platform because it interacts with the native operating system and the hardware. So it
is in practice, platform dependent.
We have discussed the core differences, now let’s take a closer look at each
component. let us discuss them in brief first and interrelate them with the image
below proposed.
JDK(Java Development Kit)
The JDK is a software development kit that provides the environment to develop and
execute the java application. It includes two things:
●​ Development Tools (to provide an environment to develop your java programs)
●​ JRE (to execute your java program)
Working of JDK
The JDK enables the development and execution of Java programs. Consider the
following process:
●​ Java Source File (e.g., Example.java): You write the Java program in a source
file.
●​ Compilation: The source file is compiled by the Java Compiler (part of JDK) into
bytecode, which is stored in a .class file (e.g., Example.class).
●​ Execution: The bytecode is executed by the JVM (Java Virtual Machine), which
interprets the bytecode and runs the Java program.

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

JRE((Java Runtime Environment)


The JRE is an installation package that provides an environment to only run(not
develop) the Java program (or application) onto your machine. JRE is only used by
those who only want to run Java programs that are end-users of your system.
Working of JRE
When you run a Java program, the following steps occur:
●​ Class Loader: The JRE’s class loader loads the .class file containing the bytecode
into memory.
●​ Bytecode Verifier: The bytecode verifier checks the bytecode for security and
correctness.
●​ Interpreter: The JVM interprets the bytecode and executes the program.
●​ Execution: The program executes, making calls to the underlying hardware and
system resources as needed.

JVM (Java Virtual Machine)


The JVM is a very important part of both JDK and JRE because it is contained or
inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and
JVM is responsible for executing the java program line by line, hence it is also known
as an interpreter.

Working of JVM
It is mainly responsible for three activities.
●​ Loading
●​ Linking
●​ Initialization

Java Source File Structure

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.

Structure of Java Program


●​ package statement: In Java, a package is a way to gather together classes, sub
packages, and interfaces.
●​ import statements: A package, class, or interface is imported using an import
statement.
●​ class definition: A class is a passive entity that serves as a user-defined
blueprint or template from which objects are formed.
Example
packageexample;//package
import java.util.*;//import statement

class demo
{// class definition
int x;
}

Classes and Objects in Java


In Java, classes and objects are basic concepts of Object Oriented Programming
(OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior. For example, the
animal type Dog is a class while a particular dog named Tommy is an object of
the Dog class. In this article, we will discuss Java classes and objects and how to
implement them in our program.

Difference Between Java Classes and Objects


The main differences between class and object in Java are as follows:
Class Object

Class is the blueprint of an object. It is


An object is an instance of the class.
used to create objects.

No memory is allocated when a class is Memory is allocated as soon as an object


declared. is created.
Class Object

An object is a real-world entity such as a


A class is a group of similar objects.
book, car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.

Objects of the class car can be BMW,


An example of class can be a car.
Mercedes, Ferrari, etc.

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.

Properties of Java Classes


●​ Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
●​ Class does not occupy memory.
●​ Class is a group of variables of different data types and a group of methods.
●​ A Class in Java can contain:
o​ Data member
o​ Method
o​ Constructor
o​ Nested Class
o​ Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Components of Java Classes

In general, class declarations can include these components, in order:


●​ Modifiers: A class can be public or has default access (Refer this for details).
●​ Class keyword: Class keyword is used to create a class.
●​ Class name: The name should begin with an initial letter (capitalized by
convention).
●​ Superclass (if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
●​ Interfaces(if any): A comma-separated list of interfaces implemented by the class,
if any, preceded by the keyword implements. A class can implement more than one
interface.
●​ Body: The class body is surrounded by braces, { }.

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.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

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:

1.​ Constructor name must be the same as its class name.


2.​ A Constructor must have no explicit return type.
3.​ A Java constructor cannot be abstract, static, final, and synchronized.

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.

Types of Java Constructors

There are two types of constructors in Java:

1.​ Default Constructor (No-arg constructor)


2.​ Parameterized Constructor
1) Java Default Constructor

A constructor is called "Default Constructor" when it does not have any parameter.

Syntax:

1.​ <class_name>(){}

Example of Default Constructor

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.

Q) What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.

Example of Default Constructor: Displays the Default Values

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.

2) Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.

Example of Parameterized Constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the 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.

Constructor overloading in Java is a technique of having more than one constructor


with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types.
Example of Constructor Overloading

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.

Java Constructor Java Method

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 constructor is invoked implicitly. The method is invoked explicitly.

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.

There are four types of Java access modifiers:

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.

Simple example of private access modifier

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.

Example of default access modifier

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.

1.​ //save by A.java


2.​ package pack;
3.​ class A{
4.​ void msg(){System.out.println("Hello");}
5.​ }
1.​ //save by B.java
2.​ package mypack;
3.​ import pack.*;
4.​ class B{
5.​ public static void main(String args[]){
6.​ A obj = new A();//Compile Time Error
7.​ obj.msg();//Compile Time Error
8.​ }
9.​ }
In the above example, the scope of class A and its method msg() is default 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.

It provides more accessibility than the default modifer.

Example of protected access modifier

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.

1.​ //save by A.java


2.​ package pack;
3.​ public class A{
4.​ protected void msg(){System.out.println("Hello");}
5.​ }
1.​ //save by B.java
2.​ package mypack;
3.​ import pack.*;
4.​
5.​ class B extends A{
6.​ public static void main(String args[]){
7.​ B obj = new B();
8.​ obj.msg();
9.​ }
10.​}
Output:Hello

4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.

Example of public access modifier

1.​ //save by A.java


2.​
3.​ package pack;
4.​ public class A{
5.​ public void msg(){System.out.println("Hello");}
6.​ }
1.​ //save by B.java
2.​
3.​ package mypack;
4.​ import pack.*;
5.​
6.​ class B{
7.​ public static void main(String args[]){
8.​ A obj = new A();
9.​ obj.msg();
10.​ }
11.​}
Output:Hello

Java Access Modifiers with Method Overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must
not be more restrictive.

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.

What are static members of a Java class?

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

What are final members in Java?

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

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

Java Data Types


Data types in Java are of different sizes and values that can be stored in the variable
that is made as per convenience and circumstances to cover up all test cases. Java has
two categories in which data types are segregated
1.​ Primitive Data Type: such as boolean, char, int, short, byte, long, float, and
double. The Boolean with uppercase B is a wrapper class for the primitive data
type boolean in Java.
2.​ Non-Primitive Data Type or Object Data type: such as String, Array, etc.
3.​ , let us explore different types of primitive and non-primitive data types.
4.​

Primitive Data Types in Java

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

‘a’, ‘\u0041’, characters representation of


Unicode 16
\u0000 ‘\101’, ‘\\’, ‘\’, ASCII values
character bits
char ‘\n’, ‘β’ 0 to 255
Example
Type Description Default Size Literals Range of values

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

IEEE 754 1.23e100f ,


32
floating 0.0 -1.23e-100f , upto 7 decimal digits
bits
float point .3f ,3.14F

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.

A local variable cannot be defined with "static" keyword.

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

Types of Operators in Java


1.​ Arithmetic Operators
2.​ Unary Operators
3.​ Assignment Operator
4.​ Relational Operators
5.​ Logical Operators
6.​ Ternary Operator
7.​ Bitwise Operators
8.​ Shift Operators
9.​ instance of operator

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

control flow in Java?


Control Flow Statement In Java: The mechanisms and tools that allow programmers to
control the way in which messages are passed within a Java program are referred to as
flow controls in Java. It enables developers to determine the program's behaviour
based on parameters or criteria.
Java provides three types of control flow statements.

1.​ Decision Making statements


o​ if statements
o​ switch statement

2.​ Loop statements


o​ do while loop
o​ while loop
o​ for loop
o​ for-each loop
3.​ Jump statements
o​ break statement
o​ continue statement

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.

Array Declaration Syntax:


typevar-name[]'
OR
type[] var-name;
An array declaration has two components: the type and the var-name.
The type declares the element type of the array. The element type determines the data
type of each element that comprises the array. The var-name declares the name of the
array variable. Like an array of int type, we can also create an array of other primitive
data types like char, float, double…etc.

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
.

An array is a data structure that A string is basically treated as an object


01. stores a collection of elements of which represents a sequence of
the same data type. characters. An array
Array can hold any of the data But, the String can hold only a char data
02.
types. type.

A string class contains a pointer to some


The elements of the array are
part of the heap memory where the
03. stored in a contiguous memory
actual contents of the string are stored
location.
in memory.

Java array not ended with a null


character, the end element of the But by default String is ended with null
04.
array is the last element of the (‘\0’) character in Java.
array.

05. Arrays are mutable. Strings are immutable.

06. The length of the array is fixed. The size of the string is not fixed.

Java - What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating objects
that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

●​ OOP is faster and easier to execute


●​ OOP provides a clear structure for the programs
●​ OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
●​ OOP makes it possible to create full reusable applications with less code and
shorter development time

Java - What are Classes and Objects?

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.

Why use inheritance in Java?

o​ For Method Overriding (so runtime polymorphism can be achieved).


o​ For Code Reusability.

Terms used in Inheritance

o​ Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
o​ Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
o​ Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o​ Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined in
the previous class.
The syntax of Java Inheritance
1.​ class Subclass-name extends Superclass-name
2.​ {
3.​ //methods and fields
4.​ }
The extends keyword indicates that we are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

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.

Types of Inheritance in Java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.


When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Single Inheritance
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single 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.​ 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.

Q) Why multiple inheritance is not supported in Java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

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.

2. Flexibility and Extensibility

Polymorphism allows subclasses to provide their own implementations of methods


defined in the superclass, making it easier to extend and customize behavior without
modifying existing code.

3. Dynamic Method Invocation:

Polymorphism enables dynamic method invocation, where the method called is


determined by the actual object type at runtime, providing flexibility in method
dispatch.

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:

Polymorphism is also achieved through method overloading, where multiple methods


with the same name but different parameter lists can be defined within a class or its
subclasses, enhancing code readability and allowing flexibility in method invocation
based on parameter types.

6. Reduced Code Complexity:

Polymorphism helps reduce code complexity by promoting a modular and hierarchical


class structure, making it easier to understand, maintain, and extend large-scale
software systems.

Types of Polymorphism

There are two types of polymorphism in Java:

1.​ Compile-time Polymorphism


2.​ Runtime Polymorphism.

We can perform polymorphism in Java by method overloading and method overriding.

1) Compile-Time Polymorphism in Java

In Java, method overloading is used to achieve compile-time polymorphism. A class


can have numerous methods with the same name but distinct parameter lists thanks to
method overloading. The compiler uses the amount and kind of parameters provided
to it during compilation to decide which method to call. This choice is made during
compilation, which is why it's called "compile-time 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

Method Overriding in Java


Method Overriding is a type of runtime polymorphism. In method overriding, a
method in a derived class has the same name, return type, and parameters as a method
in its parent class. The derived class provides a specific implementation for the
method that is already defined in the parent class.
Example of Method Overriding:
1.​ class Bike{
2.​ void run(){System.out.println("running");}
3.​ }
4.​ class Splendor extends Bike{
5.​ void run(){System.out.println("running safely with 60km");}
6.​ }
7.​ public class Main{
8.​ public static void main(String args[]){
9.​ Bike b = new Splendor();//upcasting
10.​ b.run();
11.​ }
12.​ }
13.​ Output:-
14.​ running safely with 60km
15.​

Difference Between Method Overloading and Method Overriding in Java


The differences between Method Overloading and Method Overriding in Java are as
follows:
Method Overloading Method Overriding

Method overloading is a Method overriding is a run-time


compile-time polymorphism. polymorphism.

Method overriding is used to grant the


Method overloading helps to increase specific implementation of the method
the readability of the program. which is already provided by its parent class
or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods


In method overriding, methods must have
must have the same name and
the same name and same signature.
different signatures.

In method overloading, the return


In method overriding, the return type must
type can or can not be the same, but
be the same or co-variant.
we just have to change the parameter.

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.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or
write-only. In other words, you can skip the getter or setter methods.

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

Abstract Class in Java


In the world of Java programming, abstract classes play an important role in defining
the structure of classes and their behavior in the hierarchy. They provide a blueprint
for other teams to follow, and some methods remain undefined. This flexibility
empowers developers to generate a well-organized and scalable codebase. In this
section, we will explore the concept of abstract classes in Java, examining their
features, advantages, and best practices.

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

o​ An abstract class must be declared with an abstract keyword.


o​ It can have abstract and non-abstract methods.
o​ It cannot be instantiated.
o​ It can have constructors and static methods also.
o​ It can have final methods which will force the subclass not to change the body
of the method.

Syntax of Abstract Classes


In Java, abstract classes are defined using the abstract keyword. Here's a basic syntax
example:

1.​ public abstract class Shape {


2.​ public abstract double area();
3.​ public void display() {
4.​ System.out.println("This is a shape.");
5.​ }
6.​ }
In this example, Shape is an abstract class with one abstract method area() and one
concrete method display(). Subclasses of Shape must implement the area() method,
but they can inherit the display() method.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as
an abstract method.

Example:- // Abstract class

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Cat extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The Cat says: Mew Mew ");

class Main {

public static void main(String[] args) {

Cat myCat = new Cat(); // Create a Cat object


myCat.animalSound();

myCat.sleep();

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

o​ Java Interface also represents the IS-A relationship.


o​ It cannot be instantiated just like the abstract class.
o​ Since Java 8, we can have default and static methods in an interface.
o​ Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

o​ It is used to achieve abstraction.


o​ By interface, we can support the functionality of multiple inheritance.
o​ It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by 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 the methods declared in the interface.

Relationship Between Classes and Interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
interface FirstInterface {

public void myMethod(); // interface method

interface SecondInterface {

public void myOtherMethod(); // interface method

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class Main {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

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.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package
The package keyword is used to create a package in java.

1.​ //save as Simple.java


2.​ package mypack;
3.​ public class Simple{
4.​ public static void main(String args[]){
5.​ System.out.println("Welcome to package");
6.​ }
7.​ }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1.​ javac -d directory javafilename


1.​ 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.Simpleetc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

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

How to access package from another package?


There are three ways to access the package from outside the package.

1.​ import package.*;


2.​ import package.classname;
3.​ fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example of package that import the packagename.*


1.​ //save by A.java
2.​ package pack;
3.​ public class A{
4.​ public void msg(){System.out.println("Hello");}
5.​ }
1.​ //save by B.java
2.​ package mypack;
3.​ import pack.*;
4.​
5.​ class B{
6.​ public static void main(String args[]){
7.​ A obj = new A();
8.​ obj.msg();
9.​ }
10.​}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.

Example of package by import package.classname


1.​ //save by A.java
2.​
3.​ package pack;
4.​ public class A{
5.​ public void msg(){System.out.println("Hello");}
6.​ }
1.​ //save by B.java
2.​ package mypack;
3.​ import pack.A;
4.​
5.​ class B{
6.​ public static void main(String args[]){
7.​ A obj = new A();
8.​ obj.msg();
9.​ }
10.​}
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.​
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name


1.​ //save by A.java
2.​ package pack;
3.​ public class A{
4.​ public void msg(){System.out.println("Hello");}
5.​ }
1.​ //save by B.java
2.​ package mypack;
3.​ class B{
4.​ public static void main(String args[]){
5.​ pack.A obj = new pack.A();//using fully qualified name
6.​ obj.msg();
7.​ }
8.​ }
Output:Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import
the subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java
that tells where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

●​ 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{}

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one public c
but keep the package name same. For example:

1.​ //save as A.java


2.​
3.​ package javatpoint;
4.​ public class A{}
1.​ //save as B.java
2.​
3.​ package javatpoint;
4.​ public class B{}

You might also like