0% found this document useful (0 votes)
10 views63 pages

Java Unit-1

The document outlines the syllabus for a Java programming course, covering topics such as Java's history, environment, and fundamental programming structures. It emphasizes Java's popularity, ease of learning, and versatility, while detailing the components of Java development including JDK, JRE, and JVM. Additionally, it provides insights into Java's syntax, class definitions, and methods, along with instructions for compiling and running Java programs.

Uploaded by

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

Java Unit-1

The document outlines the syllabus for a Java programming course, covering topics such as Java's history, environment, and fundamental programming structures. It emphasizes Java's popularity, ease of learning, and versatility, while detailing the components of Java development including JDK, JRE, and JVM. Additionally, it provides insights into Java's syntax, class definitions, and methods, along with instructions for compiling and running Java programs.

Uploaded by

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

1.

Syllabus 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

Java Introduction
Java is a general-purpose, object-oriented programming language that was designed by James
Gosling at Sun Microsystems in 1991. The compilation of the Java applications results in the
bytecode that can be run on any platform using the Java Virtual Machine. Because of this, Java
is also known as a WORA (Write Once, Run Anywhere) language.
Why Java
Top 10 Reasons to Learn Java

1. Java’s Popularity and High Salary

Java is one of the most popular programming languages in the world. It is used by some 9
million developers and it runs on around 7 billion devices worldwide according to Oracle
blogs.

2. Java is Easy to Learn

Java is quite easy to learn and can be understood in a short span of time as it has a syntax
similar to English.

3. Java has a Large Community

There is a large online community of Java users ranging from beginner, intermediate, and even
expert levels that are particularly helpful in case any support is required.

4. Java has an Abundant API

Java has an abundant Application Programming Interface (API) that includes many Java
classes, packages, interfaces, etc. This is useful for constructing applications without
necessarily knowing their inside implementations. Java has mainly three types of API
i.e. Official Java core APIs, Optional official Java APIs, and Unofficial APIs. These APIs
overall are used for almost everything including networking, I/O, databases, media, XML
parsing, speech synthesis, etc.
5. Java has Multiple Open Source Libraries

Open-source libraries have resources that can be copied, studied, changed, shared, etc. There
are multiple open source libraries in Java such as JHipster, Maven, Google Guava, Apache
Commons, etc. that can be used to make Java development easier, cheaper and faster.

6. Java has Powerful Development Tools

There are many Integrated development environments (IDEs) in Java that provide various
facilities for software development to programmers. Powerful Java IDEs such as Eclipse,
NetBeans, IntelliJ IDEA, etc. play a big role in the success of Java. These IDEs provide many
facilities such as debugging, syntax highlighting, code completion, language support,
automated refactoring, etc. that make coding in Java easier and faster. Java has created a base
for the Android operating system and opted around 90% of fortune 500 companies to develop a
lot of back-end applications. Also, it plays a great role in Apache Hadoop data processing,
Amazon Web Services, Windows Azure, etc.

7. Java is Free of Cost

One of the reasons Java is very popular among individual programmers is that it is available
under the Oracle Binary Code License (BCL) free of charge. This means that Java is free for
development and test environments, but for commercial purposes, a little pay is required.

8. Java is Platform Independent

Java is platform-independent as the Java source code is converted to byte code by the compiler
which can then be executed on any platform using the Java Virtual Machine. Java is also
known as a WORA (write once, run anywhere) language because it is platform-independent.
Also, the development of most Java applications occurs in a Windows environment while they
are run on a UNIX platform because of the platform-independent nature of Java.

9. Java has Great Documentation Support

The documentation support for Java is excellent using Javadoc which is the documentation
generator for Java. It uses the Java source code to generate the API documentation in HTML
format. So, Javadoc provides a great reference while coding in Java so that understanding the
code is quite simple.

10. Java is Versatile

Java is very versatile as it is used for programming applications on the web, mobile, desktop,
etc. using different platforms. Also, Java has many features such as dynamic coding, multiple
security features, platform-independent characteristics, network-centric designing, etc. that
make it quite versatile. It doesn’t matter if you are in high school or are in the first year of your
college, if you have the curiosity to learn to code, today is the day to start.
History of Java
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team was to create a
new project which can. Initially C++ was the original choice to develop the project. James
Gosling wanted to enhance C++ to achieve the target but due to high memory usage, that idea
was rejected and team started with a new language initially named as GreenTalk. The file
extension used as .gt. Later this language was termed as Oak and finally to Java.

Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office. Also,
Oak is an image of solidarity and picked as a national tree of numerous nations like the U.S.A.,
France, Germany, Romania, etc. But they had to later rename it as “JAVA” as it was already a
trademark by Oak Technologies.
Finally Java

Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by the team. James
Gosling tabled Java title based on type of espresso coffee bean. Java is an island in Indonesia
where new coffee was discovered termed as Java coffee. As per James Gosling, Java was among
the top choice along with Silk. Finally Java was selected as it was quite unique .

Sun released the first public implementation as Java 1.0 in 1996. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).

Java Version with Date


Version Release date Codename
JDK 1.0 23rd January 1996 Oak
JDK 1.1 18th February 1997
Playgrou
J2SE 1.2 4th December 1998 nd
J2SE 1.3 8th May 2000 Kestrel
J2SE 1.4 13th February 2002 Merlin
J2SE 5.0 30th September 2004 Tiger
Java SE 6 11th December 2006 Mustang
Java SE 7 28th July 2011 Dolphin
Java SE 8 18th March 2014 Spider.
Java SE 9 21st September 2017
Java SE 10 20th March 2018
Java SE 11 25th September 2018
Java SE 12 19th March 2019
Java SE 13 17th September 2019
Java SE 14 17th March 2020
Java SE 15 16th September 2020
Java SE 16 16th March 2021
Java SE 17 14th September 2021
Java SE 18 22nd March 2022
Java SE 19 20th September 2022
Java SE 20 21st March 2023
Java SE 21 19th September 2023

Java SE 22 19th March 2024


Java SE 23 17 September 2024
Java SE 24 18 March 2025
Java SE 25 September 2025
As of March 31, 2025, the latest version of the Java Development Kit (JDK) is JDK
24, released on March 18, 2025.

JDK in Java
The Java Development Kit (JDK) is a cross-platformed software development
environment that offers a collection of tools and libraries necessary for developing
Java-based software applications and applets. It is a core package used in Java,
along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment). It physically exists. It includes the Java Runtime Environment
(JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), and other tools needed in Java development.
JDK=JRE+Development Tools
One can easily install more than one version of JDK on the same computer. The Java
developers can make use of it on macOS, Windows, Linux, and Solaris.

What is JRE?

Java Run-time Environment (JRE) is the part of the Java Development Kit
(JDK). It is a freely available software distribution which has Java Class
Library, specific tools, and a stand-alone JVM. It is the most common
environment available on devices to run java programs. The source Java
code gets compiled and converted to Java bytecode. If you wish to run this
bytecode on any platform, you require JRE. The JRE loads classes, verify
access to memory, and retrieves the system resources. JRE acts as a layer on
the top of the operating system. It physically exists

JRE stands for “Java Runtime Environment” and may also be written as “Java
RTE.” The Java Runtime Environment provides the minimum requirements for
executing a Java application; it consists of the Java Virtual Machine (JVM), core
classes, and supporting files.

JVM

JVM (Java Virtual Machine) is an abstract machine(It means not real machine,
however, it acts like a machine. Not any machine but as a machine). It is called a
virtual machine because it doesn't physically exist. It is a specification that
provides a runtime environment in which Java bytecode can be executed. It
can also run those programs which are written in other languages and
compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JRE, and JDK
are platform dependent because the configuration of each OS is different
from each other. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.
Difference between JVM, JDK, and JRE

JVMs are not same for all hardware and software, for example for window os
JVM is different and for Linux VJM is different.

o
o

Structure of Java Program

Documentation Section

The documentation section is an important section but optional for a Java


program. It includes basic information about a Java program. The
information includes the author's name, date of creation, version,
program name, company name, and description of the program. To
write the statements in the documentation section, we use comments. The
comments may be single-line, multi-line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//).


For example:

1. //First Java Program


o Multi-line Comment: It starts with a /* and ends with */. We write
between these two symbols. For example:

1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends
with */. For example:

1. /**It is an example of documentation comment*/

Package Declaration

The package declaration is optional. It is placed just after the documentation


section. In this section, we declare the package name in which the class is
placed. For example:

package javatpoint; //where javatpoint is the package name


package com.javatpoint; //where com is the root directory and javatpoint is the
subdirectory

Import Statements

We use the import keyword to import the class. It is written before the class
declaration and after the package statement. For example:

import java.util.Scanner; //it imports the Scanner class only


import java.util.*; //it imports all the class of the java.util package

Interface Section

The interface in Java is a mechanism to achieve abstraction. It is an optional


section. We use the interface keyword to create an interface. An interface is
a slightly different from the class. It contains only method declaration.It cannot
have a method body.

interface car
{
void start();
void stop();
}

Class Definition

. We use the class keyword to define the class. The class is a blueprint of a
Java program. Every Java program has at least one class that contains the
main() method. For example:

class Student //class definition


{
}

Class Variables and Constants

In a Java program, the variables and constants are defined just after the
class definition. The variables and constants store values of the parameters.
It is used during the execution of the program. We can also decide and
define the scope of variables by using the modifiers. It defines the life of the
variables. For example:

class Student //class definition


{
String sname; //variable
int id;
double percentage;
}

Main Method Class

The execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class.

public static void main(String args[])


{
}

Methods and behavior

In this section, we define the functionality of the program by using


the methods. The methods are the set of instructions that we want to
perform. These instructions execute at runtime and perform the specified
task. For example:

public class Demo //class definition


{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}

How to compile a java program


Steps-
1. Create the program by typing it into a text editor and saving it to a file named,
say, MyProgram.java.
2. Compile it by typing "javac MyProgram.java" in the terminal window.
3. Execute (or run) it by typing "java MyProgram" in the terminal window.

To write the simple program, you need to open notepad by start


menu -> All Programs -> Accessories -> Notepad and write a
simple program as we have shown below:

o
o As displayed in the above diagram, write the simple program of Java in
notepad and saved it as Simple.java. In order to compile and run the
above program, you need to open the command prompt by start
menu -> All Programs -> Accessories -> command prompt.
When we have done with all the steps properly, it shows the following
output:
o

o To compile and run the above program, go to your current directory


first; my current directory is c:\new. Write here:

To compile: javac Simple.java


To execute: java Simple

What happens at compile time?

At compile time, the Java file is compiled by Java Compiler (It does not
interact with OS) and converts the Java code into bytecode.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Example 2:
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

Defining a Class in Java

Java provides a reserved keyword class to define a class. The keyword must
be followed by the class name. Inside the class, we declare methods and
variables.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by
convention).
4. 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.
5. 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.
6. Body: The class body surrounded by braces, { }.

Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
Example-
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It
means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as
the static method. The core advantage of the static method is that
there is no need to create an object to invoke the static method. The
main() method is executed by the JVM, so it doesn't require creating an
object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any
value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
We will discuss it in coming section.
o System.out.println() is used to print statement. Here, System is a
class, out is an object of the PrintStream class, println() is a method of
the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.

Java Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known
as functions.
Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the


method. It specifies the visibility of the method. Java provides four types of
access specifier:

o Public: The method is accessible by all classes when we use public


specifier in our application.
o Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
o Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible
only from the same package only.

o Return Type: Return type is a data type that the method returns. It
may have a primitive data type, object, collection, void, etc. If the
method does not return anything, we use void keyword.

o Method Name: It is a unique name that is used to define the name of


a method. It must be corresponding to the functionality of the method.
Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its
name.

o Parameter List: It is the list of parameters separated by a comma


and enclosed in the pair of parentheses. It contains the data type and
variable name. If the method has no parameter, left the parentheses
blank.

o Method Body: It is a part of the method declaration. It contains all the


actions to be performed. It is enclosed within the pair of curly braces.

Types of Method

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When
we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already
stored in the library.

Each and every predefined method is defined inside a class. Such


as print() method is defined in the java.io.PrintStream class. It prints the
statement that we write inside the method. For example, print("Java"), it
prints Java on the console.

Let's see an example of the predefined method.

Demo.java

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

User-defined Method

The method written by the user or programmer is known as a user-


defined method. These methods are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd.
First, we will define the method.

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();
}

// Outputs "I just got executed!"

Addition.java

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Output:

The sum of a and b is= 24

Methods in Java can also be classified into the following types:

 Static Method
 Instance Method
 Abstract Method
Static Method

A method that has static keyword is known as static method. In other words,
a method that belongs to a class rather than an instance of a class is known
as a static method. We can also create a static method by using the
keyword static before the method name.

The main advantage of a static method is that we can call it without creating
an object. It can access static data members and also change the value of it.
It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.

Example of static method

Display.java

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
11. }

Output:

Instance Method

The method of the class is known as an instance method. It is a non-


static method defined in the class. Before calling or invoking the instance
method, it is necessary to create an object of its class. Let's see an example
of an instance method.

InstanceMethodExample.java

public class InstanceMethodExample


{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}

Output:

The sum is: 25

Abstract Method

The method that does not has method body is known as abstract method. In
other words, without an implementation is known as abstract method. It
always declares in the abstract class. It means the class itself must be
abstract if it has abstract method. To create an abstract method, we use the
keyword abstract.

Syntax

abstract void method_name();

Example of abstract method

Demo.java

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}

Output:
Abstract method...
Access Modifiers in Java

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.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Java static keyword

The static keyword in Java is used for memory management mainly. We


can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.

static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once,
if any object changes the value of the static variable, it will retain its value.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output-
1
2
3
Constructors in Java

In Java, a constructor 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.

Rules for creating Java constructor

There are two rules defined for the 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

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any


parameter.

Syntax of default constructor:


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.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.
How Java Constructors are Different From Java Methods?
 Constructors must have the same name as the class within which it is defined it is
not necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type or void if
does not return any value.
 Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.

Operators in Java

Operator in Java is a symbol that is used to perform operations. For


example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence


Operator Category Precedence
Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &


bitwise exclusive ^
OR

bitwise inclusive |
OR

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular class.
For example,

class Main {

public static void main(String[] args) {

String str = "Programiz";

boolean result;

// checks if str is an instance of

// the String class

result = str instanceof String;

System.out.println("Is str an object of String? " + result);

}
}
Output

Is str an object of String? true

Java Data Types

Data types are divided into two groups:


 Primitive data types -
includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes (you will
learn more about these in a later chapter)

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it
has no additional methods.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values


Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123
or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

Example

int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Java Type Casting

Type casting is when you assign a value of one primitive data type to
another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a


larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller


size type
double -> float -> long -> int -> char -> short -> byte

Example1- Widening Casting

public class Main {

public static void main(String[] args) {


int myInt = 9;

double myDouble = myInt; // Automatic casting: int to


double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Example2- Narrowing Casting

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variableName = value;

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


System.out.println(myNum)

Types of Variables in Java


1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.
3. Static Variables
Static variables are also known as class variables.
 These variables are declared similarly to instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor, or block.
public class A
{
static int m=100;//static variable
public String name; //public instance
String division; //default instance
private int age; //private instance

void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//local variable
}
}//end of class

Final Variables

If you don't want others (or yourself) to overwrite existing values, use
the final keyword (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):

Example

final int myNum = 15;

myNum = 20; // will generate an error: cannot assign a value to


a final variable
Control Flow in Java

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

Java If-else Statement

The Java if statement is used to test the condition. It


checks boolean condition: true or false. There are various types of if
statement in Java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition
is true.

Syntax:

if(condition){
//code to be executed
}

Java if-else Statement

The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.

Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple


statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Java Nested if statement


The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when outer if block condition is
true.

Syntax:

if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Java Switch Statement

The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement. The switch statement works with byte,
short, int, long, enum types, String and some wrapper types like Byte, Short,
Int, and Long. Since Java 7, you can use strings in the switch statement.

Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Loops in Java

for Loop
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

Java Nested for Loop


If we have a for loop inside the another loop, it is known as nested for loop.
The inner loop executes completely whenever outer loop executes.

Java While Loop

The Java while loop is used to iterate a part of the program repeatedly until
the specified Boolean condition is true. As soon as the Boolean condition
becomes false, the loop automatically stops.

The while loop is considered as a repeating if statement. If the number of


iteration is not fixed, it is recommended to use the while loop.

Syntax:

while (condition){
//code to be executed
I ncrement / decrement statement
}
Java do-while Loop

The Java do-while loop is used to iterate a part of the program repeatedly,
until the specified condition is true. If the number of iteration is not fixed and
you must have to execute the loop at least once, it is recommended to use a
do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike while
loop and for loop, the do-while check the condition at the end of loop body.
The Java do-while loop is executed at least once because condition is
checked after loop body.
Syntax:

do{
//code to be executed / loop body
//update statement
}while (condition);
Java Break Statement

When a break statement is encountered inside a loop, the loop is


immediately terminated and the program control resumes at the next
statement following the loop.

The Java break statement is used to break loop or switch statement. It


breaks the current flow of the program at specified condition. In case of inner
loop, it breaks only inner loop.

We can use Java break statement in all types of loops such as for loop, while
loop and do-while loop.

Syntax:

break;

for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}

Output:
1
2
3
4
Java Continue Statement

The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for
loop or while loop.

The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.
Syntax:

continue;

for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}

Test it Now

Output:

1
2
3
4
6
7
8
9
10
Java Comments

The Java comments are the statements in a program that are not executed
by the compiler and interpreter.

Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment

The single-line comment is used to comment only one line of the code.

Syntax:

//This is single line comment

2) Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code.


Syntax:

/*
This
is
multi line
comment
*/

3) Java Documentation Comment

Documentation comments are usually used to write large programs for a


project or software application as it helps to create documentation API.
These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The


documentation comments are placed between /** and */.

1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
Java Arrays

Normally, an array is a collection of similar type of elements which has


contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Example-
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//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();
}
}}
Java 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','o','i','n','t'};
String s=new String(ch);

is same as:

String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object


that represents a sequence of characters. The java.lang.String class is used
to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Note: String objects are stored in a special memory area known as the "string constant
pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference var
iable

In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).

Java String Example

StringExample.java

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Java OOPs Concepts

Simula is considered the first object-oriented programming language. The


programming paradigm where everything is represented as an object is
known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming


language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

Object means a real-world entity such as a pen, chair, table, computer,


watch, etc. Object-Oriented Programming is a methodology or paradigm
to design a program using classes and objects.

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class.

Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviors of a parent object,
it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For


example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different
medicines.

A java class is the example of encapsulation. Java bean is the fully


encapsulated class because all the data members are private here.

Top Advantages of OOP

Let us now look at the various OOPS advantages.

 Modularity: OOP divides complex systems into smaller components, making the
codebase easier to comprehend, create, and maintain.
 Reusability: Inheritance allows code reuse, improving code quality and saving time.
 Encapsulation: Protects data integrity and privacy by restricting direct access and
allowing controlled access through methods.
 Flexibility and Scalability: OOP enables easy addition and modification of features
without impacting the entire codebase.
 Code Organization: OOP promotes a structured approach, enhancing collaboration and
code readability.
 Code Maintenance: Changes and bug fixes can be made to specific objects or classes
without affecting other parts of the system, reducing errors and improving debugging.
 Code Reusability: OOP encourages the development of reusable code elements, saving
time and improving system reliability.
 Better Problem Solving: OOP models real-world systems, allowing developers to create
intuitive solutions that closely mimic real-world circumstances.

Disadvantages of OOP

 Increased complexity: OOP's emphasis on modularity and code organization can make
larger projects more challenging to understand and maintain.
 Performance overhead: OOP languages often have a performance cost compared to
procedural languages due to the additional abstraction layers introduced by objects and
encapsulation.
 Dependency management: Inheritance and code reuse in OOP can create
interdependencies among classes, making it difficult to manage changes and maintain
overall functionality.
 Overuse of inheritance: Improper use of inheritance can lead to complex class
hierarchies and tightly coupled classes, making code maintenance and modifications
more difficult in the future.

Syntax to declare a class:


class <class_name>{
field;
method;
}
How to Create Object in Java

Using new Keyword

Using the new keyword is the most popular way to create an object or
instance of the class. When we create an instance of the class by using the
new keyword, it allocates memory (heap) for the newly created object and
also returns the reference of that object to that memory. The new keyword
is also used to create an array. The syntax for creating an object is:

ClassName object = new ClassName();

CreateObjectExample1.java

public class CreateObjectExample1


{
void show()
{
System.out.println("Welcome to java");
}
public static void main(String[] args)
{
//creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
//invoking method using the object
obj.show();
}
}

Output:

Welcome to java

By using the new keyword, we can also invoke the constructor (default or
parametrized) of the class.

CreateObjectExample2.java

public class CreateObjectExample2


{
//constructor of the class
CreateObjectExample2()
{
System.out.println("Welcome to java");
}
public static void main(String[] args)
{
//creating an object using new keyword
CreateObjectExample2 obj = new CreateObjectExample2();
}
}

Output:

Welcome to java
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

Why use inheritance in java


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

Terms used in Inheritance


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


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.

In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

As displayed in the above 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=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class
as well as of Employee class i.e. code reusability.

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.

Single Inheritance Example

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.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...

Multilevel Inheritance Example

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.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

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.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


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

Consider a scenario where A, B, and C are three classes. The C class inherits
A and B classes. If A and B classes have the same method and you call it
from child class object, there will be ambiguity to call the method of A or B
class.

Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
Method Overloading in Java

If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method
only.
1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.

In this example, we are creating static methods so that we don't need to


create instance for calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Test it Now

Output:

22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The
first add method receives two integer arguments and second add method
receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Test it Now

Output:

22
24.9
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the


method that has been declared by one of its parent class, it is known as
method overriding.

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Test it Now

Output:

Bike is running safely


No. Method Overloading Method Overriding
1) Method overloading is Method overriding occurs in two
performed within class. classes that have IS-A (inheritance)
relationship.

2) In case of method In case of method


overloading, parameter must be overriding, parameter must be
different. same.

3) Method overloading is the Method overriding is the example


example of compile time of run time polymorphism.
polymorphism.

Encapsulation in Java

Encapsulation helps to hide data by preventing unauthorized access to the implementation


details.

What is Encapsulation in Java?

Data Encapsulation can be defined as wrapping the code or methods(properties) and the related
fields or variables together as a single unit. In object-oriented programming, we call this single
unit - a class, interface, etc.

Achieving Encapsulation in Java

To achieve encapsulation in Java −

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the
variables values.

Access Within Within Same Package by Outside Package


Global
Modifier Class Package Subclasses by Subclasses
Public Yes Yes Yes Yes Yes
Protected Yes Yes Yes Yes No
Default Yes Yes Yes No No
Private Yes No No No No
A Private Access Modifier is used for the purpose of Data Hiding.

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.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism.
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a
function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method overriding,

Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces

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


o It can have abstract and non-abstract methods.
o Abstract methods are methods with no implementation. They do not
contain any method statement.
o

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Test it Now
running safely
Interface in Java
An interface in Java is a blueprint of a class. 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.

Java Interface also represents the IS-A relationship.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.

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.

Syntax:
interface <interface_name>{

// declare methods that abstract


}

The relationship between classes and interfaces

Java Interface Example

In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Test it Now

Output:

Hello

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Test it Now
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but it is possible by an
interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not


supported in the case of class because of ambiguity. However, it is supported
in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class.

Abstract class Interface

1) Abstract class can have Interface can have only


abstract and non- abstract methods. Since Java 8, it
abstract methods. can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used The interface keyword is used to


to declare abstract class. declare interface.

6) An abstract class can extend An interface can extend another


another Java class and implement Java interface only.
multiple Java interfaces.

7) An abstract class can be An interface can be implemented


extended using keyword using keyword "implements".
"extends".

8) A Java abstract class can have Members of a Java interface are


class members like private, public by default.
protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java Package

A java package is a group of similar types of classes, interfaces and sub-


packages.
Package in java can be categorized in two form, built-in package and user-
defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

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

javac -d directory javafilename


For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case
of windows) etc. If you want to keep the package within the same directory,
you can use . (dot).
How to run java package program

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

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


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

How to access package from another package?

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

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.

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

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

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


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//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();
}
}
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.

Package Naming Convention


A package name is made up of the reverse of the Internet Domain Name (to
ensure uniqueness) plus your own organization's internal project name,
separated by dots '.'. Package names are in lowercase. For example,
suppose that your Internet Domain Name is "zzz.com", you can name your
package as "com.zzz.project1.subproject2".
The prefix "java" and "javax" are reserved for core Java packages and Java
extensions, respectively.
CLASSPATH - For Locating Classes
CLASSPATH is an environment variable (i.e., global variables of the operating
system available to all the processes) needed for the Java compiler and
runtime to locate the Java packages/classes used in a Java program. (Why
not call PACKAGEPATH?) This is similar to another environment variable PATH,
which is used by the Command shell to find the executable programs.
CLASSPATH can be set in one of the following ways:

choose control panel ⇒ System ⇒ Advanced ⇒ Environment Variables


1. CLASSPATH can be set permanently in the environment: In Windows,

⇒ choose "System Variables" (for all the users) or "User Variables" (only
the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists)
or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the
required directories and JAR files (separated by semicolons) as the value
(e.g., ".;c:\myProject\classes;d:\tomcat\lib\servlet-api.jar").
Take note that you need to include the current working directory
(denoted by '.') in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following
command:
> SET CLASSPATH
NOTE: For Unixes and Mac OS X: Use forward slash '/' as the directory
separator and ':' as the path seperator, e.g.,
".:/usr/local/myproject/classes:/usr/local/tomcat/lib/servle
t-api.jar".

2. CLASSPATH can be set temporarily for that particular CMD shell session
by issuing the following command:
3. > SET CLASSPATH=.;c:\myProject\classes;d:\tomcat\lib\
servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use
the command-line option -classpath (or -cp) of
the javac and java commands, for example,
> java –classpath c:\myProject\classes
com.abc.project1.subproject2.MyClass3
Java Create Jar Files

We can either download the JAR files from the browser or can write our own
JAR files using Eclipse IDE.

The steps to bundle the source code, i.e., .java files, into a JAR are given
below. In this section, we only understand how we can create JAR files using
eclipse IDE. In the following steps, we don't cover how we can create an
executable JAR in Java.

1. In the first step, we will open Eclipse IDE and select the Export option
from the File When we select the Export option, the Jar File wizard
opens with the following screen:
2. From the open wizard, we select the Java JAR file and click on
the Next The Next button opens JAR Export for JAR File Specification.
3. Now, from the JAR File Specification page, we select the resources
needed for exporting in the Select the resources to export After
that, we enter the JAR file name and folder. By default, the Export
generated class files and resources checkbox is checked. We also
check the Export Java source files and resources checkbox to
export the source code.
If there are other Java files or resources which we want to include and
which are available in the open project, browse to their location and
ensure the file or resource is checked in the window on the right.
4. On the same page, there are three more checkboxes, i.e., Compress
the content of the JAR file, Add directory entries, and Overwrite
existing files without warning. By default, the Compress content
of the JAR file checkbox is checked.
5. Now, we have two options for proceeding next, i.e., Finish and Next. If
we click on the Next, it will immediately create a JAR file to that
location which we defined in the Select the export destination. If
we click on the Next button, it will open the Jar Packaging
Option wizard for creating a JAR description, setting the advance
option, or changing the default manifest.
For now, we skip
the Next and click on the Finish button.
6. Now, we go to the specified location, which we defined in the Select
the export destination, to ensure that the JAR file is created
successfully or not.

Static import in Java


In Java, static import concept is introduced in 1.5 version. With the help of static
import, we can access the static members of a class directly without class name or
any object. For Example: we always use sqrt() method of Math class by using Math
class i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance
coding. But according to the programming experts, it will lead to confusion and not
good for programming. If there is no specific requirement then we should not go for
static import.
Advantage of static import:
If user wants to access any static member of class then less coding is required.
Disadvantage of static import:
Static import makes the program unreadable and unmaintainable if you are reusing
this feature.
// Java Program to illustrate
// calling of predefined methods
// without static import
class Geeks {
public static void main(String[] args)
{
System.out.println(Math.sqrt(4));
System.out.println(Math.pow(2, 2));
System.out.println(Math.abs(6.3));
}
}
Output:

2.0
4.0
6.3
// Java Program to illustrate
// calling of predefined methods
// with static import
import static java.lang.Math.*;
class Test2 {
public static void main(String[] args)
{
System.out.println(sqrt(4));
System.out.println(pow(2, 2));
System.out.println(abs(6.3));
}
}
Output:

2.0
4.0
6.3
Naming Conventions

For avoiding unwanted package names, we have some following naming


conventions which we use in creating a package.

o The name should always be in the lower case.


o They should be period-delimited.
o The names should be based on the company or organization name.

In order to define a package name based on an organization, we'll first


reverse the company URL. After that, we define it by the company and
include division names and project names.

For example, if we want to create a package out of www.javatpoint.com, we


will reserve it in the following way:

1. com.javatpoint

If we want to define a sub-package of the com.javatpoint, we will do it in


the following way:

1. com.javatpoint.examples

You might also like